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