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