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