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