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