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