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