]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - crypto/openssl/ssl/d1_both.c
MFS: r295060, r296462, r296597-296598, r299053, r306229, r306335, r308200
[FreeBSD/stable/8.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     do {
547         item = pqueue_peek(s->d1->buffered_messages);
548         if (item == NULL)
549             return 0;
550
551         frag = (hm_fragment *)item->data;
552
553         if (frag->msg_header.seq < s->d1->handshake_read_seq) {
554             /* This is a stale message that has been buffered so clear it */
555             pqueue_pop(s->d1->buffered_messages);
556             dtls1_hm_fragment_free(frag);
557             pitem_free(item);
558             item = NULL;
559             frag = NULL;
560         }
561     } while (item == NULL);
562
563
564     /* Don't return if reassembly still in progress */
565     if (frag->reassembly != NULL)
566         return 0;
567
568     if (s->d1->handshake_read_seq == frag->msg_header.seq) {
569         unsigned long frag_len = frag->msg_header.frag_len;
570         pqueue_pop(s->d1->buffered_messages);
571
572         al = dtls1_preprocess_fragment(s, &frag->msg_header, max);
573
574         if (al == 0) {          /* no alert */
575             unsigned char *p =
576                 (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
577             memcpy(&p[frag->msg_header.frag_off], frag->fragment,
578                    frag->msg_header.frag_len);
579         }
580
581         dtls1_hm_fragment_free(frag);
582         pitem_free(item);
583
584         if (al == 0) {
585             *ok = 1;
586             return frag_len;
587         }
588
589         ssl3_send_alert(s, SSL3_AL_FATAL, al);
590         s->init_num = 0;
591         *ok = 0;
592         return -1;
593     } else
594         return 0;
595 }
596
597 /*
598  * dtls1_max_handshake_message_len returns the maximum number of bytes
599  * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but
600  * may be greater if the maximum certificate list size requires it.
601  */
602 static unsigned long dtls1_max_handshake_message_len(const SSL *s)
603 {
604     unsigned long max_len =
605         DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
606     if (max_len < (unsigned long)s->max_cert_list)
607         return s->max_cert_list;
608     return max_len;
609 }
610
611 static int
612 dtls1_reassemble_fragment(SSL *s, const struct hm_header_st *msg_hdr, int *ok)
613 {
614     hm_fragment *frag = NULL;
615     pitem *item = NULL;
616     int i = -1, is_complete;
617     PQ_64BIT seq64;
618     unsigned long frag_len = msg_hdr->frag_len;
619
620     if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len ||
621         msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
622         goto err;
623
624     if (frag_len == 0)
625         return DTLS1_HM_FRAGMENT_RETRY;
626
627     /* Try to find item in queue */
628     pq_64bit_init(&seq64);
629     pq_64bit_assign_word(&seq64, msg_hdr->seq);
630     item = pqueue_find(s->d1->buffered_messages, seq64);
631     pq_64bit_free(&seq64);
632
633     if (item == NULL) {
634         frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
635         if (frag == NULL)
636             goto err;
637         memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
638         frag->msg_header.frag_len = frag->msg_header.msg_len;
639         frag->msg_header.frag_off = 0;
640     } else {
641         frag = (hm_fragment *)item->data;
642         if (frag->msg_header.msg_len != msg_hdr->msg_len) {
643             item = NULL;
644             frag = NULL;
645             goto err;
646         }
647     }
648
649     /*
650      * If message is already reassembled, this must be a retransmit and can
651      * be dropped. In this case item != NULL and so frag does not need to be
652      * freed.
653      */
654     if (frag->reassembly == NULL) {
655         unsigned char devnull[256];
656
657         while (frag_len) {
658             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
659                                           devnull,
660                                           frag_len >
661                                           sizeof(devnull) ? sizeof(devnull) :
662                                           frag_len, 0);
663             if (i <= 0)
664                 goto err;
665             frag_len -= i;
666         }
667         return DTLS1_HM_FRAGMENT_RETRY;
668     }
669
670     /* read the body of the fragment (header has already been read */
671     i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
672                                   frag->fragment + msg_hdr->frag_off,
673                                   frag_len, 0);
674     if ((unsigned long)i != frag_len)
675         i = -1;
676     if (i <= 0)
677         goto err;
678
679     RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
680                         (long)(msg_hdr->frag_off + frag_len));
681
682     RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
683                                is_complete);
684
685     if (is_complete) {
686         OPENSSL_free(frag->reassembly);
687         frag->reassembly = NULL;
688     }
689
690     if (item == NULL) {
691         pq_64bit_init(&seq64);
692         pq_64bit_assign_word(&seq64, msg_hdr->seq);
693         item = pitem_new(seq64, frag);
694         pq_64bit_free(&seq64);
695
696         if (item == NULL) {
697             i = -1;
698             goto err;
699         }
700
701         item = pqueue_insert(s->d1->buffered_messages, item);
702         /*
703          * pqueue_insert fails iff a duplicate item is inserted. However,
704          * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
705          * would have returned it and control would never have reached this
706          * branch.
707          */
708         OPENSSL_assert(item != NULL);
709     }
710
711     return DTLS1_HM_FRAGMENT_RETRY;
712
713  err:
714     if (frag != NULL && item == NULL)
715         dtls1_hm_fragment_free(frag);
716     *ok = 0;
717     return i;
718 }
719
720 static int
721 dtls1_process_out_of_seq_message(SSL *s, const struct hm_header_st *msg_hdr,
722                                  int *ok)
723 {
724     int i = -1;
725     hm_fragment *frag = NULL;
726     pitem *item = NULL;
727     PQ_64BIT seq64;
728     unsigned long frag_len = msg_hdr->frag_len;
729
730     if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
731         goto err;
732
733     /* Try to find item in queue, to prevent duplicate entries */
734     pq_64bit_init(&seq64);
735     pq_64bit_assign_word(&seq64, msg_hdr->seq);
736     item = pqueue_find(s->d1->buffered_messages, seq64);
737     pq_64bit_free(&seq64);
738
739     /*
740      * If we already have an entry and this one is a fragment, don't discard
741      * it and rather try to reassemble it.
742      */
743     if (item != NULL && frag_len != msg_hdr->msg_len)
744         item = NULL;
745
746     /*
747      * Discard the message if sequence number was already there, is too far
748      * in the future, already in the queue or if we received a FINISHED
749      * before the SERVER_HELLO, which then must be a stale retransmit.
750      */
751     if (msg_hdr->seq <= s->d1->handshake_read_seq ||
752         msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL ||
753         (s->d1->handshake_read_seq == 0 && msg_hdr->type == SSL3_MT_FINISHED))
754     {
755         unsigned char devnull[256];
756
757         while (frag_len) {
758             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
759                                           devnull,
760                                           frag_len >
761                                           sizeof(devnull) ? sizeof(devnull) :
762                                           frag_len, 0);
763             if (i <= 0)
764                 goto err;
765             frag_len -= i;
766         }
767     } else {
768         if (frag_len != msg_hdr->msg_len)
769             return dtls1_reassemble_fragment(s, msg_hdr, ok);
770
771         if (frag_len > dtls1_max_handshake_message_len(s))
772             goto err;
773
774         frag = dtls1_hm_fragment_new(frag_len, 0);
775         if (frag == NULL)
776             goto err;
777
778         memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
779
780         if (frag_len) {
781             /*
782              * read the body of the fragment (header has already been read)
783              */
784             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
785                                           frag->fragment, frag_len, 0);
786             if ((unsigned long)i != frag_len)
787                 i = -1;
788             if (i <= 0)
789                 goto err;
790         }
791
792         pq_64bit_init(&seq64);
793         pq_64bit_assign_word(&seq64, msg_hdr->seq);
794
795         item = pitem_new(seq64, frag);
796         pq_64bit_free(&seq64);
797         if (item == NULL)
798             goto err;
799
800         item = pqueue_insert(s->d1->buffered_messages, item);
801         /*
802          * pqueue_insert fails iff a duplicate item is inserted. However,
803          * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
804          * would have returned it. Then, either |frag_len| !=
805          * |msg_hdr->msg_len| in which case |item| is set to NULL and it will
806          * have been processed with |dtls1_reassemble_fragment|, above, or
807          * the record will have been discarded.
808          */
809         OPENSSL_assert(item != NULL);
810     }
811
812     return DTLS1_HM_FRAGMENT_RETRY;
813
814  err:
815     if (frag != NULL && item == NULL)
816         dtls1_hm_fragment_free(frag);
817     *ok = 0;
818     return i;
819 }
820
821 static long
822 dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok)
823 {
824     unsigned char wire[DTLS1_HM_HEADER_LENGTH];
825     unsigned long len, frag_off, frag_len;
826     int i, al;
827     struct hm_header_st msg_hdr;
828
829  redo:
830     /* see if we have the required fragment already */
831     if ((frag_len = dtls1_retrieve_buffered_fragment(s, max, ok)) || *ok) {
832         if (*ok)
833             s->init_num = frag_len;
834         return frag_len;
835     }
836
837     /* read handshake message header */
838     i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, wire,
839                                   DTLS1_HM_HEADER_LENGTH, 0);
840     if (i <= 0) {               /* nbio, or an error */
841         s->rwstate = SSL_READING;
842         *ok = 0;
843         return i;
844     }
845     /* Handshake fails if message header is incomplete */
846     if (i != DTLS1_HM_HEADER_LENGTH) {
847         al = SSL_AD_UNEXPECTED_MESSAGE;
848         SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, SSL_R_UNEXPECTED_MESSAGE);
849         goto f_err;
850     }
851
852     /* parse the message fragment header */
853     dtls1_get_message_header(wire, &msg_hdr);
854
855     /*
856      * if this is a future (or stale) message it gets buffered
857      * (or dropped)--no further processing at this time
858      * While listening, we accept seq 1 (ClientHello with cookie)
859      * although we're still expecting seq 0 (ClientHello)
860      */
861     if (msg_hdr.seq != s->d1->handshake_read_seq
862         && !(s->d1->listen && msg_hdr.seq == 1))
863         return dtls1_process_out_of_seq_message(s, &msg_hdr, ok);
864
865     len = msg_hdr.msg_len;
866     frag_off = msg_hdr.frag_off;
867     frag_len = msg_hdr.frag_len;
868
869     if (frag_len && frag_len < len)
870         return dtls1_reassemble_fragment(s, &msg_hdr, ok);
871
872     if (!s->server && s->d1->r_msg_hdr.frag_off == 0 &&
873         wire[0] == SSL3_MT_HELLO_REQUEST) {
874         /*
875          * The server may always send 'Hello Request' messages -- we are
876          * doing a handshake anyway now, so ignore them if their format is
877          * correct. Does not count for 'Finished' MAC.
878          */
879         if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) {
880             if (s->msg_callback)
881                 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
882                                 wire, DTLS1_HM_HEADER_LENGTH, s,
883                                 s->msg_callback_arg);
884
885             s->init_num = 0;
886             goto redo;
887         } else {                /* Incorrectly formated Hello request */
888
889             al = SSL_AD_UNEXPECTED_MESSAGE;
890             SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,
891                    SSL_R_UNEXPECTED_MESSAGE);
892             goto f_err;
893         }
894     }
895
896     if ((al = dtls1_preprocess_fragment(s, &msg_hdr, max)))
897         goto f_err;
898
899     /* XDTLS:  ressurect this when restart is in place */
900     s->state = stn;
901
902     if (frag_len > 0) {
903         unsigned char *p =
904             (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
905
906         i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
907                                       &p[frag_off], frag_len, 0);
908         /*
909          * XDTLS: fix this--message fragments cannot span multiple packets
910          */
911         if (i <= 0) {
912             s->rwstate = SSL_READING;
913             *ok = 0;
914             return i;
915         }
916     } else
917         i = 0;
918
919     /*
920      * XDTLS: an incorrectly formatted fragment should cause the handshake
921      * to fail
922      */
923     if (i != (int)frag_len) {
924         al = SSL3_AD_ILLEGAL_PARAMETER;
925         SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, SSL3_AD_ILLEGAL_PARAMETER);
926         goto f_err;
927     }
928
929     *ok = 1;
930
931     /*
932      * Note that s->init_num is *not* used as current offset in
933      * s->init_buf->data, but as a counter summing up fragments' lengths: as
934      * soon as they sum up to handshake packet length, we assume we have got
935      * all the fragments.
936      */
937     s->init_num = frag_len;
938     return frag_len;
939
940  f_err:
941     ssl3_send_alert(s, SSL3_AL_FATAL, al);
942     s->init_num = 0;
943
944     *ok = 0;
945     return (-1);
946 }
947
948 int dtls1_send_finished(SSL *s, int a, int b, const char *sender, int slen)
949 {
950     unsigned char *p, *d;
951     int i;
952     unsigned long l;
953
954     if (s->state == a) {
955         d = (unsigned char *)s->init_buf->data;
956         p = &(d[DTLS1_HM_HEADER_LENGTH]);
957
958         i = s->method->ssl3_enc->final_finish_mac(s,
959                                                   &(s->s3->finish_dgst1),
960                                                   &(s->s3->finish_dgst2),
961                                                   sender, slen,
962                                                   s->s3->tmp.finish_md);
963         s->s3->tmp.finish_md_len = i;
964         memcpy(p, s->s3->tmp.finish_md, i);
965         p += i;
966         l = i;
967
968         /*
969          * Copy the finished so we can use it for renegotiation checks
970          */
971         if (s->type == SSL_ST_CONNECT) {
972             OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
973             memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md, i);
974             s->s3->previous_client_finished_len = i;
975         } else {
976             OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
977             memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md, i);
978             s->s3->previous_server_finished_len = i;
979         }
980
981 #ifdef OPENSSL_SYS_WIN16
982         /*
983          * MSVC 1.5 does not clear the top bytes of the word unless I do
984          * this.
985          */
986         l &= 0xffff;
987 #endif
988
989         d = dtls1_set_message_header(s, d, SSL3_MT_FINISHED, l, 0, l);
990         s->init_num = (int)l + DTLS1_HM_HEADER_LENGTH;
991         s->init_off = 0;
992
993         /* buffer the message to handle re-xmits */
994         dtls1_buffer_message(s, 0);
995
996         s->state = b;
997     }
998
999     /* SSL3_ST_SEND_xxxxxx_HELLO_B */
1000     return (dtls1_do_write(s, SSL3_RT_HANDSHAKE));
1001 }
1002
1003 /*-
1004  * for these 2 messages, we need to
1005  * ssl->enc_read_ctx                    re-init
1006  * ssl->s3->read_sequence               zero
1007  * ssl->s3->read_mac_secret             re-init
1008  * ssl->session->read_sym_enc           assign
1009  * ssl->session->read_compression       assign
1010  * ssl->session->read_hash              assign
1011  */
1012 int dtls1_send_change_cipher_spec(SSL *s, int a, int b)
1013 {
1014     unsigned char *p;
1015
1016     if (s->state == a) {
1017         p = (unsigned char *)s->init_buf->data;
1018         *p++ = SSL3_MT_CCS;
1019         s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1020         s->init_num = DTLS1_CCS_HEADER_LENGTH;
1021
1022         if (s->client_version == DTLS1_BAD_VER) {
1023             s->d1->next_handshake_write_seq++;
1024             s2n(s->d1->handshake_write_seq, p);
1025             s->init_num += 2;
1026         }
1027
1028         s->init_off = 0;
1029
1030         dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
1031                                      s->d1->handshake_write_seq, 0, 0);
1032
1033         /* buffer the message to handle re-xmits */
1034         dtls1_buffer_message(s, 1);
1035
1036         s->state = b;
1037     }
1038
1039     /* SSL3_ST_CW_CHANGE_B */
1040     return (dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC));
1041 }
1042
1043 static int dtls1_add_cert_to_buf(BUF_MEM *buf, unsigned long *l, X509 *x)
1044 {
1045     int n;
1046     unsigned char *p;
1047
1048     n = i2d_X509(x, NULL);
1049     if (!BUF_MEM_grow_clean(buf, (int)(n + (*l) + 3))) {
1050         SSLerr(SSL_F_DTLS1_ADD_CERT_TO_BUF, ERR_R_BUF_LIB);
1051         return 0;
1052     }
1053     p = (unsigned char *)&(buf->data[*l]);
1054     l2n3(n, p);
1055     i2d_X509(x, &p);
1056     *l += n + 3;
1057
1058     return 1;
1059 }
1060
1061 unsigned long dtls1_output_cert_chain(SSL *s, X509 *x)
1062 {
1063     unsigned char *p;
1064     int i;
1065     unsigned long l = 3 + DTLS1_HM_HEADER_LENGTH;
1066     BUF_MEM *buf;
1067
1068     /* TLSv1 sends a chain with nothing in it, instead of an alert */
1069     buf = s->init_buf;
1070     if (!BUF_MEM_grow_clean(buf, 10)) {
1071         SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN, ERR_R_BUF_LIB);
1072         return (0);
1073     }
1074     if (x != NULL) {
1075         X509_STORE_CTX xs_ctx;
1076
1077         if (!X509_STORE_CTX_init(&xs_ctx, s->ctx->cert_store, x, NULL)) {
1078             SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN, ERR_R_X509_LIB);
1079             return (0);
1080         }
1081
1082         X509_verify_cert(&xs_ctx);
1083         /* Don't leave errors in the queue */
1084         ERR_clear_error();
1085         for (i = 0; i < sk_X509_num(xs_ctx.chain); i++) {
1086             x = sk_X509_value(xs_ctx.chain, i);
1087
1088             if (!dtls1_add_cert_to_buf(buf, &l, x)) {
1089                 X509_STORE_CTX_cleanup(&xs_ctx);
1090                 return 0;
1091             }
1092         }
1093         X509_STORE_CTX_cleanup(&xs_ctx);
1094     }
1095     /* Thawte special :-) */
1096     for (i = 0; i < sk_X509_num(s->ctx->extra_certs); i++) {
1097         x = sk_X509_value(s->ctx->extra_certs, i);
1098         if (!dtls1_add_cert_to_buf(buf, &l, x))
1099             return 0;
1100     }
1101
1102     l -= (3 + DTLS1_HM_HEADER_LENGTH);
1103
1104     p = (unsigned char *)&(buf->data[DTLS1_HM_HEADER_LENGTH]);
1105     l2n3(l, p);
1106     l += 3;
1107     p = (unsigned char *)&(buf->data[0]);
1108     p = dtls1_set_message_header(s, p, SSL3_MT_CERTIFICATE, l, 0, l);
1109
1110     l += DTLS1_HM_HEADER_LENGTH;
1111     return (l);
1112 }
1113
1114 int dtls1_read_failed(SSL *s, int code)
1115 {
1116     if (code > 0) {
1117         fprintf(stderr, "invalid state reached %s:%d", __FILE__, __LINE__);
1118         return 1;
1119     }
1120
1121     if (!dtls1_is_timer_expired(s)) {
1122         /*
1123          * not a timeout, none of our business, let higher layers handle
1124          * this.  in fact it's probably an error
1125          */
1126         return code;
1127     }
1128
1129     /* done, no need to send a retransmit */
1130     if (!SSL_in_init(s)) {
1131         BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
1132         return code;
1133     }
1134 #if 0                           /* for now, each alert contains only one
1135                                  * record number */
1136     item = pqueue_peek(state->rcvd_records);
1137     if (item) {
1138         /* send an alert immediately for all the missing records */
1139     } else
1140 #endif
1141
1142 #if 0                           /* no more alert sending, just retransmit the
1143                                  * last set of messages */
1144     if (state->timeout.read_timeouts >= DTLS1_TMO_READ_COUNT)
1145         ssl3_send_alert(s, SSL3_AL_WARNING,
1146                         DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
1147 #endif
1148
1149     return dtls1_handle_timeout(s);
1150 }
1151
1152 int dtls1_get_queue_priority(unsigned short seq, int is_ccs)
1153 {
1154     /*
1155      * The index of the retransmission queue actually is the message sequence
1156      * number, since the queue only contains messages of a single handshake.
1157      * However, the ChangeCipherSpec has no message sequence number and so
1158      * using only the sequence will result in the CCS and Finished having the
1159      * same index. To prevent this, the sequence number is multiplied by 2.
1160      * In case of a CCS 1 is subtracted. This does not only differ CSS and
1161      * Finished, it also maintains the order of the index (important for
1162      * priority queues) and fits in the unsigned short variable.
1163      */
1164     return seq * 2 - is_ccs;
1165 }
1166
1167 int dtls1_retransmit_buffered_messages(SSL *s)
1168 {
1169     pqueue sent = s->d1->sent_messages;
1170     piterator iter;
1171     pitem *item;
1172     hm_fragment *frag;
1173     int found = 0;
1174
1175     iter = pqueue_iterator(sent);
1176
1177     for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
1178         frag = (hm_fragment *)item->data;
1179         if (dtls1_retransmit_message(s, (unsigned short)
1180                                      dtls1_get_queue_priority
1181                                      (frag->msg_header.seq,
1182                                       frag->msg_header.is_ccs), 0,
1183                                      &found) <= 0 && found) {
1184             fprintf(stderr, "dtls1_retransmit_message() failed\n");
1185             return -1;
1186         }
1187     }
1188
1189     return 1;
1190 }
1191
1192 int dtls1_buffer_message(SSL *s, int is_ccs)
1193 {
1194     pitem *item;
1195     hm_fragment *frag;
1196     PQ_64BIT seq64;
1197
1198     /*
1199      * this function is called immediately after a message has been
1200      * serialized
1201      */
1202     OPENSSL_assert(s->init_off == 0);
1203
1204     frag = dtls1_hm_fragment_new(s->init_num, 0);
1205     if (!frag)
1206         return 0;
1207
1208     memcpy(frag->fragment, s->init_buf->data, s->init_num);
1209
1210     if (is_ccs) {
1211         OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
1212                        DTLS1_CCS_HEADER_LENGTH <= (unsigned int)s->init_num);
1213     } else {
1214         OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
1215                        DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num);
1216     }
1217
1218     frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
1219     frag->msg_header.seq = s->d1->w_msg_hdr.seq;
1220     frag->msg_header.type = s->d1->w_msg_hdr.type;
1221     frag->msg_header.frag_off = 0;
1222     frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
1223     frag->msg_header.is_ccs = is_ccs;
1224
1225     /* save current state */
1226     frag->msg_header.saved_retransmit_state.enc_write_ctx = s->enc_write_ctx;
1227     frag->msg_header.saved_retransmit_state.write_hash = s->write_hash;
1228     frag->msg_header.saved_retransmit_state.compress = s->compress;
1229     frag->msg_header.saved_retransmit_state.session = s->session;
1230     frag->msg_header.saved_retransmit_state.epoch = s->d1->w_epoch;
1231
1232     pq_64bit_init(&seq64);
1233
1234     pq_64bit_assign_word(&seq64,
1235                          dtls1_get_queue_priority(frag->msg_header.seq,
1236                                                   frag->msg_header.is_ccs));
1237
1238     item = pitem_new(seq64, frag);
1239     pq_64bit_free(&seq64);
1240     if (item == NULL) {
1241         dtls1_hm_fragment_free(frag);
1242         return 0;
1243     }
1244 #if 0
1245     fprintf(stderr, "buffered messge: \ttype = %xx\n", msg_buf->type);
1246     fprintf(stderr, "\t\t\t\t\tlen = %d\n", msg_buf->len);
1247     fprintf(stderr, "\t\t\t\t\tseq_num = %d\n", msg_buf->seq_num);
1248 #endif
1249
1250     pqueue_insert(s->d1->sent_messages, item);
1251     return 1;
1252 }
1253
1254 int
1255 dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off,
1256                          int *found)
1257 {
1258     int ret;
1259     /* XDTLS: for now assuming that read/writes are blocking */
1260     pitem *item;
1261     hm_fragment *frag;
1262     unsigned long header_length;
1263     PQ_64BIT seq64;
1264     struct dtls1_retransmit_state saved_state;
1265     unsigned char save_write_sequence[8];
1266
1267     /*-
1268       OPENSSL_assert(s->init_num == 0);
1269       OPENSSL_assert(s->init_off == 0);
1270      */
1271
1272     /* XDTLS:  the requested message ought to be found, otherwise error */
1273     pq_64bit_init(&seq64);
1274     pq_64bit_assign_word(&seq64, seq);
1275
1276     item = pqueue_find(s->d1->sent_messages, seq64);
1277     pq_64bit_free(&seq64);
1278     if (item == NULL) {
1279         fprintf(stderr, "retransmit:  message %d non-existant\n", seq);
1280         *found = 0;
1281         return 0;
1282     }
1283
1284     *found = 1;
1285     frag = (hm_fragment *)item->data;
1286
1287     if (frag->msg_header.is_ccs)
1288         header_length = DTLS1_CCS_HEADER_LENGTH;
1289     else
1290         header_length = DTLS1_HM_HEADER_LENGTH;
1291
1292     memcpy(s->init_buf->data, frag->fragment,
1293            frag->msg_header.msg_len + header_length);
1294     s->init_num = frag->msg_header.msg_len + header_length;
1295
1296     dtls1_set_message_header_int(s, frag->msg_header.type,
1297                                  frag->msg_header.msg_len,
1298                                  frag->msg_header.seq, 0,
1299                                  frag->msg_header.frag_len);
1300
1301     /* save current state */
1302     saved_state.enc_write_ctx = s->enc_write_ctx;
1303     saved_state.write_hash = s->write_hash;
1304     saved_state.compress = s->compress;
1305     saved_state.session = s->session;
1306     saved_state.epoch = s->d1->w_epoch;
1307     saved_state.epoch = s->d1->w_epoch;
1308
1309     s->d1->retransmitting = 1;
1310
1311     /* restore state in which the message was originally sent */
1312     s->enc_write_ctx = frag->msg_header.saved_retransmit_state.enc_write_ctx;
1313     s->write_hash = frag->msg_header.saved_retransmit_state.write_hash;
1314     s->compress = frag->msg_header.saved_retransmit_state.compress;
1315     s->session = frag->msg_header.saved_retransmit_state.session;
1316     s->d1->w_epoch = frag->msg_header.saved_retransmit_state.epoch;
1317
1318     if (frag->msg_header.saved_retransmit_state.epoch ==
1319         saved_state.epoch - 1) {
1320         memcpy(save_write_sequence, s->s3->write_sequence,
1321                sizeof(s->s3->write_sequence));
1322         memcpy(s->s3->write_sequence, s->d1->last_write_sequence,
1323                sizeof(s->s3->write_sequence));
1324     }
1325
1326     ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
1327                          SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
1328
1329     /* restore current state */
1330     s->enc_write_ctx = saved_state.enc_write_ctx;
1331     s->write_hash = saved_state.write_hash;
1332     s->compress = saved_state.compress;
1333     s->session = saved_state.session;
1334     s->d1->w_epoch = saved_state.epoch;
1335
1336     if (frag->msg_header.saved_retransmit_state.epoch ==
1337         saved_state.epoch - 1) {
1338         memcpy(s->d1->last_write_sequence, s->s3->write_sequence,
1339                sizeof(s->s3->write_sequence));
1340         memcpy(s->s3->write_sequence, save_write_sequence,
1341                sizeof(s->s3->write_sequence));
1342     }
1343
1344     s->d1->retransmitting = 0;
1345
1346     (void)BIO_flush(SSL_get_wbio(s));
1347     return ret;
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 }