RAND_bytes updates
[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, long max,
164                                        int *ok);
165
166 static hm_fragment *dtls1_hm_fragment_new(unsigned long frag_len,
167                                           int reassembly)
168 {
169     hm_fragment *frag = NULL;
170     unsigned char *buf = NULL;
171     unsigned char *bitmask = NULL;
172
173     frag = (hm_fragment *)OPENSSL_malloc(sizeof(hm_fragment));
174     if (frag == NULL)
175         return NULL;
176
177     if (frag_len) {
178         buf = (unsigned char *)OPENSSL_malloc(frag_len);
179         if (buf == NULL) {
180             OPENSSL_free(frag);
181             return NULL;
182         }
183     }
184
185     /* zero length fragment gets zero frag->fragment */
186     frag->fragment = buf;
187
188     /* Initialize reassembly bitmask if necessary */
189     if (reassembly) {
190         bitmask =
191             (unsigned char *)OPENSSL_malloc(RSMBLY_BITMASK_SIZE(frag_len));
192         if (bitmask == NULL) {
193             if (buf != NULL)
194                 OPENSSL_free(buf);
195             OPENSSL_free(frag);
196             return NULL;
197         }
198         memset(bitmask, 0, RSMBLY_BITMASK_SIZE(frag_len));
199     }
200
201     frag->reassembly = bitmask;
202
203     return frag;
204 }
205
206 void dtls1_hm_fragment_free(hm_fragment *frag)
207 {
208
209     if (frag->msg_header.is_ccs) {
210         EVP_CIPHER_CTX_free(frag->msg_header.
211                             saved_retransmit_state.enc_write_ctx);
212         EVP_MD_CTX_destroy(frag->msg_header.
213                            saved_retransmit_state.write_hash);
214     }
215     if (frag->fragment)
216         OPENSSL_free(frag->fragment);
217     if (frag->reassembly)
218         OPENSSL_free(frag->reassembly);
219     OPENSSL_free(frag);
220 }
221
222 static int dtls1_query_mtu(SSL *s)
223 {
224     if (s->d1->link_mtu) {
225         s->d1->mtu =
226             s->d1->link_mtu - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
227         s->d1->link_mtu = 0;
228     }
229
230     /* AHA!  Figure out the MTU, and stick to the right size */
231     if (s->d1->mtu < dtls1_min_mtu(s)) {
232         if (!(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
233             s->d1->mtu =
234                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
235
236             /*
237              * I've seen the kernel return bogus numbers when it doesn't know
238              * (initial write), so just make sure we have a reasonable number
239              */
240             if (s->d1->mtu < dtls1_min_mtu(s)) {
241                 /* Set to min mtu */
242                 s->d1->mtu = dtls1_min_mtu(s);
243                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
244                          s->d1->mtu, NULL);
245             }
246         } else
247             return 0;
248     }
249     return 1;
250 }
251
252 /*
253  * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
254  * SSL3_RT_CHANGE_CIPHER_SPEC)
255  */
256 int dtls1_do_write(SSL *s, int type)
257 {
258     int ret;
259     unsigned int curr_mtu;
260     int retry = 1;
261     unsigned int len, frag_off, mac_size, blocksize, used_len;
262
263     if (!dtls1_query_mtu(s))
264         return -1;
265
266     OPENSSL_assert(s->d1->mtu >= dtls1_min_mtu(s)); /* should have something
267                                                      * reasonable now */
268
269     if (s->init_off == 0 && type == SSL3_RT_HANDSHAKE)
270         OPENSSL_assert(s->init_num ==
271                        (int)s->d1->w_msg_hdr.msg_len +
272                        DTLS1_HM_HEADER_LENGTH);
273
274     if (s->write_hash) {
275         if (s->enc_write_ctx
276             && EVP_CIPHER_CTX_mode(s->enc_write_ctx) == EVP_CIPH_GCM_MODE)
277             mac_size = 0;
278         else
279             mac_size = EVP_MD_CTX_size(s->write_hash);
280     } else
281         mac_size = 0;
282
283     if (s->enc_write_ctx &&
284         (EVP_CIPHER_CTX_mode(s->enc_write_ctx) == EVP_CIPH_CBC_MODE))
285         blocksize = 2 * EVP_CIPHER_block_size(s->enc_write_ctx->cipher);
286     else
287         blocksize = 0;
288
289     frag_off = 0;
290     /* s->init_num shouldn't ever be < 0...but just in case */
291     while (s->init_num > 0) {
292         used_len = BIO_wpending(SSL_get_wbio(s)) + DTLS1_RT_HEADER_LENGTH
293             + mac_size + blocksize;
294         if (s->d1->mtu > used_len)
295             curr_mtu = s->d1->mtu - used_len;
296         else
297             curr_mtu = 0;
298
299         if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
300             /*
301              * grr.. we could get an error if MTU picked was wrong
302              */
303             ret = BIO_flush(SSL_get_wbio(s));
304             if (ret <= 0)
305                 return ret;
306             used_len = DTLS1_RT_HEADER_LENGTH + mac_size + blocksize;
307             if (s->d1->mtu > used_len + DTLS1_HM_HEADER_LENGTH) {
308                 curr_mtu = s->d1->mtu - used_len;
309             } else {
310                 /* Shouldn't happen */
311                 return -1;
312             }
313         }
314
315         /*
316          * We just checked that s->init_num > 0 so this cast should be safe
317          */
318         if (((unsigned int)s->init_num) > curr_mtu)
319             len = curr_mtu;
320         else
321             len = s->init_num;
322
323         /* Shouldn't ever happen */
324         if (len > INT_MAX)
325             len = INT_MAX;
326
327         /*
328          * XDTLS: this function is too long.  split out the CCS part
329          */
330         if (type == SSL3_RT_HANDSHAKE) {
331             if (s->init_off != 0) {
332                 OPENSSL_assert(s->init_off > DTLS1_HM_HEADER_LENGTH);
333                 s->init_off -= DTLS1_HM_HEADER_LENGTH;
334                 s->init_num += DTLS1_HM_HEADER_LENGTH;
335
336                 /*
337                  * We just checked that s->init_num > 0 so this cast should
338                  * be safe
339                  */
340                 if (((unsigned int)s->init_num) > curr_mtu)
341                     len = curr_mtu;
342                 else
343                     len = s->init_num;
344             }
345
346             /* Shouldn't ever happen */
347             if (len > INT_MAX)
348                 len = INT_MAX;
349
350             if (len < DTLS1_HM_HEADER_LENGTH) {
351                 /*
352                  * len is so small that we really can't do anything sensible
353                  * so fail
354                  */
355                 return -1;
356             }
357             dtls1_fix_message_header(s, frag_off,
358                                      len - DTLS1_HM_HEADER_LENGTH);
359
360             dtls1_write_message_header(s,
361                                        (unsigned char *)&s->init_buf->
362                                        data[s->init_off]);
363         }
364
365         ret = dtls1_write_bytes(s, type, &s->init_buf->data[s->init_off],
366                                 len);
367         if (ret < 0) {
368             /*
369              * might need to update MTU here, but we don't know which
370              * previous packet caused the failure -- so can't really
371              * retransmit anything.  continue as if everything is fine and
372              * wait for an alert to handle the retransmit
373              */
374             if (retry && BIO_ctrl(SSL_get_wbio(s),
375                                   BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0) {
376                 if (!(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
377                     if (!dtls1_query_mtu(s))
378                         return -1;
379                     /* Have one more go */
380                     retry = 0;
381                 } else
382                     return -1;
383             } else {
384                 return (-1);
385             }
386         } else {
387
388             /*
389              * bad if this assert fails, only part of the handshake message
390              * got sent.  but why would this happen?
391              */
392             OPENSSL_assert(len == (unsigned int)ret);
393
394             if (type == SSL3_RT_HANDSHAKE && !s->d1->retransmitting) {
395                 /*
396                  * should not be done for 'Hello Request's, but in that case
397                  * we'll ignore the result anyway
398                  */
399                 unsigned char *p =
400                     (unsigned char *)&s->init_buf->data[s->init_off];
401                 const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
402                 int xlen;
403
404                 if (frag_off == 0 && s->version != DTLS1_BAD_VER) {
405                     /*
406                      * reconstruct message header is if it is being sent in
407                      * single fragment
408                      */
409                     *p++ = msg_hdr->type;
410                     l2n3(msg_hdr->msg_len, p);
411                     s2n(msg_hdr->seq, p);
412                     l2n3(0, p);
413                     l2n3(msg_hdr->msg_len, p);
414                     p -= DTLS1_HM_HEADER_LENGTH;
415                     xlen = ret;
416                 } else {
417                     p += DTLS1_HM_HEADER_LENGTH;
418                     xlen = ret - DTLS1_HM_HEADER_LENGTH;
419                 }
420
421                 ssl3_finish_mac(s, p, xlen);
422             }
423
424             if (ret == s->init_num) {
425                 if (s->msg_callback)
426                     s->msg_callback(1, s->version, type, s->init_buf->data,
427                                     (size_t)(s->init_off + s->init_num), s,
428                                     s->msg_callback_arg);
429
430                 s->init_off = 0; /* done writing this message */
431                 s->init_num = 0;
432
433                 return (1);
434             }
435             s->init_off += ret;
436             s->init_num -= ret;
437             frag_off += (ret -= DTLS1_HM_HEADER_LENGTH);
438         }
439     }
440     return (0);
441 }
442
443 /*
444  * Obtain handshake message of message type 'mt' (any if mt == -1), maximum
445  * acceptable body length 'max'. Read an entire handshake message.  Handshake
446  * messages arrive in fragments.
447  */
448 long dtls1_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok)
449 {
450     int i, al;
451     struct hm_header_st *msg_hdr;
452     unsigned char *p;
453     unsigned long msg_len;
454
455     /*
456      * s3->tmp is used to store messages that are unexpected, caused by the
457      * absence of an optional handshake message
458      */
459     if (s->s3->tmp.reuse_message) {
460         s->s3->tmp.reuse_message = 0;
461         if ((mt >= 0) && (s->s3->tmp.message_type != mt)) {
462             al = SSL_AD_UNEXPECTED_MESSAGE;
463             SSLerr(SSL_F_DTLS1_GET_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
464             goto f_err;
465         }
466         *ok = 1;
467         s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
468         s->init_num = (int)s->s3->tmp.message_size;
469         return s->init_num;
470     }
471
472     msg_hdr = &s->d1->r_msg_hdr;
473     memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
474
475  again:
476     i = dtls1_get_message_fragment(s, st1, stn, max, ok);
477     if (i == DTLS1_HM_BAD_FRAGMENT || i == DTLS1_HM_FRAGMENT_RETRY) {
478         /* bad fragment received */
479         goto again;
480     } else if (i <= 0 && !*ok) {
481         return i;
482     }
483
484     p = (unsigned char *)s->init_buf->data;
485     msg_len = msg_hdr->msg_len;
486
487     /* reconstruct message header */
488     *(p++) = msg_hdr->type;
489     l2n3(msg_len, p);
490     s2n(msg_hdr->seq, p);
491     l2n3(0, p);
492     l2n3(msg_len, p);
493     if (s->version != DTLS1_BAD_VER) {
494         p -= DTLS1_HM_HEADER_LENGTH;
495         msg_len += DTLS1_HM_HEADER_LENGTH;
496     }
497
498     ssl3_finish_mac(s, p, msg_len);
499     if (s->msg_callback)
500         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
501                         p, msg_len, s, s->msg_callback_arg);
502
503     memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
504
505     /* Don't change sequence numbers while listening */
506     if (!s->d1->listen)
507         s->d1->handshake_read_seq++;
508
509     s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
510     return s->init_num;
511
512  f_err:
513     ssl3_send_alert(s, SSL3_AL_FATAL, al);
514     *ok = 0;
515     return -1;
516 }
517
518 static int dtls1_preprocess_fragment(SSL *s, struct hm_header_st *msg_hdr,
519                                      int max)
520 {
521     size_t frag_off, frag_len, msg_len;
522
523     msg_len = msg_hdr->msg_len;
524     frag_off = msg_hdr->frag_off;
525     frag_len = msg_hdr->frag_len;
526
527     /* sanity checking */
528     if ((frag_off + frag_len) > msg_len) {
529         SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, SSL_R_EXCESSIVE_MESSAGE_SIZE);
530         return SSL_AD_ILLEGAL_PARAMETER;
531     }
532
533     if ((frag_off + frag_len) > (unsigned long)max) {
534         SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, SSL_R_EXCESSIVE_MESSAGE_SIZE);
535         return SSL_AD_ILLEGAL_PARAMETER;
536     }
537
538     if (s->d1->r_msg_hdr.frag_off == 0) { /* first fragment */
539         /*
540          * msg_len is limited to 2^24, but is effectively checked against max
541          * above
542          */
543         if (!BUF_MEM_grow_clean
544             (s->init_buf, msg_len + DTLS1_HM_HEADER_LENGTH)) {
545             SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, ERR_R_BUF_LIB);
546             return SSL_AD_INTERNAL_ERROR;
547         }
548
549         s->s3->tmp.message_size = msg_len;
550         s->d1->r_msg_hdr.msg_len = msg_len;
551         s->s3->tmp.message_type = msg_hdr->type;
552         s->d1->r_msg_hdr.type = msg_hdr->type;
553         s->d1->r_msg_hdr.seq = msg_hdr->seq;
554     } else if (msg_len != s->d1->r_msg_hdr.msg_len) {
555         /*
556          * They must be playing with us! BTW, failure to enforce upper limit
557          * would open possibility for buffer overrun.
558          */
559         SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, SSL_R_EXCESSIVE_MESSAGE_SIZE);
560         return SSL_AD_ILLEGAL_PARAMETER;
561     }
562
563     return 0;                   /* no error */
564 }
565
566 static int dtls1_retrieve_buffered_fragment(SSL *s, long max, int *ok)
567 {
568     /*-
569      * (0) check whether the desired fragment is available
570      * if so:
571      * (1) copy over the fragment to s->init_buf->data[]
572      * (2) update s->init_num
573      */
574     pitem *item;
575     hm_fragment *frag;
576     int al;
577
578     *ok = 0;
579     item = pqueue_peek(s->d1->buffered_messages);
580     if (item == NULL)
581         return 0;
582
583     frag = (hm_fragment *)item->data;
584
585     /* Don't return if reassembly still in progress */
586     if (frag->reassembly != NULL)
587         return 0;
588
589     if (s->d1->handshake_read_seq == frag->msg_header.seq) {
590         unsigned long frag_len = frag->msg_header.frag_len;
591         pqueue_pop(s->d1->buffered_messages);
592
593         al = dtls1_preprocess_fragment(s, &frag->msg_header, max);
594
595         if (al == 0) {          /* no alert */
596             unsigned char *p =
597                 (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
598             memcpy(&p[frag->msg_header.frag_off], frag->fragment,
599                    frag->msg_header.frag_len);
600         }
601
602         dtls1_hm_fragment_free(frag);
603         pitem_free(item);
604
605         if (al == 0) {
606             *ok = 1;
607             return frag_len;
608         }
609
610         ssl3_send_alert(s, SSL3_AL_FATAL, al);
611         s->init_num = 0;
612         *ok = 0;
613         return -1;
614     } else
615         return 0;
616 }
617
618 /*
619  * dtls1_max_handshake_message_len returns the maximum number of bytes
620  * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but
621  * may be greater if the maximum certificate list size requires it.
622  */
623 static unsigned long dtls1_max_handshake_message_len(const SSL *s)
624 {
625     unsigned long max_len =
626         DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
627     if (max_len < (unsigned long)s->max_cert_list)
628         return s->max_cert_list;
629     return max_len;
630 }
631
632 static int
633 dtls1_reassemble_fragment(SSL *s, const struct hm_header_st *msg_hdr, int *ok)
634 {
635     hm_fragment *frag = NULL;
636     pitem *item = NULL;
637     int i = -1, is_complete;
638     unsigned char seq64be[8];
639     unsigned long frag_len = msg_hdr->frag_len;
640
641     if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len ||
642         msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
643         goto err;
644
645     if (frag_len == 0)
646         return DTLS1_HM_FRAGMENT_RETRY;
647
648     /* Try to find item in queue */
649     memset(seq64be, 0, sizeof(seq64be));
650     seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
651     seq64be[7] = (unsigned char)msg_hdr->seq;
652     item = pqueue_find(s->d1->buffered_messages, seq64be);
653
654     if (item == NULL) {
655         frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
656         if (frag == NULL)
657             goto err;
658         memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
659         frag->msg_header.frag_len = frag->msg_header.msg_len;
660         frag->msg_header.frag_off = 0;
661     } else {
662         frag = (hm_fragment *)item->data;
663         if (frag->msg_header.msg_len != msg_hdr->msg_len) {
664             item = NULL;
665             frag = NULL;
666             goto err;
667         }
668     }
669
670     /*
671      * If message is already reassembled, this must be a retransmit and can
672      * be dropped. In this case item != NULL and so frag does not need to be
673      * freed.
674      */
675     if (frag->reassembly == NULL) {
676         unsigned char devnull[256];
677
678         while (frag_len) {
679             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
680                                           devnull,
681                                           frag_len >
682                                           sizeof(devnull) ? sizeof(devnull) :
683                                           frag_len, 0);
684             if (i <= 0)
685                 goto err;
686             frag_len -= i;
687         }
688         return DTLS1_HM_FRAGMENT_RETRY;
689     }
690
691     /* read the body of the fragment (header has already been read */
692     i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
693                                   frag->fragment + msg_hdr->frag_off,
694                                   frag_len, 0);
695     if ((unsigned long)i != frag_len)
696         i = -1;
697     if (i <= 0)
698         goto err;
699
700     RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
701                         (long)(msg_hdr->frag_off + frag_len));
702
703     RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
704                                is_complete);
705
706     if (is_complete) {
707         OPENSSL_free(frag->reassembly);
708         frag->reassembly = NULL;
709     }
710
711     if (item == NULL) {
712         item = pitem_new(seq64be, frag);
713         if (item == NULL) {
714             i = -1;
715             goto err;
716         }
717
718         item = pqueue_insert(s->d1->buffered_messages, item);
719         /*
720          * pqueue_insert fails iff a duplicate item is inserted. However,
721          * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
722          * would have returned it and control would never have reached this
723          * branch.
724          */
725         OPENSSL_assert(item != NULL);
726     }
727
728     return DTLS1_HM_FRAGMENT_RETRY;
729
730  err:
731     if (frag != NULL && item == NULL)
732         dtls1_hm_fragment_free(frag);
733     *ok = 0;
734     return i;
735 }
736
737 static int
738 dtls1_process_out_of_seq_message(SSL *s, const struct hm_header_st *msg_hdr,
739                                  int *ok)
740 {
741     int i = -1;
742     hm_fragment *frag = NULL;
743     pitem *item = NULL;
744     unsigned char seq64be[8];
745     unsigned long frag_len = msg_hdr->frag_len;
746
747     if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
748         goto err;
749
750     /* Try to find item in queue, to prevent duplicate entries */
751     memset(seq64be, 0, sizeof(seq64be));
752     seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
753     seq64be[7] = (unsigned char)msg_hdr->seq;
754     item = pqueue_find(s->d1->buffered_messages, seq64be);
755
756     /*
757      * If we already have an entry and this one is a fragment, don't discard
758      * it and rather try to reassemble it.
759      */
760     if (item != NULL && frag_len != msg_hdr->msg_len)
761         item = NULL;
762
763     /*
764      * Discard the message if sequence number was already there, is too far
765      * in the future, already in the queue or if we received a FINISHED
766      * before the SERVER_HELLO, which then must be a stale retransmit.
767      */
768     if (msg_hdr->seq <= s->d1->handshake_read_seq ||
769         msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL ||
770         (s->d1->handshake_read_seq == 0 && msg_hdr->type == SSL3_MT_FINISHED))
771     {
772         unsigned char devnull[256];
773
774         while (frag_len) {
775             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
776                                           devnull,
777                                           frag_len >
778                                           sizeof(devnull) ? sizeof(devnull) :
779                                           frag_len, 0);
780             if (i <= 0)
781                 goto err;
782             frag_len -= i;
783         }
784     } else {
785         if (frag_len != msg_hdr->msg_len)
786             return dtls1_reassemble_fragment(s, msg_hdr, ok);
787
788         if (frag_len > dtls1_max_handshake_message_len(s))
789             goto err;
790
791         frag = dtls1_hm_fragment_new(frag_len, 0);
792         if (frag == NULL)
793             goto err;
794
795         memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
796
797         if (frag_len) {
798             /*
799              * read the body of the fragment (header has already been read
800              */
801             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
802                                           frag->fragment, frag_len, 0);
803             if ((unsigned long)i != frag_len)
804                 i = -1;
805             if (i <= 0)
806                 goto err;
807         }
808
809         item = pitem_new(seq64be, frag);
810         if (item == NULL)
811             goto err;
812
813         item = pqueue_insert(s->d1->buffered_messages, item);
814         /*
815          * pqueue_insert fails iff a duplicate item is inserted. However,
816          * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
817          * would have returned it. Then, either |frag_len| !=
818          * |msg_hdr->msg_len| in which case |item| is set to NULL and it will
819          * have been processed with |dtls1_reassemble_fragment|, above, or
820          * the record will have been discarded.
821          */
822         OPENSSL_assert(item != NULL);
823     }
824
825     return DTLS1_HM_FRAGMENT_RETRY;
826
827  err:
828     if (frag != NULL && item == NULL)
829         dtls1_hm_fragment_free(frag);
830     *ok = 0;
831     return i;
832 }
833
834 static long
835 dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok)
836 {
837     unsigned char wire[DTLS1_HM_HEADER_LENGTH];
838     unsigned long len, frag_off, frag_len;
839     int i, al;
840     struct hm_header_st msg_hdr;
841
842  redo:
843     /* see if we have the required fragment already */
844     if ((frag_len = dtls1_retrieve_buffered_fragment(s, max, ok)) || *ok) {
845         if (*ok)
846             s->init_num = frag_len;
847         return frag_len;
848     }
849
850     /* read handshake message header */
851     i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, wire,
852                                   DTLS1_HM_HEADER_LENGTH, 0);
853     if (i <= 0) {               /* nbio, or an error */
854         s->rwstate = SSL_READING;
855         *ok = 0;
856         return i;
857     }
858     /* Handshake fails if message header is incomplete */
859     if (i != DTLS1_HM_HEADER_LENGTH) {
860         al = SSL_AD_UNEXPECTED_MESSAGE;
861         SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, SSL_R_UNEXPECTED_MESSAGE);
862         goto f_err;
863     }
864
865     /* parse the message fragment header */
866     dtls1_get_message_header(wire, &msg_hdr);
867
868     /*
869      * if this is a future (or stale) message it gets buffered
870      * (or dropped)--no further processing at this time
871      * While listening, we accept seq 1 (ClientHello with cookie)
872      * although we're still expecting seq 0 (ClientHello)
873      */
874     if (msg_hdr.seq != s->d1->handshake_read_seq
875         && !(s->d1->listen && msg_hdr.seq == 1))
876         return dtls1_process_out_of_seq_message(s, &msg_hdr, ok);
877
878     len = msg_hdr.msg_len;
879     frag_off = msg_hdr.frag_off;
880     frag_len = msg_hdr.frag_len;
881
882     if (frag_len && frag_len < len)
883         return dtls1_reassemble_fragment(s, &msg_hdr, ok);
884
885     if (!s->server && s->d1->r_msg_hdr.frag_off == 0 &&
886         wire[0] == SSL3_MT_HELLO_REQUEST) {
887         /*
888          * The server may always send 'Hello Request' messages -- we are
889          * doing a handshake anyway now, so ignore them if their format is
890          * correct. Does not count for 'Finished' MAC.
891          */
892         if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) {
893             if (s->msg_callback)
894                 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
895                                 wire, DTLS1_HM_HEADER_LENGTH, s,
896                                 s->msg_callback_arg);
897
898             s->init_num = 0;
899             goto redo;
900         } else {                /* Incorrectly formated Hello request */
901
902             al = SSL_AD_UNEXPECTED_MESSAGE;
903             SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,
904                    SSL_R_UNEXPECTED_MESSAGE);
905             goto f_err;
906         }
907     }
908
909     if ((al = dtls1_preprocess_fragment(s, &msg_hdr, max)))
910         goto f_err;
911
912     /* XDTLS:  ressurect this when restart is in place */
913     s->state = stn;
914
915     if (frag_len > 0) {
916         unsigned char *p =
917             (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
918
919         i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
920                                       &p[frag_off], frag_len, 0);
921         /*
922          * XDTLS: fix this--message fragments cannot span multiple packets
923          */
924         if (i <= 0) {
925             s->rwstate = SSL_READING;
926             *ok = 0;
927             return i;
928         }
929     } else
930         i = 0;
931
932     /*
933      * XDTLS: an incorrectly formatted fragment should cause the handshake
934      * to fail
935      */
936     if (i != (int)frag_len) {
937         al = SSL3_AD_ILLEGAL_PARAMETER;
938         SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, SSL3_AD_ILLEGAL_PARAMETER);
939         goto f_err;
940     }
941
942     *ok = 1;
943
944     /*
945      * Note that s->init_num is *not* used as current offset in
946      * s->init_buf->data, but as a counter summing up fragments' lengths: as
947      * soon as they sum up to handshake packet length, we assume we have got
948      * all the fragments.
949      */
950     s->init_num = frag_len;
951     return frag_len;
952
953  f_err:
954     ssl3_send_alert(s, SSL3_AL_FATAL, al);
955     s->init_num = 0;
956
957     *ok = 0;
958     return (-1);
959 }
960
961 /*-
962  * for these 2 messages, we need to
963  * ssl->enc_read_ctx                    re-init
964  * ssl->s3->read_sequence               zero
965  * ssl->s3->read_mac_secret             re-init
966  * ssl->session->read_sym_enc           assign
967  * ssl->session->read_compression       assign
968  * ssl->session->read_hash              assign
969  */
970 int dtls1_send_change_cipher_spec(SSL *s, int a, int b)
971 {
972     unsigned char *p;
973
974     if (s->state == a) {
975         p = (unsigned char *)s->init_buf->data;
976         *p++ = SSL3_MT_CCS;
977         s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
978         s->init_num = DTLS1_CCS_HEADER_LENGTH;
979
980         if (s->version == DTLS1_BAD_VER) {
981             s->d1->next_handshake_write_seq++;
982             s2n(s->d1->handshake_write_seq, p);
983             s->init_num += 2;
984         }
985
986         s->init_off = 0;
987
988         dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
989                                      s->d1->handshake_write_seq, 0, 0);
990
991         /* buffer the message to handle re-xmits */
992         if(!dtls1_buffer_message(s, 1)) {
993             SSLerr(SSL_F_DTLS1_SEND_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
994             return -1;
995         }
996
997         s->state = b;
998     }
999
1000     /* SSL3_ST_CW_CHANGE_B */
1001     return (dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC));
1002 }
1003
1004 int dtls1_read_failed(SSL *s, int code)
1005 {
1006     if (code > 0) {
1007         fprintf(stderr, "invalid state reached %s:%d", __FILE__, __LINE__);
1008         return 1;
1009     }
1010
1011     if (!dtls1_is_timer_expired(s)) {
1012         /*
1013          * not a timeout, none of our business, let higher layers handle
1014          * this.  in fact it's probably an error
1015          */
1016         return code;
1017     }
1018 #ifndef OPENSSL_NO_HEARTBEATS
1019     /* done, no need to send a retransmit */
1020     if (!SSL_in_init(s) && !s->tlsext_hb_pending)
1021 #else
1022     /* done, no need to send a retransmit */
1023     if (!SSL_in_init(s))
1024 #endif
1025     {
1026         BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
1027         return code;
1028     }
1029
1030     return dtls1_handle_timeout(s);
1031 }
1032
1033 int dtls1_get_queue_priority(unsigned short seq, int is_ccs)
1034 {
1035     /*
1036      * The index of the retransmission queue actually is the message sequence
1037      * number, since the queue only contains messages of a single handshake.
1038      * However, the ChangeCipherSpec has no message sequence number and so
1039      * using only the sequence will result in the CCS and Finished having the
1040      * same index. To prevent this, the sequence number is multiplied by 2.
1041      * In case of a CCS 1 is subtracted. This does not only differ CSS and
1042      * Finished, it also maintains the order of the index (important for
1043      * priority queues) and fits in the unsigned short variable.
1044      */
1045     return seq * 2 - is_ccs;
1046 }
1047
1048 int dtls1_retransmit_buffered_messages(SSL *s)
1049 {
1050     pqueue sent = s->d1->sent_messages;
1051     piterator iter;
1052     pitem *item;
1053     hm_fragment *frag;
1054     int found = 0;
1055
1056     iter = pqueue_iterator(sent);
1057
1058     for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
1059         frag = (hm_fragment *)item->data;
1060         if (dtls1_retransmit_message(s, (unsigned short)
1061                                      dtls1_get_queue_priority
1062                                      (frag->msg_header.seq,
1063                                       frag->msg_header.is_ccs), 0,
1064                                      &found) <= 0 && found) {
1065             fprintf(stderr, "dtls1_retransmit_message() failed\n");
1066             return -1;
1067         }
1068     }
1069
1070     return 1;
1071 }
1072
1073 int dtls1_buffer_message(SSL *s, int is_ccs)
1074 {
1075     pitem *item;
1076     hm_fragment *frag;
1077     unsigned char seq64be[8];
1078
1079     /*
1080      * this function is called immediately after a message has been
1081      * serialized
1082      */
1083     OPENSSL_assert(s->init_off == 0);
1084
1085     frag = dtls1_hm_fragment_new(s->init_num, 0);
1086     if (!frag)
1087         return 0;
1088
1089     memcpy(frag->fragment, s->init_buf->data, s->init_num);
1090
1091     if (is_ccs) {
1092         /* For DTLS1_BAD_VER the header length is non-standard */
1093         OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
1094                        ((s->version==DTLS1_BAD_VER)?3:DTLS1_CCS_HEADER_LENGTH)
1095                        == (unsigned int)s->init_num);
1096     } else {
1097         OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
1098                        DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num);
1099     }
1100
1101     frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
1102     frag->msg_header.seq = s->d1->w_msg_hdr.seq;
1103     frag->msg_header.type = s->d1->w_msg_hdr.type;
1104     frag->msg_header.frag_off = 0;
1105     frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
1106     frag->msg_header.is_ccs = is_ccs;
1107
1108     /* save current state */
1109     frag->msg_header.saved_retransmit_state.enc_write_ctx = s->enc_write_ctx;
1110     frag->msg_header.saved_retransmit_state.write_hash = s->write_hash;
1111     frag->msg_header.saved_retransmit_state.compress = s->compress;
1112     frag->msg_header.saved_retransmit_state.session = s->session;
1113     frag->msg_header.saved_retransmit_state.epoch = s->d1->w_epoch;
1114
1115     memset(seq64be, 0, sizeof(seq64be));
1116     seq64be[6] =
1117         (unsigned
1118          char)(dtls1_get_queue_priority(frag->msg_header.seq,
1119                                         frag->msg_header.is_ccs) >> 8);
1120     seq64be[7] =
1121         (unsigned
1122          char)(dtls1_get_queue_priority(frag->msg_header.seq,
1123                                         frag->msg_header.is_ccs));
1124
1125     item = pitem_new(seq64be, frag);
1126     if (item == NULL) {
1127         dtls1_hm_fragment_free(frag);
1128         return 0;
1129     }
1130
1131     pqueue_insert(s->d1->sent_messages, item);
1132     return 1;
1133 }
1134
1135 int
1136 dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off,
1137                          int *found)
1138 {
1139     int ret;
1140     /* XDTLS: for now assuming that read/writes are blocking */
1141     pitem *item;
1142     hm_fragment *frag;
1143     unsigned long header_length;
1144     unsigned char seq64be[8];
1145     struct dtls1_retransmit_state saved_state;
1146     unsigned char save_write_sequence[8];
1147
1148     /*-
1149       OPENSSL_assert(s->init_num == 0);
1150       OPENSSL_assert(s->init_off == 0);
1151      */
1152
1153     /* XDTLS:  the requested message ought to be found, otherwise error */
1154     memset(seq64be, 0, sizeof(seq64be));
1155     seq64be[6] = (unsigned char)(seq >> 8);
1156     seq64be[7] = (unsigned char)seq;
1157
1158     item = pqueue_find(s->d1->sent_messages, seq64be);
1159     if (item == NULL) {
1160         fprintf(stderr, "retransmit:  message %d non-existant\n", seq);
1161         *found = 0;
1162         return 0;
1163     }
1164
1165     *found = 1;
1166     frag = (hm_fragment *)item->data;
1167
1168     if (frag->msg_header.is_ccs)
1169         header_length = DTLS1_CCS_HEADER_LENGTH;
1170     else
1171         header_length = DTLS1_HM_HEADER_LENGTH;
1172
1173     memcpy(s->init_buf->data, frag->fragment,
1174            frag->msg_header.msg_len + header_length);
1175     s->init_num = frag->msg_header.msg_len + header_length;
1176
1177     dtls1_set_message_header_int(s, frag->msg_header.type,
1178                                  frag->msg_header.msg_len,
1179                                  frag->msg_header.seq, 0,
1180                                  frag->msg_header.frag_len);
1181
1182     /* save current state */
1183     saved_state.enc_write_ctx = s->enc_write_ctx;
1184     saved_state.write_hash = s->write_hash;
1185     saved_state.compress = s->compress;
1186     saved_state.session = s->session;
1187     saved_state.epoch = s->d1->w_epoch;
1188     saved_state.epoch = s->d1->w_epoch;
1189
1190     s->d1->retransmitting = 1;
1191
1192     /* restore state in which the message was originally sent */
1193     s->enc_write_ctx = frag->msg_header.saved_retransmit_state.enc_write_ctx;
1194     s->write_hash = frag->msg_header.saved_retransmit_state.write_hash;
1195     s->compress = frag->msg_header.saved_retransmit_state.compress;
1196     s->session = frag->msg_header.saved_retransmit_state.session;
1197     s->d1->w_epoch = frag->msg_header.saved_retransmit_state.epoch;
1198
1199     if (frag->msg_header.saved_retransmit_state.epoch ==
1200         saved_state.epoch - 1) {
1201         memcpy(save_write_sequence, s->s3->write_sequence,
1202                sizeof(s->s3->write_sequence));
1203         memcpy(s->s3->write_sequence, s->d1->last_write_sequence,
1204                sizeof(s->s3->write_sequence));
1205     }
1206
1207     ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
1208                          SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
1209
1210     /* restore current state */
1211     s->enc_write_ctx = saved_state.enc_write_ctx;
1212     s->write_hash = saved_state.write_hash;
1213     s->compress = saved_state.compress;
1214     s->session = saved_state.session;
1215     s->d1->w_epoch = saved_state.epoch;
1216
1217     if (frag->msg_header.saved_retransmit_state.epoch ==
1218         saved_state.epoch - 1) {
1219         memcpy(s->d1->last_write_sequence, s->s3->write_sequence,
1220                sizeof(s->s3->write_sequence));
1221         memcpy(s->s3->write_sequence, save_write_sequence,
1222                sizeof(s->s3->write_sequence));
1223     }
1224
1225     s->d1->retransmitting = 0;
1226
1227     (void)BIO_flush(SSL_get_wbio(s));
1228     return ret;
1229 }
1230
1231 /* call this function when the buffered messages are no longer needed */
1232 void dtls1_clear_record_buffer(SSL *s)
1233 {
1234     pitem *item;
1235
1236     for (item = pqueue_pop(s->d1->sent_messages);
1237          item != NULL; item = pqueue_pop(s->d1->sent_messages)) {
1238         dtls1_hm_fragment_free((hm_fragment *)item->data);
1239         pitem_free(item);
1240     }
1241 }
1242
1243 void dtls1_set_message_header(SSL *s, unsigned char *p,
1244                                         unsigned char mt, unsigned long len,
1245                                         unsigned long frag_off,
1246                                         unsigned long frag_len)
1247 {
1248     /* Don't change sequence numbers while listening */
1249     if (frag_off == 0 && !s->d1->listen) {
1250         s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1251         s->d1->next_handshake_write_seq++;
1252     }
1253
1254     dtls1_set_message_header_int(s, mt, len, s->d1->handshake_write_seq,
1255                                  frag_off, frag_len);
1256 }
1257
1258 /* don't actually do the writing, wait till the MTU has been retrieved */
1259 static void
1260 dtls1_set_message_header_int(SSL *s, unsigned char mt,
1261                              unsigned long len, unsigned short seq_num,
1262                              unsigned long frag_off, unsigned long frag_len)
1263 {
1264     struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1265
1266     msg_hdr->type = mt;
1267     msg_hdr->msg_len = len;
1268     msg_hdr->seq = seq_num;
1269     msg_hdr->frag_off = frag_off;
1270     msg_hdr->frag_len = frag_len;
1271 }
1272
1273 static void
1274 dtls1_fix_message_header(SSL *s, unsigned long frag_off,
1275                          unsigned long frag_len)
1276 {
1277     struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1278
1279     msg_hdr->frag_off = frag_off;
1280     msg_hdr->frag_len = frag_len;
1281 }
1282
1283 static unsigned char *dtls1_write_message_header(SSL *s, unsigned char *p)
1284 {
1285     struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1286
1287     *p++ = msg_hdr->type;
1288     l2n3(msg_hdr->msg_len, p);
1289
1290     s2n(msg_hdr->seq, p);
1291     l2n3(msg_hdr->frag_off, p);
1292     l2n3(msg_hdr->frag_len, p);
1293
1294     return p;
1295 }
1296
1297 unsigned int dtls1_link_min_mtu(void)
1298 {
1299     return (g_probable_mtu[(sizeof(g_probable_mtu) /
1300                             sizeof(g_probable_mtu[0])) - 1]);
1301 }
1302
1303 unsigned int dtls1_min_mtu(SSL *s)
1304 {
1305     return dtls1_link_min_mtu() - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
1306 }
1307
1308 void
1309 dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr)
1310 {
1311     memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
1312     msg_hdr->type = *(data++);
1313     n2l3(data, msg_hdr->msg_len);
1314
1315     n2s(data, msg_hdr->seq);
1316     n2l3(data, msg_hdr->frag_off);
1317     n2l3(data, msg_hdr->frag_len);
1318 }
1319
1320 void dtls1_get_ccs_header(unsigned char *data, struct ccs_header_st *ccs_hdr)
1321 {
1322     memset(ccs_hdr, 0x00, sizeof(struct ccs_header_st));
1323
1324     ccs_hdr->type = *(data++);
1325 }
1326
1327 int dtls1_shutdown(SSL *s)
1328 {
1329     int ret;
1330 #ifndef OPENSSL_NO_SCTP
1331     if (BIO_dgram_is_sctp(SSL_get_wbio(s)) &&
1332         !(s->shutdown & SSL_SENT_SHUTDOWN)) {
1333         ret = BIO_dgram_sctp_wait_for_dry(SSL_get_wbio(s));
1334         if (ret < 0)
1335             return -1;
1336
1337         if (ret == 0)
1338             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 1,
1339                      NULL);
1340     }
1341 #endif
1342     ret = ssl3_shutdown(s);
1343 #ifndef OPENSSL_NO_SCTP
1344     BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 0, NULL);
1345 #endif
1346     return ret;
1347 }
1348
1349 #ifndef OPENSSL_NO_HEARTBEATS
1350 int dtls1_process_heartbeat(SSL *s)
1351 {
1352     unsigned char *p = &s->s3->rrec.data[0], *pl;
1353     unsigned short hbtype;
1354     unsigned int payload;
1355     unsigned int padding = 16;  /* Use minimum padding */
1356
1357     if (s->msg_callback)
1358         s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
1359                         &s->s3->rrec.data[0], s->s3->rrec.length,
1360                         s, s->msg_callback_arg);
1361
1362     /* Read type and payload length first */
1363     if (1 + 2 + 16 > s->s3->rrec.length)
1364         return 0;               /* silently discard */
1365     if (s->s3->rrec.length > SSL3_RT_MAX_PLAIN_LENGTH)
1366         return 0;               /* silently discard per RFC 6520 sec. 4 */
1367
1368     hbtype = *p++;
1369     n2s(p, payload);
1370     if (1 + 2 + payload + 16 > s->s3->rrec.length)
1371         return 0;               /* silently discard per RFC 6520 sec. 4 */
1372     pl = p;
1373
1374     if (hbtype == TLS1_HB_REQUEST) {
1375         unsigned char *buffer, *bp;
1376         unsigned int write_length = 1 /* heartbeat type */  +
1377             2 /* heartbeat length */  +
1378             payload + padding;
1379         int r;
1380
1381         if (write_length > SSL3_RT_MAX_PLAIN_LENGTH)
1382             return 0;
1383
1384         /*
1385          * Allocate memory for the response, size is 1 byte message type,
1386          * plus 2 bytes payload length, plus payload, plus padding
1387          */
1388         buffer = OPENSSL_malloc(write_length);
1389         if (buffer == NULL)
1390             return -1;
1391         bp = buffer;
1392
1393         /* Enter response type, length and copy payload */
1394         *bp++ = TLS1_HB_RESPONSE;
1395         s2n(payload, bp);
1396         memcpy(bp, pl, payload);
1397         bp += payload;
1398         /* Random padding */
1399         if (RAND_bytes(bp, padding) <= 0) {
1400             OPENSSL_free(buffer);
1401             return -1;
1402         }
1403
1404         r = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, write_length);
1405
1406         if (r >= 0 && s->msg_callback)
1407             s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
1408                             buffer, write_length, s, s->msg_callback_arg);
1409
1410         OPENSSL_free(buffer);
1411
1412         if (r < 0)
1413             return r;
1414     } else if (hbtype == TLS1_HB_RESPONSE) {
1415         unsigned int seq;
1416
1417         /*
1418          * We only send sequence numbers (2 bytes unsigned int), and 16
1419          * random bytes, so we just try to read the sequence number
1420          */
1421         n2s(pl, seq);
1422
1423         if (payload == 18 && seq == s->tlsext_hb_seq) {
1424             dtls1_stop_timer(s);
1425             s->tlsext_hb_seq++;
1426             s->tlsext_hb_pending = 0;
1427         }
1428     }
1429
1430     return 0;
1431 }
1432
1433 int dtls1_heartbeat(SSL *s)
1434 {
1435     unsigned char *buf, *p;
1436     int ret = -1;
1437     unsigned int payload = 18;  /* Sequence number + random bytes */
1438     unsigned int padding = 16;  /* Use minimum padding */
1439
1440     /* Only send if peer supports and accepts HB requests... */
1441     if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
1442         s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS) {
1443         SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
1444         return -1;
1445     }
1446
1447     /* ...and there is none in flight yet... */
1448     if (s->tlsext_hb_pending) {
1449         SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PENDING);
1450         return -1;
1451     }
1452
1453     /* ...and no handshake in progress. */
1454     if (SSL_in_init(s) || s->in_handshake) {
1455         SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_UNEXPECTED_MESSAGE);
1456         return -1;
1457     }
1458
1459     /*
1460      * Check if padding is too long, payload and padding must not exceed 2^14
1461      * - 3 = 16381 bytes in total.
1462      */
1463     OPENSSL_assert(payload + padding <= 16381);
1464
1465     /*-
1466      * Create HeartBeat message, we just use a sequence number
1467      * as payload to distuingish different messages and add
1468      * some random stuff.
1469      *  - Message Type, 1 byte
1470      *  - Payload Length, 2 bytes (unsigned int)
1471      *  - Payload, the sequence number (2 bytes uint)
1472      *  - Payload, random bytes (16 bytes uint)
1473      *  - Padding
1474      */
1475     buf = OPENSSL_malloc(1 + 2 + payload + padding);
1476     if (buf == NULL) {
1477         SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_MALLOC_FAILURE);
1478         return -1;
1479     }
1480     p = buf;
1481     /* Message Type */
1482     *p++ = TLS1_HB_REQUEST;
1483     /* Payload length (18 bytes here) */
1484     s2n(payload, p);
1485     /* Sequence number */
1486     s2n(s->tlsext_hb_seq, p);
1487     /* 16 random bytes */
1488     if (RAND_bytes(p, 16) <= 0) {
1489         SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
1490         goto err;
1491     }
1492     p += 16;
1493     /* Random padding */
1494     if (RAND_bytes(p, padding) <= 0) {
1495         SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
1496         goto err;
1497     }
1498
1499     ret = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
1500     if (ret >= 0) {
1501         if (s->msg_callback)
1502             s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
1503                             buf, 3 + payload + padding,
1504                             s, s->msg_callback_arg);
1505
1506         dtls1_start_timer(s);
1507         s->tlsext_hb_pending = 1;
1508     }
1509
1510  err:
1511     OPENSSL_free(buf);
1512
1513     return ret;
1514 }
1515 #endif