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