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