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