dtls_get_message changes for state machine move
[openssl.git] / ssl / d1_both.c
1 /* ssl/d1_both.c */
2 /*
3  * DTLS implementation written by Nagendra Modadugu
4  * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
5  */
6 /* ====================================================================
7  * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    openssl-core@openssl.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
60  * All rights reserved.
61  *
62  * This package is an SSL implementation written
63  * by Eric Young (eay@cryptsoft.com).
64  * The implementation was written so as to conform with Netscapes SSL.
65  *
66  * This library is free for commercial and non-commercial use as long as
67  * the following conditions are aheared to.  The following conditions
68  * apply to all code found in this distribution, be it the RC4, RSA,
69  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
70  * included with this distribution is covered by the same copyright terms
71  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
72  *
73  * Copyright remains Eric Young's, and as such any Copyright notices in
74  * the code are not to be removed.
75  * If this package is used in a product, Eric Young should be given attribution
76  * as the author of the parts of the library used.
77  * This can be in the form of a textual message at program startup or
78  * in documentation (online or textual) provided with the package.
79  *
80  * Redistribution and use in source and binary forms, with or without
81  * modification, are permitted provided that the following conditions
82  * are met:
83  * 1. Redistributions of source code must retain the copyright
84  *    notice, this list of conditions and the following disclaimer.
85  * 2. Redistributions in binary form must reproduce the above copyright
86  *    notice, this list of conditions and the following disclaimer in the
87  *    documentation and/or other materials provided with the distribution.
88  * 3. All advertising materials mentioning features or use of this software
89  *    must display the following acknowledgement:
90  *    "This product includes cryptographic software written by
91  *     Eric Young (eay@cryptsoft.com)"
92  *    The word 'cryptographic' can be left out if the rouines from the library
93  *    being used are not cryptographic related :-).
94  * 4. If you include any Windows specific code (or a derivative thereof) from
95  *    the apps directory (application code) you must include an acknowledgement:
96  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
97  *
98  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
99  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
100  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
101  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
102  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
103  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
104  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
105  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
106  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
107  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
108  * SUCH DAMAGE.
109  *
110  * The licence and distribution terms for any publically available version or
111  * derivative of this code cannot be changed.  i.e. this code cannot simply be
112  * copied and put under another distribution licence
113  * [including the GNU Public Licence.]
114  */
115
116 #include <limits.h>
117 #include <string.h>
118 #include <stdio.h>
119 #include "ssl_locl.h"
120 #include <openssl/buffer.h>
121 #include <openssl/rand.h>
122 #include <openssl/objects.h>
123 #include <openssl/evp.h>
124 #include <openssl/x509.h>
125
126 #define RSMBLY_BITMASK_SIZE(msg_len) (((msg_len) + 7) / 8)
127
128 #define RSMBLY_BITMASK_MARK(bitmask, start, end) { \
129                         if ((end) - (start) <= 8) { \
130                                 long ii; \
131                                 for (ii = (start); ii < (end); ii++) bitmask[((ii) >> 3)] |= (1 << ((ii) & 7)); \
132                         } else { \
133                                 long ii; \
134                                 bitmask[((start) >> 3)] |= bitmask_start_values[((start) & 7)]; \
135                                 for (ii = (((start) >> 3) + 1); ii < ((((end) - 1)) >> 3); ii++) bitmask[ii] = 0xff; \
136                                 bitmask[(((end) - 1) >> 3)] |= bitmask_end_values[((end) & 7)]; \
137                         } }
138
139 #define RSMBLY_BITMASK_IS_COMPLETE(bitmask, msg_len, is_complete) { \
140                         long ii; \
141                         OPENSSL_assert((msg_len) > 0); \
142                         is_complete = 1; \
143                         if (bitmask[(((msg_len) - 1) >> 3)] != bitmask_end_values[((msg_len) & 7)]) is_complete = 0; \
144                         if (is_complete) for (ii = (((msg_len) - 1) >> 3) - 1; ii >= 0 ; ii--) \
145                                 if (bitmask[ii] != 0xff) { is_complete = 0; break; } }
146
147 static unsigned char bitmask_start_values[] =
148     { 0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80 };
149 static unsigned char bitmask_end_values[] =
150     { 0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f };
151
152 /* XDTLS:  figure out the right values */
153 static const unsigned int g_probable_mtu[] = { 1500, 512, 256 };
154
155 static void dtls1_fix_message_header(SSL *s, unsigned long frag_off,
156                                      unsigned long frag_len);
157 static unsigned char *dtls1_write_message_header(SSL *s, unsigned char *p);
158 static void dtls1_set_message_header_int(SSL *s, unsigned char mt,
159                                          unsigned long len,
160                                          unsigned short seq_num,
161                                          unsigned long frag_off,
162                                          unsigned long frag_len);
163 static long dtls1_get_message_fragment(SSL *s, int st1, int stn, int mt,
164                                        int *ok);
165 static int dtls_get_reassembled_message(SSL *s, long *len);
166
167 static hm_fragment *dtls1_hm_fragment_new(unsigned long frag_len,
168                                           int reassembly)
169 {
170     hm_fragment *frag = NULL;
171     unsigned char *buf = NULL;
172     unsigned char *bitmask = NULL;
173
174     frag = OPENSSL_malloc(sizeof(*frag));
175     if (frag == NULL)
176         return NULL;
177
178     if (frag_len) {
179         buf = OPENSSL_malloc(frag_len);
180         if (buf == NULL) {
181             OPENSSL_free(frag);
182             return NULL;
183         }
184     }
185
186     /* zero length fragment gets zero frag->fragment */
187     frag->fragment = buf;
188
189     /* Initialize reassembly bitmask if necessary */
190     if (reassembly) {
191         bitmask = OPENSSL_zalloc(RSMBLY_BITMASK_SIZE(frag_len));
192         if (bitmask == NULL) {
193             OPENSSL_free(buf);
194             OPENSSL_free(frag);
195             return NULL;
196         }
197     }
198
199     frag->reassembly = bitmask;
200
201     return frag;
202 }
203
204 void dtls1_hm_fragment_free(hm_fragment *frag)
205 {
206     if (!frag)
207         return;
208     if (frag->msg_header.is_ccs) {
209         EVP_CIPHER_CTX_free(frag->msg_header.
210                             saved_retransmit_state.enc_write_ctx);
211         EVP_MD_CTX_destroy(frag->msg_header.
212                            saved_retransmit_state.write_hash);
213     }
214     OPENSSL_free(frag->fragment);
215     OPENSSL_free(frag->reassembly);
216     OPENSSL_free(frag);
217 }
218
219 static int dtls1_query_mtu(SSL *s)
220 {
221     if (s->d1->link_mtu) {
222         s->d1->mtu =
223             s->d1->link_mtu - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
224         s->d1->link_mtu = 0;
225     }
226
227     /* AHA!  Figure out the MTU, and stick to the right size */
228     if (s->d1->mtu < dtls1_min_mtu(s)) {
229         if (!(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
230             s->d1->mtu =
231                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
232
233             /*
234              * I've seen the kernel return bogus numbers when it doesn't know
235              * (initial write), so just make sure we have a reasonable number
236              */
237             if (s->d1->mtu < dtls1_min_mtu(s)) {
238                 /* Set to min mtu */
239                 s->d1->mtu = dtls1_min_mtu(s);
240                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
241                          s->d1->mtu, NULL);
242             }
243         } else
244             return 0;
245     }
246     return 1;
247 }
248
249 /*
250  * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
251  * SSL3_RT_CHANGE_CIPHER_SPEC)
252  */
253 int dtls1_do_write(SSL *s, int type)
254 {
255     int ret;
256     unsigned int curr_mtu;
257     int retry = 1;
258     unsigned int len, frag_off, mac_size, blocksize, used_len;
259
260     if (!dtls1_query_mtu(s))
261         return -1;
262
263     OPENSSL_assert(s->d1->mtu >= dtls1_min_mtu(s)); /* should have something
264                                                      * reasonable now */
265
266     if (s->init_off == 0 && type == SSL3_RT_HANDSHAKE)
267         OPENSSL_assert(s->init_num ==
268                        (int)s->d1->w_msg_hdr.msg_len +
269                        DTLS1_HM_HEADER_LENGTH);
270
271     if (s->write_hash) {
272         if (s->enc_write_ctx
273             && ((EVP_CIPHER_CTX_mode(s->enc_write_ctx) == EVP_CIPH_GCM_MODE) ||
274                 (EVP_CIPHER_CTX_mode(s->enc_write_ctx) == EVP_CIPH_CCM_MODE)))
275             mac_size = 0;
276         else
277             mac_size = EVP_MD_CTX_size(s->write_hash);
278     } else
279         mac_size = 0;
280
281     if (s->enc_write_ctx &&
282         (EVP_CIPHER_CTX_mode(s->enc_write_ctx) == EVP_CIPH_CBC_MODE))
283         blocksize = 2 * EVP_CIPHER_block_size(s->enc_write_ctx->cipher);
284     else
285         blocksize = 0;
286
287     frag_off = 0;
288     /* s->init_num shouldn't ever be < 0...but just in case */
289     while (s->init_num > 0) {
290         used_len = BIO_wpending(SSL_get_wbio(s)) + DTLS1_RT_HEADER_LENGTH
291             + mac_size + blocksize;
292         if (s->d1->mtu > used_len)
293             curr_mtu = s->d1->mtu - used_len;
294         else
295             curr_mtu = 0;
296
297         if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
298             /*
299              * grr.. we could get an error if MTU picked was wrong
300              */
301             ret = BIO_flush(SSL_get_wbio(s));
302             if (ret <= 0)
303                 return ret;
304             used_len = DTLS1_RT_HEADER_LENGTH + mac_size + blocksize;
305             if (s->d1->mtu > used_len + DTLS1_HM_HEADER_LENGTH) {
306                 curr_mtu = s->d1->mtu - used_len;
307             } else {
308                 /* Shouldn't happen */
309                 return -1;
310             }
311         }
312
313         /*
314          * We just checked that s->init_num > 0 so this cast should be safe
315          */
316         if (((unsigned int)s->init_num) > curr_mtu)
317             len = curr_mtu;
318         else
319             len = s->init_num;
320
321         /* Shouldn't ever happen */
322         if (len > INT_MAX)
323             len = INT_MAX;
324
325         /*
326          * XDTLS: this function is too long.  split out the CCS part
327          */
328         if (type == SSL3_RT_HANDSHAKE) {
329             if (s->init_off != 0) {
330                 OPENSSL_assert(s->init_off > DTLS1_HM_HEADER_LENGTH);
331                 s->init_off -= DTLS1_HM_HEADER_LENGTH;
332                 s->init_num += DTLS1_HM_HEADER_LENGTH;
333
334                 /*
335                  * We just checked that s->init_num > 0 so this cast should
336                  * be safe
337                  */
338                 if (((unsigned int)s->init_num) > curr_mtu)
339                     len = curr_mtu;
340                 else
341                     len = s->init_num;
342             }
343
344             /* Shouldn't ever happen */
345             if (len > INT_MAX)
346                 len = INT_MAX;
347
348             if (len < DTLS1_HM_HEADER_LENGTH) {
349                 /*
350                  * len is so small that we really can't do anything sensible
351                  * so fail
352                  */
353                 return -1;
354             }
355             dtls1_fix_message_header(s, frag_off,
356                                      len - DTLS1_HM_HEADER_LENGTH);
357
358             dtls1_write_message_header(s,
359                                        (unsigned char *)&s->init_buf->
360                                        data[s->init_off]);
361         }
362
363         ret = dtls1_write_bytes(s, type, &s->init_buf->data[s->init_off],
364                                 len);
365         if (ret < 0) {
366             /*
367              * might need to update MTU here, but we don't know which
368              * previous packet caused the failure -- so can't really
369              * retransmit anything.  continue as if everything is fine and
370              * wait for an alert to handle the retransmit
371              */
372             if (retry && BIO_ctrl(SSL_get_wbio(s),
373                                   BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0) {
374                 if (!(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
375                     if (!dtls1_query_mtu(s))
376                         return -1;
377                     /* Have one more go */
378                     retry = 0;
379                 } else
380                     return -1;
381             } else {
382                 return (-1);
383             }
384         } else {
385
386             /*
387              * bad if this assert fails, only part of the handshake message
388              * got sent.  but why would this happen?
389              */
390             OPENSSL_assert(len == (unsigned int)ret);
391
392             if (type == SSL3_RT_HANDSHAKE && !s->d1->retransmitting) {
393                 /*
394                  * should not be done for 'Hello Request's, but in that case
395                  * we'll ignore the result anyway
396                  */
397                 unsigned char *p =
398                     (unsigned char *)&s->init_buf->data[s->init_off];
399                 const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
400                 int xlen;
401
402                 if (frag_off == 0 && s->version != DTLS1_BAD_VER) {
403                     /*
404                      * reconstruct message header is if it is being sent in
405                      * single fragment
406                      */
407                     *p++ = msg_hdr->type;
408                     l2n3(msg_hdr->msg_len, p);
409                     s2n(msg_hdr->seq, p);
410                     l2n3(0, p);
411                     l2n3(msg_hdr->msg_len, p);
412                     p -= DTLS1_HM_HEADER_LENGTH;
413                     xlen = ret;
414                 } else {
415                     p += DTLS1_HM_HEADER_LENGTH;
416                     xlen = ret - DTLS1_HM_HEADER_LENGTH;
417                 }
418
419                 ssl3_finish_mac(s, p, xlen);
420             }
421
422             if (ret == s->init_num) {
423                 if (s->msg_callback)
424                     s->msg_callback(1, s->version, type, s->init_buf->data,
425                                     (size_t)(s->init_off + s->init_num), s,
426                                     s->msg_callback_arg);
427
428                 s->init_off = 0; /* done writing this message */
429                 s->init_num = 0;
430
431                 return (1);
432             }
433             s->init_off += ret;
434             s->init_num -= ret;
435             frag_off += (ret -= DTLS1_HM_HEADER_LENGTH);
436         }
437     }
438     return (0);
439 }
440
441 /*
442  * Obtain handshake message of message type 'mt' (any if mt == -1), maximum
443  * acceptable body length 'max'. Read an entire handshake message.  Handshake
444  * messages arrive in fragments.
445  */
446 long dtls1_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok)
447 {
448     int i, al;
449     struct hm_header_st *msg_hdr;
450     unsigned char *p;
451     unsigned long msg_len;
452
453     /*
454      * s3->tmp is used to store messages that are unexpected, caused by the
455      * absence of an optional handshake message
456      */
457     if (s->s3->tmp.reuse_message) {
458         if ((mt >= 0) && (s->s3->tmp.message_type != mt)) {
459             al = SSL_AD_UNEXPECTED_MESSAGE;
460             SSLerr(SSL_F_DTLS1_GET_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
461             goto f_err;
462         }
463         *ok = 1;
464
465
466         /*
467          * Messages reused from dtls1_listen also have the record header in
468          * the buffer which we need to skip over.
469          */
470         if (s->s3->tmp.reuse_message == DTLS1_SKIP_RECORD_HEADER) {
471             s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH
472                           + DTLS1_RT_HEADER_LENGTH;
473         } else {
474             s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
475         }
476         s->init_num = (int)s->s3->tmp.message_size;
477         s->s3->tmp.reuse_message = 0;
478         return s->init_num;
479     }
480
481     msg_hdr = &s->d1->r_msg_hdr;
482     memset(msg_hdr, 0, sizeof(*msg_hdr));
483
484  again:
485     i = dtls1_get_message_fragment(s, st1, stn, mt, ok);
486     if (i == DTLS1_HM_BAD_FRAGMENT || i == DTLS1_HM_FRAGMENT_RETRY) {
487         /* bad fragment received */
488         goto again;
489     } else if (i <= 0 && !*ok) {
490         return i;
491     }
492
493     if (mt >= 0 && s->s3->tmp.message_type != mt) {
494         al = SSL_AD_UNEXPECTED_MESSAGE;
495         SSLerr(SSL_F_DTLS1_GET_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
496         goto f_err;
497     }
498
499     p = (unsigned char *)s->init_buf->data;
500
501     if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
502         if (s->msg_callback) {
503             s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
504                             p, 1, s, s->msg_callback_arg);
505         }
506         /*
507          * This isn't a real handshake message so skip the processing below.
508          * dtls1_get_message_fragment() will never return a CCS if mt == -1,
509          * so we are ok to continue in that case.
510          */
511         return i;
512     }
513
514     msg_len = msg_hdr->msg_len;
515
516     /* reconstruct message header */
517     *(p++) = msg_hdr->type;
518     l2n3(msg_len, p);
519     s2n(msg_hdr->seq, p);
520     l2n3(0, p);
521     l2n3(msg_len, p);
522     if (s->version != DTLS1_BAD_VER) {
523         p -= DTLS1_HM_HEADER_LENGTH;
524         msg_len += DTLS1_HM_HEADER_LENGTH;
525     }
526
527     if (msg_len > (unsigned long)max) {
528         al = SSL_AD_ILLEGAL_PARAMETER;
529         SSLerr(SSL_F_DTLS1_GET_MESSAGE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
530         goto f_err;
531     }
532
533     ssl3_finish_mac(s, p, msg_len);
534     if (s->msg_callback)
535         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
536                         p, msg_len, s, s->msg_callback_arg);
537
538     memset(msg_hdr, 0, sizeof(*msg_hdr));
539
540     s->d1->handshake_read_seq++;
541
542
543     s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
544     return s->init_num;
545
546  f_err:
547     ssl3_send_alert(s, SSL3_AL_FATAL, al);
548     *ok = 0;
549     return -1;
550 }
551
552 int dtls_get_message(SSL *s, int *mt, unsigned long *len)
553 {
554     struct hm_header_st *msg_hdr;
555     unsigned char *p;
556     unsigned long msg_len;
557     int ok;
558     long tmplen;
559
560     msg_hdr = &s->d1->r_msg_hdr;
561     memset(msg_hdr, 0, sizeof(*msg_hdr));
562
563  again:
564     ok = dtls_get_reassembled_message(s, &tmplen);
565     if (tmplen == DTLS1_HM_BAD_FRAGMENT
566         || tmplen == DTLS1_HM_FRAGMENT_RETRY) {
567         /* bad fragment received */
568         goto again;
569     } else if (tmplen <= 0 && !ok) {
570         return 0;
571     }
572
573     *mt = s->s3->tmp.message_type;
574
575     p = (unsigned char *)s->init_buf->data;
576
577     if (*mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
578         if (s->msg_callback) {
579             s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
580                             p, 1, s, s->msg_callback_arg);
581         }
582         /*
583          * This isn't a real handshake message so skip the processing below.
584          */
585         return 1;
586     }
587
588     msg_len = msg_hdr->msg_len;
589
590     /* reconstruct message header */
591     *(p++) = msg_hdr->type;
592     l2n3(msg_len, p);
593     s2n(msg_hdr->seq, p);
594     l2n3(0, p);
595     l2n3(msg_len, p);
596     if (s->version != DTLS1_BAD_VER) {
597         p -= DTLS1_HM_HEADER_LENGTH;
598         msg_len += DTLS1_HM_HEADER_LENGTH;
599     }
600
601     ssl3_finish_mac(s, p, msg_len);
602     if (s->msg_callback)
603         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
604                         p, msg_len, s, s->msg_callback_arg);
605
606     memset(msg_hdr, 0, sizeof(*msg_hdr));
607
608     s->d1->handshake_read_seq++;
609
610
611     s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
612     *len = s->init_num;
613
614     return 1;
615 }
616
617 static int dtls1_preprocess_fragment(SSL *s, struct hm_header_st *msg_hdr)
618 {
619     size_t frag_off, frag_len, msg_len;
620
621     msg_len = msg_hdr->msg_len;
622     frag_off = msg_hdr->frag_off;
623     frag_len = msg_hdr->frag_len;
624
625     /* sanity checking */
626     if ((frag_off + frag_len) > msg_len) {
627         SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, SSL_R_EXCESSIVE_MESSAGE_SIZE);
628         return SSL_AD_ILLEGAL_PARAMETER;
629     }
630
631     if (s->d1->r_msg_hdr.frag_off == 0) { /* first fragment */
632         /*
633          * msg_len is limited to 2^24, but is effectively checked against max
634          * above
635          */
636         if (!BUF_MEM_grow_clean
637             (s->init_buf, msg_len + DTLS1_HM_HEADER_LENGTH)) {
638             SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, ERR_R_BUF_LIB);
639             return SSL_AD_INTERNAL_ERROR;
640         }
641
642         s->s3->tmp.message_size = msg_len;
643         s->d1->r_msg_hdr.msg_len = msg_len;
644         s->s3->tmp.message_type = msg_hdr->type;
645         s->d1->r_msg_hdr.type = msg_hdr->type;
646         s->d1->r_msg_hdr.seq = msg_hdr->seq;
647     } else if (msg_len != s->d1->r_msg_hdr.msg_len) {
648         /*
649          * They must be playing with us! BTW, failure to enforce upper limit
650          * would open possibility for buffer overrun.
651          */
652         SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, SSL_R_EXCESSIVE_MESSAGE_SIZE);
653         return SSL_AD_ILLEGAL_PARAMETER;
654     }
655
656     return 0;                   /* no error */
657 }
658
659 static int dtls1_retrieve_buffered_fragment(SSL *s, int *ok)
660 {
661     /*-
662      * (0) check whether the desired fragment is available
663      * if so:
664      * (1) copy over the fragment to s->init_buf->data[]
665      * (2) update s->init_num
666      */
667     pitem *item;
668     hm_fragment *frag;
669     int al;
670
671     *ok = 0;
672     item = pqueue_peek(s->d1->buffered_messages);
673     if (item == NULL)
674         return 0;
675
676     frag = (hm_fragment *)item->data;
677
678     /* Don't return if reassembly still in progress */
679     if (frag->reassembly != NULL)
680         return 0;
681
682     if (s->d1->handshake_read_seq == frag->msg_header.seq) {
683         unsigned long frag_len = frag->msg_header.frag_len;
684         pqueue_pop(s->d1->buffered_messages);
685
686         al = dtls1_preprocess_fragment(s, &frag->msg_header);
687
688         if (al == 0) {          /* no alert */
689             unsigned char *p =
690                 (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
691             memcpy(&p[frag->msg_header.frag_off], frag->fragment,
692                    frag->msg_header.frag_len);
693         }
694
695         dtls1_hm_fragment_free(frag);
696         pitem_free(item);
697
698         if (al == 0) {
699             *ok = 1;
700             return frag_len;
701         }
702
703         ssl3_send_alert(s, SSL3_AL_FATAL, al);
704         s->init_num = 0;
705         *ok = 0;
706         return -1;
707     } else
708         return 0;
709 }
710
711 /*
712  * dtls1_max_handshake_message_len returns the maximum number of bytes
713  * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but
714  * may be greater if the maximum certificate list size requires it.
715  */
716 static unsigned long dtls1_max_handshake_message_len(const SSL *s)
717 {
718     unsigned long max_len =
719         DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
720     if (max_len < (unsigned long)s->max_cert_list)
721         return s->max_cert_list;
722     return max_len;
723 }
724
725 static int
726 dtls1_reassemble_fragment(SSL *s, const struct hm_header_st *msg_hdr, int *ok)
727 {
728     hm_fragment *frag = NULL;
729     pitem *item = NULL;
730     int i = -1, is_complete;
731     unsigned char seq64be[8];
732     unsigned long frag_len = msg_hdr->frag_len;
733
734     if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len ||
735         msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
736         goto err;
737
738     if (frag_len == 0)
739         return DTLS1_HM_FRAGMENT_RETRY;
740
741     /* Try to find item in queue */
742     memset(seq64be, 0, sizeof(seq64be));
743     seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
744     seq64be[7] = (unsigned char)msg_hdr->seq;
745     item = pqueue_find(s->d1->buffered_messages, seq64be);
746
747     if (item == NULL) {
748         frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
749         if (frag == NULL)
750             goto err;
751         memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
752         frag->msg_header.frag_len = frag->msg_header.msg_len;
753         frag->msg_header.frag_off = 0;
754     } else {
755         frag = (hm_fragment *)item->data;
756         if (frag->msg_header.msg_len != msg_hdr->msg_len) {
757             item = NULL;
758             frag = NULL;
759             goto err;
760         }
761     }
762
763     /*
764      * If message is already reassembled, this must be a retransmit and can
765      * be dropped. In this case item != NULL and so frag does not need to be
766      * freed.
767      */
768     if (frag->reassembly == NULL) {
769         unsigned char devnull[256];
770
771         while (frag_len) {
772             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
773                                           devnull,
774                                           frag_len >
775                                           sizeof(devnull) ? sizeof(devnull) :
776                                           frag_len, 0);
777             if (i <= 0)
778                 goto err;
779             frag_len -= i;
780         }
781         return DTLS1_HM_FRAGMENT_RETRY;
782     }
783
784     /* read the body of the fragment (header has already been read */
785     i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
786                                   frag->fragment + msg_hdr->frag_off,
787                                   frag_len, 0);
788     if ((unsigned long)i != frag_len)
789         i = -1;
790     if (i <= 0)
791         goto err;
792
793     RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
794                         (long)(msg_hdr->frag_off + frag_len));
795
796     RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
797                                is_complete);
798
799     if (is_complete) {
800         OPENSSL_free(frag->reassembly);
801         frag->reassembly = NULL;
802     }
803
804     if (item == NULL) {
805         item = pitem_new(seq64be, frag);
806         if (item == NULL) {
807             i = -1;
808             goto err;
809         }
810
811         item = pqueue_insert(s->d1->buffered_messages, item);
812         /*
813          * pqueue_insert fails iff a duplicate item is inserted. However,
814          * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
815          * would have returned it and control would never have reached this
816          * branch.
817          */
818         OPENSSL_assert(item != NULL);
819     }
820
821     return DTLS1_HM_FRAGMENT_RETRY;
822
823  err:
824     if (item == NULL)
825         dtls1_hm_fragment_free(frag);
826     *ok = 0;
827     return i;
828 }
829
830 static int
831 dtls1_process_out_of_seq_message(SSL *s, const struct hm_header_st *msg_hdr,
832                                  int *ok)
833 {
834     int i = -1;
835     hm_fragment *frag = NULL;
836     pitem *item = NULL;
837     unsigned char seq64be[8];
838     unsigned long frag_len = msg_hdr->frag_len;
839
840     if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
841         goto err;
842
843     /* Try to find item in queue, to prevent duplicate entries */
844     memset(seq64be, 0, sizeof(seq64be));
845     seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
846     seq64be[7] = (unsigned char)msg_hdr->seq;
847     item = pqueue_find(s->d1->buffered_messages, seq64be);
848
849     /*
850      * If we already have an entry and this one is a fragment, don't discard
851      * it and rather try to reassemble it.
852      */
853     if (item != NULL && frag_len != msg_hdr->msg_len)
854         item = NULL;
855
856     /*
857      * Discard the message if sequence number was already there, is too far
858      * in the future, already in the queue or if we received a FINISHED
859      * before the SERVER_HELLO, which then must be a stale retransmit.
860      */
861     if (msg_hdr->seq <= s->d1->handshake_read_seq ||
862         msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL ||
863         (s->d1->handshake_read_seq == 0 && msg_hdr->type == SSL3_MT_FINISHED))
864     {
865         unsigned char devnull[256];
866
867         while (frag_len) {
868             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
869                                           devnull,
870                                           frag_len >
871                                           sizeof(devnull) ? sizeof(devnull) :
872                                           frag_len, 0);
873             if (i <= 0)
874                 goto err;
875             frag_len -= i;
876         }
877     } else {
878         if (frag_len != msg_hdr->msg_len)
879             return dtls1_reassemble_fragment(s, msg_hdr, ok);
880
881         if (frag_len > dtls1_max_handshake_message_len(s))
882             goto err;
883
884         frag = dtls1_hm_fragment_new(frag_len, 0);
885         if (frag == NULL)
886             goto err;
887
888         memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
889
890         if (frag_len) {
891             /*
892              * read the body of the fragment (header has already been read
893              */
894             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
895                                           frag->fragment, frag_len, 0);
896             if ((unsigned long)i != frag_len)
897                 i = -1;
898             if (i <= 0)
899                 goto err;
900         }
901
902         item = pitem_new(seq64be, frag);
903         if (item == NULL)
904             goto err;
905
906         item = pqueue_insert(s->d1->buffered_messages, item);
907         /*
908          * pqueue_insert fails iff a duplicate item is inserted. However,
909          * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
910          * would have returned it. Then, either |frag_len| !=
911          * |msg_hdr->msg_len| in which case |item| is set to NULL and it will
912          * have been processed with |dtls1_reassemble_fragment|, above, or
913          * the record will have been discarded.
914          */
915         OPENSSL_assert(item != NULL);
916     }
917
918     return DTLS1_HM_FRAGMENT_RETRY;
919
920  err:
921     if (item == NULL)
922         dtls1_hm_fragment_free(frag);
923     *ok = 0;
924     return i;
925 }
926
927 static long
928 dtls1_get_message_fragment(SSL *s, int st1, int stn, int mt, int *ok)
929 {
930     long len;
931
932     do {
933         *ok = dtls_get_reassembled_message(s, &len);
934         /* A CCS isn't a real handshake message, so if we get one there is no
935          * message sequence number to give us confidence that this was really
936          * intended to be at this point in the handshake sequence. Therefore we
937          * only allow this if we were explicitly looking for it (i.e. if |mt|
938          * is -1 we still don't allow it). If we get one when we're not
939          * expecting it then probably something got re-ordered or this is a
940          * retransmit. We should drop this and try again.
941          */
942     } while (*ok && mt != SSL3_MT_CHANGE_CIPHER_SPEC
943              && s->s3->tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC);
944
945     if (*ok)
946         s->state = stn;
947
948     return len;
949 }
950
951 static int dtls_get_reassembled_message(SSL *s, long *len)
952 {
953     unsigned char wire[DTLS1_HM_HEADER_LENGTH];
954     unsigned long mlen, frag_off, frag_len;
955     int i, al, recvd_type;
956     struct hm_header_st msg_hdr;
957     int ok;
958
959  redo:
960     /* see if we have the required fragment already */
961     if ((frag_len = dtls1_retrieve_buffered_fragment(s, &ok)) || ok) {
962         if (ok)
963             s->init_num = frag_len;
964         *len = frag_len;
965         return ok;
966     }
967
968     /* read handshake message header */
969     i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type, wire,
970                                   DTLS1_HM_HEADER_LENGTH, 0);
971     if (i <= 0) {               /* nbio, or an error */
972         s->rwstate = SSL_READING;
973         *len = i;
974         return 0;
975     }
976     if(recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
977         if (wire[0] != SSL3_MT_CCS) {
978             al = SSL_AD_UNEXPECTED_MESSAGE;
979             SSLerr(SSL_F_DTLS_GET_REASSEMBLED_MESSAGE,
980                    SSL_R_BAD_CHANGE_CIPHER_SPEC);
981             goto f_err;
982         }
983
984         memcpy(s->init_buf->data, wire, i);
985         s->init_num = i - 1;
986         s->init_msg = s->init_buf->data + 1;
987         s->s3->tmp.message_type = SSL3_MT_CHANGE_CIPHER_SPEC;
988         s->s3->tmp.message_size = i - 1;
989         *len = i - 1;
990         return 1;
991     }
992
993     /* Handshake fails if message header is incomplete */
994     if (i != DTLS1_HM_HEADER_LENGTH) {
995         al = SSL_AD_UNEXPECTED_MESSAGE;
996         SSLerr(SSL_F_DTLS_GET_REASSEMBLED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
997         goto f_err;
998     }
999
1000     /* parse the message fragment header */
1001     dtls1_get_message_header(wire, &msg_hdr);
1002
1003     mlen = msg_hdr.msg_len;
1004     frag_off = msg_hdr.frag_off;
1005     frag_len = msg_hdr.frag_len;
1006
1007     /*
1008      * We must have at least frag_len bytes left in the record to be read.
1009      * Fragments must not span records.
1010      */
1011     if (frag_len > RECORD_LAYER_get_rrec_length(&s->rlayer)) {
1012         al = SSL3_AD_ILLEGAL_PARAMETER;
1013         SSLerr(SSL_F_DTLS_GET_REASSEMBLED_MESSAGE, SSL_R_BAD_LENGTH);
1014         goto f_err;
1015     }
1016
1017     /*
1018      * if this is a future (or stale) message it gets buffered
1019      * (or dropped)--no further processing at this time
1020      * While listening, we accept seq 1 (ClientHello with cookie)
1021      * although we're still expecting seq 0 (ClientHello)
1022      */
1023     if (msg_hdr.seq != s->d1->handshake_read_seq) {
1024         *len = dtls1_process_out_of_seq_message(s, &msg_hdr, &ok);
1025         return ok;
1026     }
1027
1028     if (frag_len && frag_len < mlen) {
1029         *len = dtls1_reassemble_fragment(s, &msg_hdr, &ok);
1030         return ok;
1031     }
1032
1033     if (!s->server && s->d1->r_msg_hdr.frag_off == 0 &&
1034         wire[0] == SSL3_MT_HELLO_REQUEST) {
1035         /*
1036          * The server may always send 'Hello Request' messages -- we are
1037          * doing a handshake anyway now, so ignore them if their format is
1038          * correct. Does not count for 'Finished' MAC.
1039          */
1040         if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) {
1041             if (s->msg_callback)
1042                 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1043                                 wire, DTLS1_HM_HEADER_LENGTH, s,
1044                                 s->msg_callback_arg);
1045
1046             s->init_num = 0;
1047             goto redo;
1048         } else {                /* Incorrectly formated Hello request */
1049
1050             al = SSL_AD_UNEXPECTED_MESSAGE;
1051             SSLerr(SSL_F_DTLS_GET_REASSEMBLED_MESSAGE,
1052                    SSL_R_UNEXPECTED_MESSAGE);
1053             goto f_err;
1054         }
1055     }
1056
1057     if ((al = dtls1_preprocess_fragment(s, &msg_hdr)))
1058         goto f_err;
1059
1060     if (frag_len > 0) {
1061         unsigned char *p =
1062             (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
1063
1064         i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
1065                                       &p[frag_off], frag_len, 0);
1066
1067         /*
1068          * This shouldn't ever fail due to NBIO because we already checked
1069          * that we have enough data in the record
1070          */
1071         if (i <= 0) {
1072             s->rwstate = SSL_READING;
1073             *len = i;
1074             return 0;
1075         }
1076     } else
1077         i = 0;
1078
1079     /*
1080      * XDTLS: an incorrectly formatted fragment should cause the handshake
1081      * to fail
1082      */
1083     if (i != (int)frag_len) {
1084         al = SSL3_AD_ILLEGAL_PARAMETER;
1085         SSLerr(SSL_F_DTLS_GET_REASSEMBLED_MESSAGE, SSL3_AD_ILLEGAL_PARAMETER);
1086         goto f_err;
1087     }
1088
1089     /*
1090      * Note that s->init_num is *not* used as current offset in
1091      * s->init_buf->data, but as a counter summing up fragments' lengths: as
1092      * soon as they sum up to handshake packet length, we assume we have got
1093      * all the fragments.
1094      */
1095     *len = s->init_num = frag_len;
1096     return 1;
1097
1098  f_err:
1099     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1100     s->init_num = 0;
1101     *len = -1;
1102     return 0;
1103 }
1104
1105 /*-
1106  * for these 2 messages, we need to
1107  * ssl->enc_read_ctx                    re-init
1108  * ssl->rlayer.read_sequence            zero
1109  * ssl->s3->read_mac_secret             re-init
1110  * ssl->session->read_sym_enc           assign
1111  * ssl->session->read_compression       assign
1112  * ssl->session->read_hash              assign
1113  */
1114 int dtls1_send_change_cipher_spec(SSL *s, int a, int b)
1115 {
1116     unsigned char *p;
1117
1118     if (s->state == a) {
1119         p = (unsigned char *)s->init_buf->data;
1120         *p++ = SSL3_MT_CCS;
1121         s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1122         s->init_num = DTLS1_CCS_HEADER_LENGTH;
1123
1124         if (s->version == DTLS1_BAD_VER) {
1125             s->d1->next_handshake_write_seq++;
1126             s2n(s->d1->handshake_write_seq, p);
1127             s->init_num += 2;
1128         }
1129
1130         s->init_off = 0;
1131
1132         dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
1133                                      s->d1->handshake_write_seq, 0, 0);
1134
1135         /* buffer the message to handle re-xmits */
1136         if (!dtls1_buffer_message(s, 1)) {
1137             SSLerr(SSL_F_DTLS1_SEND_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
1138             return -1;
1139         }
1140
1141         s->state = b;
1142     }
1143
1144     /* SSL3_ST_CW_CHANGE_B */
1145     return (dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC));
1146 }
1147
1148 int dtls1_read_failed(SSL *s, int code)
1149 {
1150     if (code > 0) {
1151         fprintf(stderr, "invalid state reached %s:%d", __FILE__, __LINE__);
1152         return 1;
1153     }
1154
1155     if (!dtls1_is_timer_expired(s)) {
1156         /*
1157          * not a timeout, none of our business, let higher layers handle
1158          * this.  in fact it's probably an error
1159          */
1160         return code;
1161     }
1162 #ifndef OPENSSL_NO_HEARTBEATS
1163     /* done, no need to send a retransmit */
1164     if (!SSL_in_init(s) && !s->tlsext_hb_pending)
1165 #else
1166     /* done, no need to send a retransmit */
1167     if (!SSL_in_init(s))
1168 #endif
1169     {
1170         BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
1171         return code;
1172     }
1173
1174     return dtls1_handle_timeout(s);
1175 }
1176
1177 int dtls1_get_queue_priority(unsigned short seq, int is_ccs)
1178 {
1179     /*
1180      * The index of the retransmission queue actually is the message sequence
1181      * number, since the queue only contains messages of a single handshake.
1182      * However, the ChangeCipherSpec has no message sequence number and so
1183      * using only the sequence will result in the CCS and Finished having the
1184      * same index. To prevent this, the sequence number is multiplied by 2.
1185      * In case of a CCS 1 is subtracted. This does not only differ CSS and
1186      * Finished, it also maintains the order of the index (important for
1187      * priority queues) and fits in the unsigned short variable.
1188      */
1189     return seq * 2 - is_ccs;
1190 }
1191
1192 int dtls1_retransmit_buffered_messages(SSL *s)
1193 {
1194     pqueue sent = s->d1->sent_messages;
1195     piterator iter;
1196     pitem *item;
1197     hm_fragment *frag;
1198     int found = 0;
1199
1200     iter = pqueue_iterator(sent);
1201
1202     for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
1203         frag = (hm_fragment *)item->data;
1204         if (dtls1_retransmit_message(s, (unsigned short)
1205                                      dtls1_get_queue_priority
1206                                      (frag->msg_header.seq,
1207                                       frag->msg_header.is_ccs), 0,
1208                                      &found) <= 0 && found) {
1209             fprintf(stderr, "dtls1_retransmit_message() failed\n");
1210             return -1;
1211         }
1212     }
1213
1214     return 1;
1215 }
1216
1217 int dtls1_buffer_message(SSL *s, int is_ccs)
1218 {
1219     pitem *item;
1220     hm_fragment *frag;
1221     unsigned char seq64be[8];
1222
1223     /*
1224      * this function is called immediately after a message has been
1225      * serialized
1226      */
1227     OPENSSL_assert(s->init_off == 0);
1228
1229     frag = dtls1_hm_fragment_new(s->init_num, 0);
1230     if (!frag)
1231         return 0;
1232
1233     memcpy(frag->fragment, s->init_buf->data, s->init_num);
1234
1235     if (is_ccs) {
1236         /* For DTLS1_BAD_VER the header length is non-standard */
1237         OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
1238                        ((s->version==DTLS1_BAD_VER)?3:DTLS1_CCS_HEADER_LENGTH)
1239                        == (unsigned int)s->init_num);
1240     } else {
1241         OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
1242                        DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num);
1243     }
1244
1245     frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
1246     frag->msg_header.seq = s->d1->w_msg_hdr.seq;
1247     frag->msg_header.type = s->d1->w_msg_hdr.type;
1248     frag->msg_header.frag_off = 0;
1249     frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
1250     frag->msg_header.is_ccs = is_ccs;
1251
1252     /* save current state */
1253     frag->msg_header.saved_retransmit_state.enc_write_ctx = s->enc_write_ctx;
1254     frag->msg_header.saved_retransmit_state.write_hash = s->write_hash;
1255     frag->msg_header.saved_retransmit_state.compress = s->compress;
1256     frag->msg_header.saved_retransmit_state.session = s->session;
1257     frag->msg_header.saved_retransmit_state.epoch =
1258         DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer);
1259
1260     memset(seq64be, 0, sizeof(seq64be));
1261     seq64be[6] =
1262         (unsigned
1263          char)(dtls1_get_queue_priority(frag->msg_header.seq,
1264                                         frag->msg_header.is_ccs) >> 8);
1265     seq64be[7] =
1266         (unsigned
1267          char)(dtls1_get_queue_priority(frag->msg_header.seq,
1268                                         frag->msg_header.is_ccs));
1269
1270     item = pitem_new(seq64be, frag);
1271     if (item == NULL) {
1272         dtls1_hm_fragment_free(frag);
1273         return 0;
1274     }
1275
1276     pqueue_insert(s->d1->sent_messages, item);
1277     return 1;
1278 }
1279
1280 int
1281 dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off,
1282                          int *found)
1283 {
1284     int ret;
1285     /* XDTLS: for now assuming that read/writes are blocking */
1286     pitem *item;
1287     hm_fragment *frag;
1288     unsigned long header_length;
1289     unsigned char seq64be[8];
1290     struct dtls1_retransmit_state saved_state;
1291
1292     /*-
1293       OPENSSL_assert(s->init_num == 0);
1294       OPENSSL_assert(s->init_off == 0);
1295      */
1296
1297     /* XDTLS:  the requested message ought to be found, otherwise error */
1298     memset(seq64be, 0, sizeof(seq64be));
1299     seq64be[6] = (unsigned char)(seq >> 8);
1300     seq64be[7] = (unsigned char)seq;
1301
1302     item = pqueue_find(s->d1->sent_messages, seq64be);
1303     if (item == NULL) {
1304         fprintf(stderr, "retransmit:  message %d non-existant\n", seq);
1305         *found = 0;
1306         return 0;
1307     }
1308
1309     *found = 1;
1310     frag = (hm_fragment *)item->data;
1311
1312     if (frag->msg_header.is_ccs)
1313         header_length = DTLS1_CCS_HEADER_LENGTH;
1314     else
1315         header_length = DTLS1_HM_HEADER_LENGTH;
1316
1317     memcpy(s->init_buf->data, frag->fragment,
1318            frag->msg_header.msg_len + header_length);
1319     s->init_num = frag->msg_header.msg_len + header_length;
1320
1321     dtls1_set_message_header_int(s, frag->msg_header.type,
1322                                  frag->msg_header.msg_len,
1323                                  frag->msg_header.seq, 0,
1324                                  frag->msg_header.frag_len);
1325
1326     /* save current state */
1327     saved_state.enc_write_ctx = s->enc_write_ctx;
1328     saved_state.write_hash = s->write_hash;
1329     saved_state.compress = s->compress;
1330     saved_state.session = s->session;
1331     saved_state.epoch = DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer);
1332
1333     s->d1->retransmitting = 1;
1334
1335     /* restore state in which the message was originally sent */
1336     s->enc_write_ctx = frag->msg_header.saved_retransmit_state.enc_write_ctx;
1337     s->write_hash = frag->msg_header.saved_retransmit_state.write_hash;
1338     s->compress = frag->msg_header.saved_retransmit_state.compress;
1339     s->session = frag->msg_header.saved_retransmit_state.session;
1340     DTLS_RECORD_LAYER_set_saved_w_epoch(&s->rlayer,
1341         frag->msg_header.saved_retransmit_state.epoch);
1342
1343     ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
1344                          SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
1345
1346     /* restore current state */
1347     s->enc_write_ctx = saved_state.enc_write_ctx;
1348     s->write_hash = saved_state.write_hash;
1349     s->compress = saved_state.compress;
1350     s->session = saved_state.session;
1351     DTLS_RECORD_LAYER_set_saved_w_epoch(&s->rlayer, saved_state.epoch);
1352
1353     s->d1->retransmitting = 0;
1354
1355     (void)BIO_flush(SSL_get_wbio(s));
1356     return ret;
1357 }
1358
1359 /* call this function when the buffered messages are no longer needed */
1360 void dtls1_clear_record_buffer(SSL *s)
1361 {
1362     pitem *item;
1363
1364     for (item = pqueue_pop(s->d1->sent_messages);
1365          item != NULL; item = pqueue_pop(s->d1->sent_messages)) {
1366         dtls1_hm_fragment_free((hm_fragment *)item->data);
1367         pitem_free(item);
1368     }
1369 }
1370
1371 void dtls1_set_message_header(SSL *s, unsigned char *p,
1372                                         unsigned char mt, unsigned long len,
1373                                         unsigned long frag_off,
1374                                         unsigned long frag_len)
1375 {
1376     if (frag_off == 0) {
1377         s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1378         s->d1->next_handshake_write_seq++;
1379     }
1380
1381     dtls1_set_message_header_int(s, mt, len, s->d1->handshake_write_seq,
1382                                  frag_off, frag_len);
1383 }
1384
1385 /* don't actually do the writing, wait till the MTU has been retrieved */
1386 static void
1387 dtls1_set_message_header_int(SSL *s, unsigned char mt,
1388                              unsigned long len, unsigned short seq_num,
1389                              unsigned long frag_off, unsigned long frag_len)
1390 {
1391     struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1392
1393     msg_hdr->type = mt;
1394     msg_hdr->msg_len = len;
1395     msg_hdr->seq = seq_num;
1396     msg_hdr->frag_off = frag_off;
1397     msg_hdr->frag_len = frag_len;
1398 }
1399
1400 static void
1401 dtls1_fix_message_header(SSL *s, unsigned long frag_off,
1402                          unsigned long frag_len)
1403 {
1404     struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1405
1406     msg_hdr->frag_off = frag_off;
1407     msg_hdr->frag_len = frag_len;
1408 }
1409
1410 static unsigned char *dtls1_write_message_header(SSL *s, unsigned char *p)
1411 {
1412     struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1413
1414     *p++ = msg_hdr->type;
1415     l2n3(msg_hdr->msg_len, p);
1416
1417     s2n(msg_hdr->seq, p);
1418     l2n3(msg_hdr->frag_off, p);
1419     l2n3(msg_hdr->frag_len, p);
1420
1421     return p;
1422 }
1423
1424 unsigned int dtls1_link_min_mtu(void)
1425 {
1426     return (g_probable_mtu[(sizeof(g_probable_mtu) /
1427                             sizeof(g_probable_mtu[0])) - 1]);
1428 }
1429
1430 unsigned int dtls1_min_mtu(SSL *s)
1431 {
1432     return dtls1_link_min_mtu() - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
1433 }
1434
1435 void
1436 dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr)
1437 {
1438     memset(msg_hdr, 0, sizeof(*msg_hdr));
1439     msg_hdr->type = *(data++);
1440     n2l3(data, msg_hdr->msg_len);
1441
1442     n2s(data, msg_hdr->seq);
1443     n2l3(data, msg_hdr->frag_off);
1444     n2l3(data, msg_hdr->frag_len);
1445 }
1446
1447 int dtls1_shutdown(SSL *s)
1448 {
1449     int ret;
1450 #ifndef OPENSSL_NO_SCTP
1451     BIO *wbio;
1452
1453     wbio = SSL_get_wbio(s);
1454     if (wbio != NULL && BIO_dgram_is_sctp(wbio) &&
1455         !(s->shutdown & SSL_SENT_SHUTDOWN)) {
1456         ret = BIO_dgram_sctp_wait_for_dry(wbio);
1457         if (ret < 0)
1458             return -1;
1459
1460         if (ret == 0)
1461             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 1,
1462                      NULL);
1463     }
1464 #endif
1465     ret = ssl3_shutdown(s);
1466 #ifndef OPENSSL_NO_SCTP
1467     BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 0, NULL);
1468 #endif
1469     return ret;
1470 }
1471
1472 #ifndef OPENSSL_NO_HEARTBEATS
1473 int dtls1_process_heartbeat(SSL *s, unsigned char *p, unsigned int length)
1474 {
1475     unsigned char *pl;
1476     unsigned short hbtype;
1477     unsigned int payload;
1478     unsigned int padding = 16;  /* Use minimum padding */
1479
1480     if (s->msg_callback)
1481         s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
1482                         p, length, s, s->msg_callback_arg);
1483
1484     /* Read type and payload length first */
1485     if (1 + 2 + 16 > length)
1486         return 0;               /* silently discard */
1487     if (length > SSL3_RT_MAX_PLAIN_LENGTH)
1488         return 0;               /* silently discard per RFC 6520 sec. 4 */
1489
1490     hbtype = *p++;
1491     n2s(p, payload);
1492     if (1 + 2 + payload + 16 > length)
1493         return 0;               /* silently discard per RFC 6520 sec. 4 */
1494     pl = p;
1495
1496     if (hbtype == TLS1_HB_REQUEST) {
1497         unsigned char *buffer, *bp;
1498         unsigned int write_length = 1 /* heartbeat type */  +
1499             2 /* heartbeat length */  +
1500             payload + padding;
1501         int r;
1502
1503         if (write_length > SSL3_RT_MAX_PLAIN_LENGTH)
1504             return 0;
1505
1506         /*
1507          * Allocate memory for the response, size is 1 byte message type,
1508          * plus 2 bytes payload length, plus payload, plus padding
1509          */
1510         buffer = OPENSSL_malloc(write_length);
1511         if (buffer == NULL)
1512             return -1;
1513         bp = buffer;
1514
1515         /* Enter response type, length and copy payload */
1516         *bp++ = TLS1_HB_RESPONSE;
1517         s2n(payload, bp);
1518         memcpy(bp, pl, payload);
1519         bp += payload;
1520         /* Random padding */
1521         if (RAND_bytes(bp, padding) <= 0) {
1522             OPENSSL_free(buffer);
1523             return -1;
1524         }
1525
1526         r = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, write_length);
1527
1528         if (r >= 0 && s->msg_callback)
1529             s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
1530                             buffer, write_length, s, s->msg_callback_arg);
1531
1532         OPENSSL_free(buffer);
1533
1534         if (r < 0)
1535             return r;
1536     } else if (hbtype == TLS1_HB_RESPONSE) {
1537         unsigned int seq;
1538
1539         /*
1540          * We only send sequence numbers (2 bytes unsigned int), and 16
1541          * random bytes, so we just try to read the sequence number
1542          */
1543         n2s(pl, seq);
1544
1545         if (payload == 18 && seq == s->tlsext_hb_seq) {
1546             dtls1_stop_timer(s);
1547             s->tlsext_hb_seq++;
1548             s->tlsext_hb_pending = 0;
1549         }
1550     }
1551
1552     return 0;
1553 }
1554
1555 int dtls1_heartbeat(SSL *s)
1556 {
1557     unsigned char *buf, *p;
1558     int ret = -1;
1559     unsigned int payload = 18;  /* Sequence number + random bytes */
1560     unsigned int padding = 16;  /* Use minimum padding */
1561
1562     /* Only send if peer supports and accepts HB requests... */
1563     if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
1564         s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS) {
1565         SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
1566         return -1;
1567     }
1568
1569     /* ...and there is none in flight yet... */
1570     if (s->tlsext_hb_pending) {
1571         SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PENDING);
1572         return -1;
1573     }
1574
1575     /* ...and no handshake in progress. */
1576     if (SSL_in_init(s) || s->in_handshake) {
1577         SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_UNEXPECTED_MESSAGE);
1578         return -1;
1579     }
1580
1581     /*
1582      * Check if padding is too long, payload and padding must not exceed 2^14
1583      * - 3 = 16381 bytes in total.
1584      */
1585     OPENSSL_assert(payload + padding <= 16381);
1586
1587     /*-
1588      * Create HeartBeat message, we just use a sequence number
1589      * as payload to distuingish different messages and add
1590      * some random stuff.
1591      *  - Message Type, 1 byte
1592      *  - Payload Length, 2 bytes (unsigned int)
1593      *  - Payload, the sequence number (2 bytes uint)
1594      *  - Payload, random bytes (16 bytes uint)
1595      *  - Padding
1596      */
1597     buf = OPENSSL_malloc(1 + 2 + payload + padding);
1598     if (buf == NULL) {
1599         SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_MALLOC_FAILURE);
1600         return -1;
1601     }
1602     p = buf;
1603     /* Message Type */
1604     *p++ = TLS1_HB_REQUEST;
1605     /* Payload length (18 bytes here) */
1606     s2n(payload, p);
1607     /* Sequence number */
1608     s2n(s->tlsext_hb_seq, p);
1609     /* 16 random bytes */
1610     if (RAND_bytes(p, 16) <= 0) {
1611         SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
1612         goto err;
1613     }
1614     p += 16;
1615     /* Random padding */
1616     if (RAND_bytes(p, padding) <= 0) {
1617         SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
1618         goto err;
1619     }
1620
1621     ret = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
1622     if (ret >= 0) {
1623         if (s->msg_callback)
1624             s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
1625                             buf, 3 + payload + padding,
1626                             s, s->msg_callback_arg);
1627
1628         dtls1_start_timer(s);
1629         s->tlsext_hb_pending = 1;
1630     }
1631
1632  err:
1633     OPENSSL_free(buf);
1634
1635     return ret;
1636 }
1637 #endif