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