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