Make SSL_write_early_finish() an internal only function
[openssl.git] / ssl / statem / statem.c
1 /*
2  * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <openssl/rand.h>
11 #include "../ssl_locl.h"
12 #include "statem_locl.h"
13
14 /*
15  * This file implements the SSL/TLS/DTLS state machines.
16  *
17  * There are two primary state machines:
18  *
19  * 1) Message flow state machine
20  * 2) Handshake state machine
21  *
22  * The Message flow state machine controls the reading and sending of messages
23  * including handling of non-blocking IO events, flushing of the underlying
24  * write BIO, handling unexpected messages, etc. It is itself broken into two
25  * separate sub-state machines which control reading and writing respectively.
26  *
27  * The Handshake state machine keeps track of the current SSL/TLS handshake
28  * state. Transitions of the handshake state are the result of events that
29  * occur within the Message flow state machine.
30  *
31  * Overall it looks like this:
32  *
33  * ---------------------------------------------            -------------------
34  * |                                           |            |                 |
35  * | Message flow state machine                |            |                 |
36  * |                                           |            |                 |
37  * | -------------------- -------------------- | Transition | Handshake state |
38  * | | MSG_FLOW_READING | | MSG_FLOW_WRITING | | Event      | machine         |
39  * | | sub-state        | | sub-state        | |----------->|                 |
40  * | | machine for      | | machine for      | |            |                 |
41  * | | reading messages | | writing messages | |            |                 |
42  * | -------------------- -------------------- |            |                 |
43  * |                                           |            |                 |
44  * ---------------------------------------------            -------------------
45  *
46  */
47
48 /* Sub state machine return values */
49 typedef enum {
50     /* Something bad happened or NBIO */
51     SUB_STATE_ERROR,
52     /* Sub state finished go to the next sub state */
53     SUB_STATE_FINISHED,
54     /* Sub state finished and handshake was completed */
55     SUB_STATE_END_HANDSHAKE
56 } SUB_STATE_RETURN;
57
58 static int state_machine(SSL *s, int server);
59 static void init_read_state_machine(SSL *s);
60 static SUB_STATE_RETURN read_state_machine(SSL *s);
61 static void init_write_state_machine(SSL *s);
62 static SUB_STATE_RETURN write_state_machine(SSL *s);
63
64 OSSL_HANDSHAKE_STATE SSL_get_state(const SSL *ssl)
65 {
66     return ssl->statem.hand_state;
67 }
68
69 int SSL_in_init(SSL *s)
70 {
71     return s->statem.in_init;
72 }
73
74 int SSL_is_init_finished(SSL *s)
75 {
76     return !(s->statem.in_init) && (s->statem.hand_state == TLS_ST_OK);
77 }
78
79 int SSL_in_before(SSL *s)
80 {
81     /*
82      * Historically being "in before" meant before anything had happened. In the
83      * current code though we remain in the "before" state for a while after we
84      * have started the handshake process (e.g. as a server waiting for the
85      * first message to arrive). There "in before" is taken to mean "in before"
86      * and not started any handshake process yet.
87      */
88     return (s->statem.hand_state == TLS_ST_BEFORE)
89         && (s->statem.state == MSG_FLOW_UNINITED);
90 }
91
92 /*
93  * Clear the state machine state and reset back to MSG_FLOW_UNINITED
94  */
95 void ossl_statem_clear(SSL *s)
96 {
97     s->statem.state = MSG_FLOW_UNINITED;
98     s->statem.hand_state = TLS_ST_BEFORE;
99     s->statem.in_init = 1;
100     s->statem.no_cert_verify = 0;
101 }
102
103 /*
104  * Set the state machine up ready for a renegotiation handshake
105  */
106 void ossl_statem_set_renegotiate(SSL *s)
107 {
108     s->statem.in_init = 1;
109     s->statem.request_state = TLS_ST_SW_HELLO_REQ;
110 }
111
112 /*
113  * Put the state machine into an error state. This is a permanent error for
114  * the current connection.
115  */
116 void ossl_statem_set_error(SSL *s)
117 {
118     s->statem.state = MSG_FLOW_ERROR;
119 }
120
121 /*
122  * Discover whether the current connection is in the error state.
123  *
124  * Valid return values are:
125  *   1: Yes
126  *   0: No
127  */
128 int ossl_statem_in_error(const SSL *s)
129 {
130     if (s->statem.state == MSG_FLOW_ERROR)
131         return 1;
132
133     return 0;
134 }
135
136 void ossl_statem_set_in_init(SSL *s, int init)
137 {
138     s->statem.in_init = init;
139 }
140
141 int ossl_statem_get_in_handshake(SSL *s)
142 {
143     return s->statem.in_handshake;
144 }
145
146 void ossl_statem_set_in_handshake(SSL *s, int inhand)
147 {
148     if (inhand)
149         s->statem.in_handshake++;
150     else
151         s->statem.in_handshake--;
152 }
153
154 /* Are we in a sensible state to skip over unreadable early data? */
155 int ossl_statem_skip_early_data(SSL *s)
156 {
157     if (s->ext.early_data != SSL_EARLY_DATA_REJECTED)
158         return 0;
159
160     if (s->hello_retry_request) {
161         if (s->statem.hand_state != TLS_ST_SW_HELLO_RETRY_REQUEST)
162             return 0;
163     } else {
164         if (!s->server || s->statem.hand_state != TLS_ST_EARLY_DATA)
165             return 0;
166     }
167
168     return 1;
169 }
170
171 /*
172  * Called when we are in SSL_read*(), SSL_write*(), or SSL_accept()
173  * /SSL_connect()/SSL_do_handshake(). Used to test whether we are in an early
174  * data state and whether we should attempt to move the handshake on if so.
175  * |send| is 1 if we are attempting to send data (SSL_write*()), 0 if we are
176  * attempting to read data (SSL_read*()), or -1 if we are in SSL_do_handshake()
177  * or similar.
178  */
179 void ossl_statem_check_finish_init(SSL *s, int send)
180 {
181     if (send == -1) {
182         if (s->statem.hand_state == TLS_ST_PENDING_EARLY_DATA_END
183                 || s->statem.hand_state == TLS_ST_EARLY_DATA)
184             ossl_statem_set_in_init(s, 1);
185     } else if (!s->server) {
186         if ((send && s->statem.hand_state == TLS_ST_PENDING_EARLY_DATA_END
187                   && s->early_data_state != SSL_EARLY_DATA_WRITING)
188                 || (!send && s->statem.hand_state == TLS_ST_EARLY_DATA))
189             ossl_statem_set_in_init(s, 1);
190     } else {
191         if (s->early_data_state == SSL_EARLY_DATA_FINISHED_READING
192                 && s->statem.hand_state == TLS_ST_EARLY_DATA)
193             ossl_statem_set_in_init(s, 1);
194     }
195 }
196
197 void ossl_statem_set_hello_verify_done(SSL *s)
198 {
199     s->statem.state = MSG_FLOW_UNINITED;
200     s->statem.in_init = 1;
201     /*
202      * This will get reset (briefly) back to TLS_ST_BEFORE when we enter
203      * state_machine() because |state| is MSG_FLOW_UNINITED, but until then any
204      * calls to SSL_in_before() will return false. Also calls to
205      * SSL_state_string() and SSL_state_string_long() will return something
206      * sensible.
207      */
208     s->statem.hand_state = TLS_ST_SR_CLNT_HELLO;
209 }
210
211 int ossl_statem_connect(SSL *s)
212 {
213     return state_machine(s, 0);
214 }
215
216 int ossl_statem_accept(SSL *s)
217 {
218     return state_machine(s, 1);
219 }
220
221 typedef void (*info_cb) (const SSL *, int, int);
222
223 static info_cb get_callback(SSL *s)
224 {
225     if (s->info_callback != NULL)
226         return s->info_callback;
227     else if (s->ctx->info_callback != NULL)
228         return s->ctx->info_callback;
229
230     return NULL;
231 }
232
233 /*
234  * The main message flow state machine. We start in the MSG_FLOW_UNINITED or
235  * MSG_FLOW_FINISHED state and finish in MSG_FLOW_FINISHED. Valid states and
236  * transitions are as follows:
237  *
238  * MSG_FLOW_UNINITED     MSG_FLOW_FINISHED
239  *        |                       |
240  *        +-----------------------+
241  *        v
242  * MSG_FLOW_WRITING <---> MSG_FLOW_READING
243  *        |
244  *        V
245  * MSG_FLOW_FINISHED
246  *        |
247  *        V
248  *    [SUCCESS]
249  *
250  * We may exit at any point due to an error or NBIO event. If an NBIO event
251  * occurs then we restart at the point we left off when we are recalled.
252  * MSG_FLOW_WRITING and MSG_FLOW_READING have sub-state machines associated with them.
253  *
254  * In addition to the above there is also the MSG_FLOW_ERROR state. We can move
255  * into that state at any point in the event that an irrecoverable error occurs.
256  *
257  * Valid return values are:
258  *   1: Success
259  * <=0: NBIO or error
260  */
261 static int state_machine(SSL *s, int server)
262 {
263     BUF_MEM *buf = NULL;
264     unsigned long Time = (unsigned long)time(NULL);
265     void (*cb) (const SSL *ssl, int type, int val) = NULL;
266     OSSL_STATEM *st = &s->statem;
267     int ret = -1;
268     int ssret;
269
270     if (st->state == MSG_FLOW_ERROR) {
271         /* Shouldn't have been called if we're already in the error state */
272         return -1;
273     }
274
275     RAND_add(&Time, sizeof(Time), 0);
276     ERR_clear_error();
277     clear_sys_error();
278
279     cb = get_callback(s);
280
281     st->in_handshake++;
282     if (!SSL_in_init(s) || SSL_in_before(s)) {
283         if (!SSL_clear(s))
284             return -1;
285     }
286 #ifndef OPENSSL_NO_SCTP
287     if (SSL_IS_DTLS(s)) {
288         /*
289          * Notify SCTP BIO socket to enter handshake mode and prevent stream
290          * identifier other than 0. Will be ignored if no SCTP is used.
291          */
292         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
293                  st->in_handshake, NULL);
294     }
295 #endif
296
297     /* Initialise state machine */
298     if (st->state == MSG_FLOW_UNINITED
299             || st->state == MSG_FLOW_FINISHED) {
300         if (st->state == MSG_FLOW_UNINITED) {
301             st->hand_state = TLS_ST_BEFORE;
302             st->request_state = TLS_ST_BEFORE;
303         }
304
305         s->server = server;
306         if (cb != NULL)
307             cb(s, SSL_CB_HANDSHAKE_START, 1);
308
309         if (SSL_IS_DTLS(s)) {
310             if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00) &&
311                 (server || (s->version & 0xff00) != (DTLS1_BAD_VER & 0xff00))) {
312                 SSLerr(SSL_F_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
313                 goto end;
314             }
315         } else {
316             if ((s->version >> 8) != SSL3_VERSION_MAJOR) {
317                 SSLerr(SSL_F_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
318                 goto end;
319             }
320         }
321
322         if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
323             SSLerr(SSL_F_STATE_MACHINE, SSL_R_VERSION_TOO_LOW);
324             goto end;
325         }
326
327         if (s->init_buf == NULL) {
328             if ((buf = BUF_MEM_new()) == NULL) {
329                 goto end;
330             }
331             if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
332                 goto end;
333             }
334             s->init_buf = buf;
335             buf = NULL;
336         }
337
338         if (!ssl3_setup_buffers(s)) {
339             goto end;
340         }
341         s->init_num = 0;
342
343         /*
344          * Should have been reset by tls_process_finished, too.
345          */
346         s->s3->change_cipher_spec = 0;
347
348         /*
349          * Ok, we now need to push on a buffering BIO ...but not with
350          * SCTP
351          */
352 #ifndef OPENSSL_NO_SCTP
353         if (!SSL_IS_DTLS(s) || !BIO_dgram_is_sctp(SSL_get_wbio(s)))
354 #endif
355             if (!ssl_init_wbio_buffer(s)) {
356                 goto end;
357             }
358
359         if ((SSL_in_before(s))
360                 || s->renegotiate) {
361             if (!tls_setup_handshake(s)) {
362                 ossl_statem_set_error(s);
363                 goto end;
364             }
365
366             if (SSL_IS_FIRST_HANDSHAKE(s))
367                 st->read_state_first_init = 1;
368         }
369
370         st->state = MSG_FLOW_WRITING;
371         init_write_state_machine(s);
372     }
373
374     while (st->state != MSG_FLOW_FINISHED) {
375         if (st->state == MSG_FLOW_READING) {
376             ssret = read_state_machine(s);
377             if (ssret == SUB_STATE_FINISHED) {
378                 st->state = MSG_FLOW_WRITING;
379                 init_write_state_machine(s);
380             } else {
381                 /* NBIO or error */
382                 goto end;
383             }
384         } else if (st->state == MSG_FLOW_WRITING) {
385             ssret = write_state_machine(s);
386             if (ssret == SUB_STATE_FINISHED) {
387                 st->state = MSG_FLOW_READING;
388                 init_read_state_machine(s);
389             } else if (ssret == SUB_STATE_END_HANDSHAKE) {
390                 st->state = MSG_FLOW_FINISHED;
391             } else {
392                 /* NBIO or error */
393                 goto end;
394             }
395         } else {
396             /* Error */
397             ossl_statem_set_error(s);
398             goto end;
399         }
400     }
401
402     ret = 1;
403
404  end:
405     st->in_handshake--;
406
407 #ifndef OPENSSL_NO_SCTP
408     if (SSL_IS_DTLS(s)) {
409         /*
410          * Notify SCTP BIO socket to leave handshake mode and allow stream
411          * identifier other than 0. Will be ignored if no SCTP is used.
412          */
413         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
414                  st->in_handshake, NULL);
415     }
416 #endif
417
418     BUF_MEM_free(buf);
419     if (cb != NULL) {
420         if (server)
421             cb(s, SSL_CB_ACCEPT_EXIT, ret);
422         else
423             cb(s, SSL_CB_CONNECT_EXIT, ret);
424     }
425     return ret;
426 }
427
428 /*
429  * Initialise the MSG_FLOW_READING sub-state machine
430  */
431 static void init_read_state_machine(SSL *s)
432 {
433     OSSL_STATEM *st = &s->statem;
434
435     st->read_state = READ_STATE_HEADER;
436 }
437
438 static int grow_init_buf(SSL *s, size_t size) {
439
440     size_t msg_offset = (char *)s->init_msg - s->init_buf->data;
441
442     if (!BUF_MEM_grow_clean(s->init_buf, (int)size))
443         return 0;
444
445     if (size < msg_offset)
446         return 0;
447
448     s->init_msg = s->init_buf->data + msg_offset;
449
450     return 1;
451 }
452
453 /*
454  * This function implements the sub-state machine when the message flow is in
455  * MSG_FLOW_READING. The valid sub-states and transitions are:
456  *
457  * READ_STATE_HEADER <--+<-------------+
458  *        |             |              |
459  *        v             |              |
460  * READ_STATE_BODY -----+-->READ_STATE_POST_PROCESS
461  *        |                            |
462  *        +----------------------------+
463  *        v
464  * [SUB_STATE_FINISHED]
465  *
466  * READ_STATE_HEADER has the responsibility for reading in the message header
467  * and transitioning the state of the handshake state machine.
468  *
469  * READ_STATE_BODY reads in the rest of the message and then subsequently
470  * processes it.
471  *
472  * READ_STATE_POST_PROCESS is an optional step that may occur if some post
473  * processing activity performed on the message may block.
474  *
475  * Any of the above states could result in an NBIO event occurring in which case
476  * control returns to the calling application. When this function is recalled we
477  * will resume in the same state where we left off.
478  */
479 static SUB_STATE_RETURN read_state_machine(SSL *s)
480 {
481     OSSL_STATEM *st = &s->statem;
482     int ret, mt;
483     size_t len = 0;
484     int (*transition) (SSL *s, int mt);
485     PACKET pkt;
486     MSG_PROCESS_RETURN(*process_message) (SSL *s, PACKET *pkt);
487     WORK_STATE(*post_process_message) (SSL *s, WORK_STATE wst);
488     size_t (*max_message_size) (SSL *s);
489     void (*cb) (const SSL *ssl, int type, int val) = NULL;
490
491     cb = get_callback(s);
492
493     if (s->server) {
494         transition = ossl_statem_server_read_transition;
495         process_message = ossl_statem_server_process_message;
496         max_message_size = ossl_statem_server_max_message_size;
497         post_process_message = ossl_statem_server_post_process_message;
498     } else {
499         transition = ossl_statem_client_read_transition;
500         process_message = ossl_statem_client_process_message;
501         max_message_size = ossl_statem_client_max_message_size;
502         post_process_message = ossl_statem_client_post_process_message;
503     }
504
505     if (st->read_state_first_init) {
506         s->first_packet = 1;
507         st->read_state_first_init = 0;
508     }
509
510     while (1) {
511         switch (st->read_state) {
512         case READ_STATE_HEADER:
513             /* Get the state the peer wants to move to */
514             if (SSL_IS_DTLS(s)) {
515                 /*
516                  * In DTLS we get the whole message in one go - header and body
517                  */
518                 ret = dtls_get_message(s, &mt, &len);
519             } else {
520                 ret = tls_get_message_header(s, &mt);
521             }
522
523             if (ret == 0) {
524                 /* Could be non-blocking IO */
525                 return SUB_STATE_ERROR;
526             }
527
528             if (cb != NULL) {
529                 /* Notify callback of an impending state change */
530                 if (s->server)
531                     cb(s, SSL_CB_ACCEPT_LOOP, 1);
532                 else
533                     cb(s, SSL_CB_CONNECT_LOOP, 1);
534             }
535             /*
536              * Validate that we are allowed to move to the new state and move
537              * to that state if so
538              */
539             if (!transition(s, mt)) {
540                 ossl_statem_set_error(s);
541                 return SUB_STATE_ERROR;
542             }
543
544             if (s->s3->tmp.message_size > max_message_size(s)) {
545                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
546                 SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
547                 return SUB_STATE_ERROR;
548             }
549
550             /* dtls_get_message already did this */
551             if (!SSL_IS_DTLS(s)
552                     && s->s3->tmp.message_size > 0
553                     && !grow_init_buf(s, s->s3->tmp.message_size
554                                          + SSL3_HM_HEADER_LENGTH)) {
555                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
556                 SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_BUF_LIB);
557                 return SUB_STATE_ERROR;
558             }
559
560             st->read_state = READ_STATE_BODY;
561             /* Fall through */
562
563         case READ_STATE_BODY:
564             if (!SSL_IS_DTLS(s)) {
565                 /* We already got this above for DTLS */
566                 ret = tls_get_message_body(s, &len);
567                 if (ret == 0) {
568                     /* Could be non-blocking IO */
569                     return SUB_STATE_ERROR;
570                 }
571             }
572
573             s->first_packet = 0;
574             if (!PACKET_buf_init(&pkt, s->init_msg, len)) {
575                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
576                 SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
577                 return SUB_STATE_ERROR;
578             }
579             ret = process_message(s, &pkt);
580
581             /* Discard the packet data */
582             s->init_num = 0;
583
584             switch (ret) {
585             case MSG_PROCESS_ERROR:
586                 return SUB_STATE_ERROR;
587
588             case MSG_PROCESS_FINISHED_READING:
589                 if (SSL_IS_DTLS(s)) {
590                     dtls1_stop_timer(s);
591                 }
592                 return SUB_STATE_FINISHED;
593
594             case MSG_PROCESS_CONTINUE_PROCESSING:
595                 st->read_state = READ_STATE_POST_PROCESS;
596                 st->read_state_work = WORK_MORE_A;
597                 break;
598
599             default:
600                 st->read_state = READ_STATE_HEADER;
601                 break;
602             }
603             break;
604
605         case READ_STATE_POST_PROCESS:
606             st->read_state_work = post_process_message(s, st->read_state_work);
607             switch (st->read_state_work) {
608             case WORK_ERROR:
609             case WORK_MORE_A:
610             case WORK_MORE_B:
611             case WORK_MORE_C:
612                 return SUB_STATE_ERROR;
613
614             case WORK_FINISHED_CONTINUE:
615                 st->read_state = READ_STATE_HEADER;
616                 break;
617
618             case WORK_FINISHED_STOP:
619                 if (SSL_IS_DTLS(s)) {
620                     dtls1_stop_timer(s);
621                 }
622                 return SUB_STATE_FINISHED;
623             }
624             break;
625
626         default:
627             /* Shouldn't happen */
628             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
629             SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
630             ossl_statem_set_error(s);
631             return SUB_STATE_ERROR;
632         }
633     }
634 }
635
636 /*
637  * Send a previously constructed message to the peer.
638  */
639 static int statem_do_write(SSL *s)
640 {
641     OSSL_STATEM *st = &s->statem;
642
643     if (st->hand_state == TLS_ST_CW_CHANGE
644         || st->hand_state == TLS_ST_SW_CHANGE) {
645         if (SSL_IS_DTLS(s))
646             return dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
647         else
648             return ssl3_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
649     } else {
650         return ssl_do_write(s);
651     }
652 }
653
654 /*
655  * Initialise the MSG_FLOW_WRITING sub-state machine
656  */
657 static void init_write_state_machine(SSL *s)
658 {
659     OSSL_STATEM *st = &s->statem;
660
661     st->write_state = WRITE_STATE_TRANSITION;
662 }
663
664 /*
665  * This function implements the sub-state machine when the message flow is in
666  * MSG_FLOW_WRITING. The valid sub-states and transitions are:
667  *
668  * +-> WRITE_STATE_TRANSITION ------> [SUB_STATE_FINISHED]
669  * |             |
670  * |             v
671  * |      WRITE_STATE_PRE_WORK -----> [SUB_STATE_END_HANDSHAKE]
672  * |             |
673  * |             v
674  * |       WRITE_STATE_SEND
675  * |             |
676  * |             v
677  * |     WRITE_STATE_POST_WORK
678  * |             |
679  * +-------------+
680  *
681  * WRITE_STATE_TRANSITION transitions the state of the handshake state machine
682
683  * WRITE_STATE_PRE_WORK performs any work necessary to prepare the later
684  * sending of the message. This could result in an NBIO event occurring in
685  * which case control returns to the calling application. When this function
686  * is recalled we will resume in the same state where we left off.
687  *
688  * WRITE_STATE_SEND sends the message and performs any work to be done after
689  * sending.
690  *
691  * WRITE_STATE_POST_WORK performs any work necessary after the sending of the
692  * message has been completed. As for WRITE_STATE_PRE_WORK this could also
693  * result in an NBIO event.
694  */
695 static SUB_STATE_RETURN write_state_machine(SSL *s)
696 {
697     OSSL_STATEM *st = &s->statem;
698     int ret;
699     WRITE_TRAN(*transition) (SSL *s);
700     WORK_STATE(*pre_work) (SSL *s, WORK_STATE wst);
701     WORK_STATE(*post_work) (SSL *s, WORK_STATE wst);
702     int (*get_construct_message_f) (SSL *s, WPACKET *pkt,
703                                     int (**confunc) (SSL *s, WPACKET *pkt),
704                                     int *mt);
705     void (*cb) (const SSL *ssl, int type, int val) = NULL;
706     int (*confunc) (SSL *s, WPACKET *pkt);
707     int mt;
708     WPACKET pkt;
709
710     cb = get_callback(s);
711
712     if (s->server) {
713         transition = ossl_statem_server_write_transition;
714         pre_work = ossl_statem_server_pre_work;
715         post_work = ossl_statem_server_post_work;
716         get_construct_message_f = ossl_statem_server_construct_message;
717     } else {
718         transition = ossl_statem_client_write_transition;
719         pre_work = ossl_statem_client_pre_work;
720         post_work = ossl_statem_client_post_work;
721         get_construct_message_f = ossl_statem_client_construct_message;
722     }
723
724     while (1) {
725         switch (st->write_state) {
726         case WRITE_STATE_TRANSITION:
727             if (cb != NULL) {
728                 /* Notify callback of an impending state change */
729                 if (s->server)
730                     cb(s, SSL_CB_ACCEPT_LOOP, 1);
731                 else
732                     cb(s, SSL_CB_CONNECT_LOOP, 1);
733             }
734             switch (transition(s)) {
735             case WRITE_TRAN_CONTINUE:
736                 st->write_state = WRITE_STATE_PRE_WORK;
737                 st->write_state_work = WORK_MORE_A;
738                 break;
739
740             case WRITE_TRAN_FINISHED:
741                 return SUB_STATE_FINISHED;
742                 break;
743
744             case WRITE_TRAN_ERROR:
745                 return SUB_STATE_ERROR;
746             }
747             break;
748
749         case WRITE_STATE_PRE_WORK:
750             switch (st->write_state_work = pre_work(s, st->write_state_work)) {
751             case WORK_ERROR:
752             case WORK_MORE_A:
753             case WORK_MORE_B:
754             case WORK_MORE_C:
755                 return SUB_STATE_ERROR;
756
757             case WORK_FINISHED_CONTINUE:
758                 st->write_state = WRITE_STATE_SEND;
759                 break;
760
761             case WORK_FINISHED_STOP:
762                 return SUB_STATE_END_HANDSHAKE;
763             }
764             if (!get_construct_message_f(s, &pkt, &confunc, &mt)) {
765                 ossl_statem_set_error(s);
766                 return SUB_STATE_ERROR;
767             }
768             if (mt == SSL3_MT_DUMMY) {
769                 /* Skip construction and sending. This isn't a "real" state */
770                 st->write_state = WRITE_STATE_POST_WORK;
771                 st->write_state_work = WORK_MORE_A;
772                 break;
773             }
774             if (!WPACKET_init(&pkt, s->init_buf)
775                     || !ssl_set_handshake_header(s, &pkt, mt)
776                     || (confunc != NULL && !confunc(s, &pkt))
777                     || !ssl_close_construct_packet(s, &pkt, mt)
778                     || !WPACKET_finish(&pkt)) {
779                 WPACKET_cleanup(&pkt);
780                 ossl_statem_set_error(s);
781                 return SUB_STATE_ERROR;
782             }
783
784             /* Fall through */
785
786         case WRITE_STATE_SEND:
787             if (SSL_IS_DTLS(s) && st->use_timer) {
788                 dtls1_start_timer(s);
789             }
790             ret = statem_do_write(s);
791             if (ret <= 0) {
792                 return SUB_STATE_ERROR;
793             }
794             st->write_state = WRITE_STATE_POST_WORK;
795             st->write_state_work = WORK_MORE_A;
796             /* Fall through */
797
798         case WRITE_STATE_POST_WORK:
799             switch (st->write_state_work = post_work(s, st->write_state_work)) {
800             case WORK_ERROR:
801             case WORK_MORE_A:
802             case WORK_MORE_B:
803             case WORK_MORE_C:
804                 return SUB_STATE_ERROR;
805
806             case WORK_FINISHED_CONTINUE:
807                 st->write_state = WRITE_STATE_TRANSITION;
808                 break;
809
810             case WORK_FINISHED_STOP:
811                 return SUB_STATE_END_HANDSHAKE;
812             }
813             break;
814
815         default:
816             return SUB_STATE_ERROR;
817         }
818     }
819 }
820
821 /*
822  * Flush the write BIO
823  */
824 int statem_flush(SSL *s)
825 {
826     s->rwstate = SSL_WRITING;
827     if (BIO_flush(s->wbio) <= 0) {
828         return 0;
829     }
830     s->rwstate = SSL_NOTHING;
831
832     return 1;
833 }
834
835 /*
836  * Called by the record layer to determine whether application data is
837  * allowed to be received in the current handshake state or not.
838  *
839  * Return values are:
840  *   1: Yes (application data allowed)
841  *   0: No (application data not allowed)
842  */
843 int ossl_statem_app_data_allowed(SSL *s)
844 {
845     OSSL_STATEM *st = &s->statem;
846
847     if (st->state == MSG_FLOW_UNINITED)
848         return 0;
849
850     if (!s->s3->in_read_app_data || (s->s3->total_renegotiations == 0))
851         return 0;
852
853     if (s->server) {
854         /*
855          * If we're a server and we haven't got as far as writing our
856          * ServerHello yet then we allow app data
857          */
858         if (st->hand_state == TLS_ST_BEFORE
859             || st->hand_state == TLS_ST_SR_CLNT_HELLO)
860             return 1;
861     } else {
862         /*
863          * If we're a client and we haven't read the ServerHello yet then we
864          * allow app data
865          */
866         if (st->hand_state == TLS_ST_CW_CLNT_HELLO)
867             return 1;
868     }
869
870     return 0;
871 }
872
873 #ifndef OPENSSL_NO_SCTP
874 /*
875  * Set flag used by SCTP to determine whether we are in the read sock state
876  */
877 void ossl_statem_set_sctp_read_sock(SSL *s, int read_sock)
878 {
879     s->statem.in_sctp_read_sock = read_sock;
880 }
881
882 /*
883  * Called by the record layer to determine whether we are in the read sock
884  * state or not.
885  *
886  * Return values are:
887  *   1: Yes (we are in the read sock state)
888  *   0: No (we are not in the read sock state)
889  */
890 int ossl_statem_in_sctp_read_sock(SSL *s)
891 {
892     return s->statem.in_sctp_read_sock;
893 }
894 #endif