50c43459711d2e0532f42cb55f4d22acd115db38
[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->statem.hand_state != TLS_ST_SW_FINISHED)
165             return 0;
166     }
167
168     return 1;
169 }
170
171 void ossl_statem_check_finish_init(SSL *s, int send)
172 {
173     if (!s->server) {
174         if ((send && s->statem.hand_state == TLS_ST_PENDING_EARLY_DATA_END)
175                 || (!send && s->statem.hand_state == TLS_ST_EARLY_DATA))
176             ossl_statem_set_in_init(s, 1);
177     }
178 }
179
180 void ossl_statem_set_hello_verify_done(SSL *s)
181 {
182     s->statem.state = MSG_FLOW_UNINITED;
183     s->statem.in_init = 1;
184     /*
185      * This will get reset (briefly) back to TLS_ST_BEFORE when we enter
186      * state_machine() because |state| is MSG_FLOW_UNINITED, but until then any
187      * calls to SSL_in_before() will return false. Also calls to
188      * SSL_state_string() and SSL_state_string_long() will return something
189      * sensible.
190      */
191     s->statem.hand_state = TLS_ST_SR_CLNT_HELLO;
192 }
193
194 int ossl_statem_connect(SSL *s)
195 {
196     return state_machine(s, 0);
197 }
198
199 int ossl_statem_accept(SSL *s)
200 {
201     return state_machine(s, 1);
202 }
203
204 typedef void (*info_cb) (const SSL *, int, int);
205
206 static info_cb get_callback(SSL *s)
207 {
208     if (s->info_callback != NULL)
209         return s->info_callback;
210     else if (s->ctx->info_callback != NULL)
211         return s->ctx->info_callback;
212
213     return NULL;
214 }
215
216 /*
217  * The main message flow state machine. We start in the MSG_FLOW_UNINITED or
218  * MSG_FLOW_FINISHED state and finish in MSG_FLOW_FINISHED. Valid states and
219  * transitions are as follows:
220  *
221  * MSG_FLOW_UNINITED     MSG_FLOW_FINISHED
222  *        |                       |
223  *        +-----------------------+
224  *        v
225  * MSG_FLOW_WRITING <---> MSG_FLOW_READING
226  *        |
227  *        V
228  * MSG_FLOW_FINISHED
229  *        |
230  *        V
231  *    [SUCCESS]
232  *
233  * We may exit at any point due to an error or NBIO event. If an NBIO event
234  * occurs then we restart at the point we left off when we are recalled.
235  * MSG_FLOW_WRITING and MSG_FLOW_READING have sub-state machines associated with them.
236  *
237  * In addition to the above there is also the MSG_FLOW_ERROR state. We can move
238  * into that state at any point in the event that an irrecoverable error occurs.
239  *
240  * Valid return values are:
241  *   1: Success
242  * <=0: NBIO or error
243  */
244 static int state_machine(SSL *s, int server)
245 {
246     BUF_MEM *buf = NULL;
247     unsigned long Time = (unsigned long)time(NULL);
248     void (*cb) (const SSL *ssl, int type, int val) = NULL;
249     OSSL_STATEM *st = &s->statem;
250     int ret = -1;
251     int ssret;
252
253     if (st->state == MSG_FLOW_ERROR) {
254         /* Shouldn't have been called if we're already in the error state */
255         return -1;
256     }
257
258     RAND_add(&Time, sizeof(Time), 0);
259     ERR_clear_error();
260     clear_sys_error();
261
262     cb = get_callback(s);
263
264     st->in_handshake++;
265     if (!SSL_in_init(s) || SSL_in_before(s)) {
266         if (!SSL_clear(s))
267             return -1;
268     }
269 #ifndef OPENSSL_NO_SCTP
270     if (SSL_IS_DTLS(s)) {
271         /*
272          * Notify SCTP BIO socket to enter handshake mode and prevent stream
273          * identifier other than 0. Will be ignored if no SCTP is used.
274          */
275         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
276                  st->in_handshake, NULL);
277     }
278 #endif
279
280     /* Initialise state machine */
281     if (st->state == MSG_FLOW_UNINITED
282             || st->state == MSG_FLOW_FINISHED) {
283         if (st->state == MSG_FLOW_UNINITED) {
284             st->hand_state = TLS_ST_BEFORE;
285             st->request_state = TLS_ST_BEFORE;
286         }
287
288         s->server = server;
289         if (cb != NULL)
290             cb(s, SSL_CB_HANDSHAKE_START, 1);
291
292         if (SSL_IS_DTLS(s)) {
293             if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00) &&
294                 (server || (s->version & 0xff00) != (DTLS1_BAD_VER & 0xff00))) {
295                 SSLerr(SSL_F_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
296                 goto end;
297             }
298         } else {
299             if ((s->version >> 8) != SSL3_VERSION_MAJOR) {
300                 SSLerr(SSL_F_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
301                 goto end;
302             }
303         }
304
305         if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
306             SSLerr(SSL_F_STATE_MACHINE, SSL_R_VERSION_TOO_LOW);
307             goto end;
308         }
309
310         if (s->init_buf == NULL) {
311             if ((buf = BUF_MEM_new()) == NULL) {
312                 goto end;
313             }
314             if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
315                 goto end;
316             }
317             s->init_buf = buf;
318             buf = NULL;
319         }
320
321         if (!ssl3_setup_buffers(s)) {
322             goto end;
323         }
324         s->init_num = 0;
325
326         /*
327          * Should have been reset by tls_process_finished, too.
328          */
329         s->s3->change_cipher_spec = 0;
330
331         /*
332          * Ok, we now need to push on a buffering BIO ...but not with
333          * SCTP
334          */
335 #ifndef OPENSSL_NO_SCTP
336         if (!SSL_IS_DTLS(s) || !BIO_dgram_is_sctp(SSL_get_wbio(s)))
337 #endif
338             if (!ssl_init_wbio_buffer(s)) {
339                 goto end;
340             }
341
342         if ((SSL_IS_FIRST_HANDSHAKE(s)
343                     && s->early_data_state != SSL_EARLY_DATA_FINISHED_WRITING
344                     && s->early_data_state != SSL_EARLY_DATA_FINISHED_READING)
345                 || s->renegotiate) {
346             if (!tls_setup_handshake(s)) {
347                 ossl_statem_set_error(s);
348                 goto end;
349             }
350
351             if (SSL_IS_FIRST_HANDSHAKE(s))
352                 st->read_state_first_init = 1;
353         }
354
355         st->state = MSG_FLOW_WRITING;
356         init_write_state_machine(s);
357     }
358
359     while (st->state != MSG_FLOW_FINISHED) {
360         if (st->state == MSG_FLOW_READING) {
361             ssret = read_state_machine(s);
362             if (ssret == SUB_STATE_FINISHED) {
363                 st->state = MSG_FLOW_WRITING;
364                 init_write_state_machine(s);
365             } else {
366                 /* NBIO or error */
367                 goto end;
368             }
369         } else if (st->state == MSG_FLOW_WRITING) {
370             ssret = write_state_machine(s);
371             if (ssret == SUB_STATE_FINISHED) {
372                 st->state = MSG_FLOW_READING;
373                 init_read_state_machine(s);
374             } else if (ssret == SUB_STATE_END_HANDSHAKE) {
375                 st->state = MSG_FLOW_FINISHED;
376             } else {
377                 /* NBIO or error */
378                 goto end;
379             }
380         } else {
381             /* Error */
382             ossl_statem_set_error(s);
383             goto end;
384         }
385     }
386
387     ret = 1;
388
389  end:
390     st->in_handshake--;
391
392 #ifndef OPENSSL_NO_SCTP
393     if (SSL_IS_DTLS(s)) {
394         /*
395          * Notify SCTP BIO socket to leave handshake mode and allow stream
396          * identifier other than 0. Will be ignored if no SCTP is used.
397          */
398         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
399                  st->in_handshake, NULL);
400     }
401 #endif
402
403     BUF_MEM_free(buf);
404     if (cb != NULL) {
405         if (server)
406             cb(s, SSL_CB_ACCEPT_EXIT, ret);
407         else
408             cb(s, SSL_CB_CONNECT_EXIT, ret);
409     }
410     return ret;
411 }
412
413 /*
414  * Initialise the MSG_FLOW_READING sub-state machine
415  */
416 static void init_read_state_machine(SSL *s)
417 {
418     OSSL_STATEM *st = &s->statem;
419
420     st->read_state = READ_STATE_HEADER;
421 }
422
423 static int grow_init_buf(SSL *s, size_t size) {
424
425     size_t msg_offset = (char *)s->init_msg - s->init_buf->data;
426
427     if (!BUF_MEM_grow_clean(s->init_buf, (int)size))
428         return 0;
429
430     if (size < msg_offset)
431         return 0;
432
433     s->init_msg = s->init_buf->data + msg_offset;
434
435     return 1;
436 }
437
438 /*
439  * This function implements the sub-state machine when the message flow is in
440  * MSG_FLOW_READING. The valid sub-states and transitions are:
441  *
442  * READ_STATE_HEADER <--+<-------------+
443  *        |             |              |
444  *        v             |              |
445  * READ_STATE_BODY -----+-->READ_STATE_POST_PROCESS
446  *        |                            |
447  *        +----------------------------+
448  *        v
449  * [SUB_STATE_FINISHED]
450  *
451  * READ_STATE_HEADER has the responsibility for reading in the message header
452  * and transitioning the state of the handshake state machine.
453  *
454  * READ_STATE_BODY reads in the rest of the message and then subsequently
455  * processes it.
456  *
457  * READ_STATE_POST_PROCESS is an optional step that may occur if some post
458  * processing activity performed on the message may block.
459  *
460  * Any of the above states could result in an NBIO event occurring in which case
461  * control returns to the calling application. When this function is recalled we
462  * will resume in the same state where we left off.
463  */
464 static SUB_STATE_RETURN read_state_machine(SSL *s)
465 {
466     OSSL_STATEM *st = &s->statem;
467     int ret, mt;
468     size_t len = 0;
469     int (*transition) (SSL *s, int mt);
470     PACKET pkt;
471     MSG_PROCESS_RETURN(*process_message) (SSL *s, PACKET *pkt);
472     WORK_STATE(*post_process_message) (SSL *s, WORK_STATE wst);
473     size_t (*max_message_size) (SSL *s);
474     void (*cb) (const SSL *ssl, int type, int val) = NULL;
475
476     cb = get_callback(s);
477
478     if (s->server) {
479         transition = ossl_statem_server_read_transition;
480         process_message = ossl_statem_server_process_message;
481         max_message_size = ossl_statem_server_max_message_size;
482         post_process_message = ossl_statem_server_post_process_message;
483     } else {
484         transition = ossl_statem_client_read_transition;
485         process_message = ossl_statem_client_process_message;
486         max_message_size = ossl_statem_client_max_message_size;
487         post_process_message = ossl_statem_client_post_process_message;
488     }
489
490     if (st->read_state_first_init) {
491         s->first_packet = 1;
492         st->read_state_first_init = 0;
493     }
494
495     while (1) {
496         switch (st->read_state) {
497         case READ_STATE_HEADER:
498             /* Get the state the peer wants to move to */
499             if (SSL_IS_DTLS(s)) {
500                 /*
501                  * In DTLS we get the whole message in one go - header and body
502                  */
503                 ret = dtls_get_message(s, &mt, &len);
504             } else {
505                 ret = tls_get_message_header(s, &mt);
506             }
507
508             if (ret == 0) {
509                 /* Could be non-blocking IO */
510                 return SUB_STATE_ERROR;
511             }
512
513             if (cb != NULL) {
514                 /* Notify callback of an impending state change */
515                 if (s->server)
516                     cb(s, SSL_CB_ACCEPT_LOOP, 1);
517                 else
518                     cb(s, SSL_CB_CONNECT_LOOP, 1);
519             }
520             /*
521              * Validate that we are allowed to move to the new state and move
522              * to that state if so
523              */
524             if (!transition(s, mt)) {
525                 ossl_statem_set_error(s);
526                 return SUB_STATE_ERROR;
527             }
528
529             if (s->s3->tmp.message_size > max_message_size(s)) {
530                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
531                 SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
532                 return SUB_STATE_ERROR;
533             }
534
535             /* dtls_get_message already did this */
536             if (!SSL_IS_DTLS(s)
537                     && s->s3->tmp.message_size > 0
538                     && !grow_init_buf(s, s->s3->tmp.message_size
539                                          + SSL3_HM_HEADER_LENGTH)) {
540                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
541                 SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_BUF_LIB);
542                 return SUB_STATE_ERROR;
543             }
544
545             st->read_state = READ_STATE_BODY;
546             /* Fall through */
547
548         case READ_STATE_BODY:
549             if (!SSL_IS_DTLS(s)) {
550                 /* We already got this above for DTLS */
551                 ret = tls_get_message_body(s, &len);
552                 if (ret == 0) {
553                     /* Could be non-blocking IO */
554                     return SUB_STATE_ERROR;
555                 }
556             }
557
558             s->first_packet = 0;
559             if (!PACKET_buf_init(&pkt, s->init_msg, len)) {
560                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
561                 SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
562                 return SUB_STATE_ERROR;
563             }
564             ret = process_message(s, &pkt);
565
566             /* Discard the packet data */
567             s->init_num = 0;
568
569             switch (ret) {
570             case MSG_PROCESS_ERROR:
571                 return SUB_STATE_ERROR;
572
573             case MSG_PROCESS_FINISHED_READING:
574                 if (SSL_IS_DTLS(s)) {
575                     dtls1_stop_timer(s);
576                 }
577                 return SUB_STATE_FINISHED;
578
579             case MSG_PROCESS_CONTINUE_PROCESSING:
580                 st->read_state = READ_STATE_POST_PROCESS;
581                 st->read_state_work = WORK_MORE_A;
582                 break;
583
584             default:
585                 st->read_state = READ_STATE_HEADER;
586                 break;
587             }
588             break;
589
590         case READ_STATE_POST_PROCESS:
591             st->read_state_work = post_process_message(s, st->read_state_work);
592             switch (st->read_state_work) {
593             case WORK_ERROR:
594             case WORK_MORE_A:
595             case WORK_MORE_B:
596             case WORK_MORE_C:
597                 return SUB_STATE_ERROR;
598
599             case WORK_FINISHED_CONTINUE:
600                 st->read_state = READ_STATE_HEADER;
601                 break;
602
603             case WORK_FINISHED_STOP:
604                 if (SSL_IS_DTLS(s)) {
605                     dtls1_stop_timer(s);
606                 }
607                 return SUB_STATE_FINISHED;
608             }
609             break;
610
611         default:
612             /* Shouldn't happen */
613             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
614             SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
615             ossl_statem_set_error(s);
616             return SUB_STATE_ERROR;
617         }
618     }
619 }
620
621 /*
622  * Send a previously constructed message to the peer.
623  */
624 static int statem_do_write(SSL *s)
625 {
626     OSSL_STATEM *st = &s->statem;
627
628     if (st->hand_state == TLS_ST_CW_CHANGE
629         || st->hand_state == TLS_ST_SW_CHANGE) {
630         if (SSL_IS_DTLS(s))
631             return dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
632         else
633             return ssl3_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
634     } else {
635         return ssl_do_write(s);
636     }
637 }
638
639 /*
640  * Initialise the MSG_FLOW_WRITING sub-state machine
641  */
642 static void init_write_state_machine(SSL *s)
643 {
644     OSSL_STATEM *st = &s->statem;
645
646     st->write_state = WRITE_STATE_TRANSITION;
647 }
648
649 /*
650  * This function implements the sub-state machine when the message flow is in
651  * MSG_FLOW_WRITING. The valid sub-states and transitions are:
652  *
653  * +-> WRITE_STATE_TRANSITION ------> [SUB_STATE_FINISHED]
654  * |             |
655  * |             v
656  * |      WRITE_STATE_PRE_WORK -----> [SUB_STATE_END_HANDSHAKE]
657  * |             |
658  * |             v
659  * |       WRITE_STATE_SEND
660  * |             |
661  * |             v
662  * |     WRITE_STATE_POST_WORK
663  * |             |
664  * +-------------+
665  *
666  * WRITE_STATE_TRANSITION transitions the state of the handshake state machine
667
668  * WRITE_STATE_PRE_WORK performs any work necessary to prepare the later
669  * sending of the message. This could result in an NBIO event occurring in
670  * which case control returns to the calling application. When this function
671  * is recalled we will resume in the same state where we left off.
672  *
673  * WRITE_STATE_SEND sends the message and performs any work to be done after
674  * sending.
675  *
676  * WRITE_STATE_POST_WORK performs any work necessary after the sending of the
677  * message has been completed. As for WRITE_STATE_PRE_WORK this could also
678  * result in an NBIO event.
679  */
680 static SUB_STATE_RETURN write_state_machine(SSL *s)
681 {
682     OSSL_STATEM *st = &s->statem;
683     int ret;
684     WRITE_TRAN(*transition) (SSL *s);
685     WORK_STATE(*pre_work) (SSL *s, WORK_STATE wst);
686     WORK_STATE(*post_work) (SSL *s, WORK_STATE wst);
687     int (*get_construct_message_f) (SSL *s, WPACKET *pkt,
688                                     int (**confunc) (SSL *s, WPACKET *pkt),
689                                     int *mt);
690     void (*cb) (const SSL *ssl, int type, int val) = NULL;
691     int (*confunc) (SSL *s, WPACKET *pkt);
692     int mt;
693     WPACKET pkt;
694
695     cb = get_callback(s);
696
697     if (s->server) {
698         transition = ossl_statem_server_write_transition;
699         pre_work = ossl_statem_server_pre_work;
700         post_work = ossl_statem_server_post_work;
701         get_construct_message_f = ossl_statem_server_construct_message;
702     } else {
703         transition = ossl_statem_client_write_transition;
704         pre_work = ossl_statem_client_pre_work;
705         post_work = ossl_statem_client_post_work;
706         get_construct_message_f = ossl_statem_client_construct_message;
707     }
708
709     while (1) {
710         switch (st->write_state) {
711         case WRITE_STATE_TRANSITION:
712             if (cb != NULL) {
713                 /* Notify callback of an impending state change */
714                 if (s->server)
715                     cb(s, SSL_CB_ACCEPT_LOOP, 1);
716                 else
717                     cb(s, SSL_CB_CONNECT_LOOP, 1);
718             }
719             switch (transition(s)) {
720             case WRITE_TRAN_CONTINUE:
721                 st->write_state = WRITE_STATE_PRE_WORK;
722                 st->write_state_work = WORK_MORE_A;
723                 break;
724
725             case WRITE_TRAN_FINISHED:
726                 return SUB_STATE_FINISHED;
727                 break;
728
729             case WRITE_TRAN_ERROR:
730                 return SUB_STATE_ERROR;
731             }
732             break;
733
734         case WRITE_STATE_PRE_WORK:
735             switch (st->write_state_work = pre_work(s, st->write_state_work)) {
736             case WORK_ERROR:
737             case WORK_MORE_A:
738             case WORK_MORE_B:
739             case WORK_MORE_C:
740                 return SUB_STATE_ERROR;
741
742             case WORK_FINISHED_CONTINUE:
743                 st->write_state = WRITE_STATE_SEND;
744                 break;
745
746             case WORK_FINISHED_STOP:
747                 return SUB_STATE_END_HANDSHAKE;
748             }
749             if (!WPACKET_init(&pkt, s->init_buf)
750                     || !get_construct_message_f(s, &pkt, &confunc, &mt)
751                     || !ssl_set_handshake_header(s, &pkt, mt)
752                     || (confunc != NULL && !confunc(s, &pkt))
753                     || !ssl_close_construct_packet(s, &pkt, mt)
754                     || !WPACKET_finish(&pkt)) {
755                 WPACKET_cleanup(&pkt);
756                 ossl_statem_set_error(s);
757                 return SUB_STATE_ERROR;
758             }
759
760             /* Fall through */
761
762         case WRITE_STATE_SEND:
763             if (SSL_IS_DTLS(s) && st->use_timer) {
764                 dtls1_start_timer(s);
765             }
766             ret = statem_do_write(s);
767             if (ret <= 0) {
768                 return SUB_STATE_ERROR;
769             }
770             st->write_state = WRITE_STATE_POST_WORK;
771             st->write_state_work = WORK_MORE_A;
772             /* Fall through */
773
774         case WRITE_STATE_POST_WORK:
775             switch (st->write_state_work = post_work(s, st->write_state_work)) {
776             case WORK_ERROR:
777             case WORK_MORE_A:
778             case WORK_MORE_B:
779             case WORK_MORE_C:
780                 return SUB_STATE_ERROR;
781
782             case WORK_FINISHED_CONTINUE:
783                 st->write_state = WRITE_STATE_TRANSITION;
784                 break;
785
786             case WORK_FINISHED_STOP:
787                 return SUB_STATE_END_HANDSHAKE;
788             }
789             break;
790
791         default:
792             return SUB_STATE_ERROR;
793         }
794     }
795 }
796
797 /*
798  * Flush the write BIO
799  */
800 int statem_flush(SSL *s)
801 {
802     s->rwstate = SSL_WRITING;
803     if (BIO_flush(s->wbio) <= 0) {
804         return 0;
805     }
806     s->rwstate = SSL_NOTHING;
807
808     return 1;
809 }
810
811 /*
812  * Called by the record layer to determine whether application data is
813  * allowed to be received in the current handshake state or not.
814  *
815  * Return values are:
816  *   1: Yes (application data allowed)
817  *   0: No (application data not allowed)
818  */
819 int ossl_statem_app_data_allowed(SSL *s)
820 {
821     OSSL_STATEM *st = &s->statem;
822
823     if (st->state == MSG_FLOW_UNINITED)
824         return 0;
825
826     if (!s->s3->in_read_app_data || (s->s3->total_renegotiations == 0))
827         return 0;
828
829     if (s->server) {
830         /*
831          * If we're a server and we haven't got as far as writing our
832          * ServerHello yet then we allow app data
833          */
834         if (st->hand_state == TLS_ST_BEFORE
835             || st->hand_state == TLS_ST_SR_CLNT_HELLO)
836             return 1;
837     } else {
838         /*
839          * If we're a client and we haven't read the ServerHello yet then we
840          * allow app data
841          */
842         if (st->hand_state == TLS_ST_CW_CLNT_HELLO)
843             return 1;
844     }
845
846     return 0;
847 }
848
849 #ifndef OPENSSL_NO_SCTP
850 /*
851  * Set flag used by SCTP to determine whether we are in the read sock state
852  */
853 void ossl_statem_set_sctp_read_sock(SSL *s, int read_sock)
854 {
855     s->statem.in_sctp_read_sock = read_sock;
856 }
857
858 /*
859  * Called by the record layer to determine whether we are in the read sock
860  * state or not.
861  *
862  * Return values are:
863  *   1: Yes (we are in the read sock state)
864  *   0: No (we are not in the read sock state)
865  */
866 int ossl_statem_in_sctp_read_sock(SSL *s)
867 {
868     return s->statem.in_sctp_read_sock;
869 }
870 #endif