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