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