xref: /dragonfly/crypto/libressl/ssl/d1_both.c (revision 44753b81)
1 /* $OpenBSD: d1_both.c,v 1.38 2015/09/11 18:08:21 jsing Exp $ */
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 <stdio.h>
118 #include <string.h>
119 
120 #include "ssl_locl.h"
121 
122 #include <openssl/buffer.h>
123 #include <openssl/evp.h>
124 #include <openssl/objects.h>
125 #include <openssl/x509.h>
126 
127 #include "pqueue.h"
128 #include "bytestring.h"
129 
130 #define RSMBLY_BITMASK_SIZE(msg_len) (((msg_len) + 7) / 8)
131 
132 #define RSMBLY_BITMASK_MARK(bitmask, start, end) { \
133 			if ((end) - (start) <= 8) { \
134 				long ii; \
135 				for (ii = (start); ii < (end); ii++) bitmask[((ii) >> 3)] |= (1 << ((ii) & 7)); \
136 			} else { \
137 				long ii; \
138 				bitmask[((start) >> 3)] |= bitmask_start_values[((start) & 7)]; \
139 				for (ii = (((start) >> 3) + 1); ii < ((((end) - 1)) >> 3); ii++) bitmask[ii] = 0xff; \
140 				bitmask[(((end) - 1) >> 3)] |= bitmask_end_values[((end) & 7)]; \
141 			} }
142 
143 #define RSMBLY_BITMASK_IS_COMPLETE(bitmask, msg_len, is_complete) { \
144 			long ii; \
145 			OPENSSL_assert((msg_len) > 0); \
146 			is_complete = 1; \
147 			if (bitmask[(((msg_len) - 1) >> 3)] != bitmask_end_values[((msg_len) & 7)]) is_complete = 0; \
148 			if (is_complete) for (ii = (((msg_len) - 1) >> 3) - 1; ii >= 0 ; ii--) \
149 				if (bitmask[ii] != 0xff) { is_complete = 0; break; } }
150 
151 static unsigned char bitmask_start_values[] = {
152 	0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80
153 };
154 static unsigned char bitmask_end_values[] = {
155 	0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f
156 };
157 
158 /* XDTLS:  figure out the right values */
159 static 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, unsigned char *p);
165 static void dtls1_set_message_header_int(SSL *s, unsigned char mt,
166     unsigned long len, unsigned short seq_num, unsigned long frag_off,
167     unsigned long frag_len);
168 static long dtls1_get_message_fragment(SSL *s, int st1, int stn, long max,
169     int *ok);
170 
171 static hm_fragment *
172 dtls1_hm_fragment_new(unsigned long frag_len, int reassembly)
173 {
174 	hm_fragment *frag = NULL;
175 	unsigned char *buf = NULL;
176 	unsigned char *bitmask = NULL;
177 
178 	frag = malloc(sizeof(hm_fragment));
179 	if (frag == NULL)
180 		return NULL;
181 
182 	if (frag_len) {
183 		buf = malloc(frag_len);
184 		if (buf == NULL) {
185 			free(frag);
186 			return NULL;
187 		}
188 	}
189 
190 	/* zero length fragment gets zero frag->fragment */
191 	frag->fragment = buf;
192 
193 	/* Initialize reassembly bitmask if necessary */
194 	if (reassembly) {
195 		bitmask = malloc(RSMBLY_BITMASK_SIZE(frag_len));
196 		if (bitmask == NULL) {
197 			free(buf);
198 			free(frag);
199 			return NULL;
200 		}
201 		memset(bitmask, 0, RSMBLY_BITMASK_SIZE(frag_len));
202 	}
203 
204 	frag->reassembly = bitmask;
205 
206 	return frag;
207 }
208 
209 static void
210 dtls1_hm_fragment_free(hm_fragment *frag)
211 {
212 	if (frag == NULL)
213 		return;
214 
215 	if (frag->msg_header.is_ccs) {
216 		EVP_CIPHER_CTX_free(
217 		    frag->msg_header.saved_retransmit_state.enc_write_ctx);
218 		EVP_MD_CTX_destroy(
219 		    frag->msg_header.saved_retransmit_state.write_hash);
220 	}
221 	free(frag->fragment);
222 	free(frag->reassembly);
223 	free(frag);
224 }
225 
226 /* send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or SSL3_RT_CHANGE_CIPHER_SPEC) */
227 int
228 dtls1_do_write(SSL *s, int type)
229 {
230 	int ret;
231 	int curr_mtu;
232 	unsigned int len, frag_off, mac_size, blocksize;
233 
234 	/* AHA!  Figure out the MTU, and stick to the right size */
235 	if (s->d1->mtu < dtls1_min_mtu() &&
236 	    !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
237 		s->d1->mtu = BIO_ctrl(SSL_get_wbio(s),
238 		    BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
239 
240 		/*
241 		 * I've seen the kernel return bogus numbers when it
242 		 * doesn't know the MTU (ie., the initial write), so just
243 		 * make sure we have a reasonable number
244 		 */
245 		if (s->d1->mtu < dtls1_min_mtu()) {
246 			s->d1->mtu = 0;
247 			s->d1->mtu = dtls1_guess_mtu(s->d1->mtu);
248 			BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
249 			    s->d1->mtu, NULL);
250 		}
251 	}
252 
253 	OPENSSL_assert(s->d1->mtu >= dtls1_min_mtu());
254 	/* should have something reasonable now */
255 
256 	if (s->init_off == 0  && type == SSL3_RT_HANDSHAKE)
257 		OPENSSL_assert(s->init_num ==
258 		    (int)s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH);
259 
260 	if (s->write_hash)
261 		mac_size = EVP_MD_CTX_size(s->write_hash);
262 	else
263 		mac_size = 0;
264 
265 	if (s->enc_write_ctx &&
266 	    (EVP_CIPHER_mode( s->enc_write_ctx->cipher) & EVP_CIPH_CBC_MODE))
267 		blocksize = 2 * EVP_CIPHER_block_size(s->enc_write_ctx->cipher);
268 	else
269 		blocksize = 0;
270 
271 	frag_off = 0;
272 	while (s->init_num) {
273 		curr_mtu = s->d1->mtu - BIO_wpending(SSL_get_wbio(s)) -
274 		    DTLS1_RT_HEADER_LENGTH - mac_size - blocksize;
275 
276 		if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
277 			/* grr.. we could get an error if MTU picked was wrong */
278 			ret = BIO_flush(SSL_get_wbio(s));
279 			if (ret <= 0)
280 				return ret;
281 			curr_mtu = s->d1->mtu - DTLS1_RT_HEADER_LENGTH -
282 			    mac_size - blocksize;
283 		}
284 
285 		if (s->init_num > curr_mtu)
286 			len = curr_mtu;
287 		else
288 			len = s->init_num;
289 
290 
291 		/* XDTLS: this function is too long.  split out the CCS part */
292 		if (type == SSL3_RT_HANDSHAKE) {
293 			if (s->init_off != 0) {
294 				OPENSSL_assert(s->init_off > DTLS1_HM_HEADER_LENGTH);
295 				s->init_off -= DTLS1_HM_HEADER_LENGTH;
296 				s->init_num += DTLS1_HM_HEADER_LENGTH;
297 
298 				if (s->init_num > curr_mtu)
299 					len = curr_mtu;
300 				else
301 					len = s->init_num;
302 			}
303 
304 			dtls1_fix_message_header(s, frag_off,
305 			    len - DTLS1_HM_HEADER_LENGTH);
306 
307 			dtls1_write_message_header(s,
308 			    (unsigned char *)&s->init_buf->data[s->init_off]);
309 
310 			OPENSSL_assert(len >= DTLS1_HM_HEADER_LENGTH);
311 		}
312 
313 		ret = dtls1_write_bytes(s, type,
314 		    &s->init_buf->data[s->init_off], len);
315 		if (ret < 0) {
316 			/*
317 			 * Might need to update MTU here, but we don't know
318 			 * which previous packet caused the failure -- so
319 			 * can't really retransmit anything.  continue as
320 			 * if everything is fine and wait for an alert to
321 			 * handle the retransmit
322 			 */
323 			if (BIO_ctrl(SSL_get_wbio(s),
324 			    BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0)
325 				s->d1->mtu = BIO_ctrl(SSL_get_wbio(s),
326 				    BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
327 			else
328 				return (-1);
329 		} else {
330 
331 			/*
332 			 * Bad if this assert fails, only part of the
333 			 * handshake message got sent.  but why would
334 			 * this happen?
335 			 */
336 			OPENSSL_assert(len == (unsigned int)ret);
337 
338 			if (type == SSL3_RT_HANDSHAKE &&
339 			    !s->d1->retransmitting) {
340 				/*
341 				 * Should not be done for 'Hello Request's,
342 				 * but in that case we'll ignore the result
343 				 * anyway
344 				 */
345 				unsigned char *p = (unsigned char *)&s->init_buf->data[s->init_off];
346 				const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
347 				int xlen;
348 
349 				if (frag_off == 0) {
350 					/*
351 					 * Reconstruct message header is if it
352 					 * is being sent in single fragment
353 					 */
354 					*p++ = msg_hdr->type;
355 					l2n3(msg_hdr->msg_len, p);
356 					s2n (msg_hdr->seq, p);
357 					l2n3(0, p);
358 					l2n3(msg_hdr->msg_len, p);
359 					p -= DTLS1_HM_HEADER_LENGTH;
360 					xlen = ret;
361 				} else {
362 					p += DTLS1_HM_HEADER_LENGTH;
363 					xlen = ret - DTLS1_HM_HEADER_LENGTH;
364 				}
365 
366 				tls1_finish_mac(s, p, xlen);
367 			}
368 
369 			if (ret == s->init_num) {
370 				if (s->msg_callback)
371 					s->msg_callback(1, s->version, type,
372 					    s->init_buf->data,
373 					    (size_t)(s->init_off + s->init_num),
374 					    s, s->msg_callback_arg);
375 
376 				s->init_off = 0;
377 				/* done writing this message */
378 				s->init_num = 0;
379 
380 				return (1);
381 			}
382 			s->init_off += ret;
383 			s->init_num -= ret;
384 			frag_off += (ret -= DTLS1_HM_HEADER_LENGTH);
385 		}
386 	}
387 	return (0);
388 }
389 
390 
391 /*
392  * Obtain handshake message of message type 'mt' (any if mt == -1),
393  * maximum acceptable body length 'max'.
394  * Read an entire handshake message.  Handshake messages arrive in
395  * fragments.
396  */
397 long
398 dtls1_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok)
399 {
400 	int i, al;
401 	struct hm_header_st *msg_hdr;
402 	unsigned char *p;
403 	unsigned long msg_len;
404 
405 	/*
406 	 * s3->tmp is used to store messages that are unexpected, caused
407 	 * by the absence of an optional handshake message
408 	 */
409 	if (s->s3->tmp.reuse_message) {
410 		s->s3->tmp.reuse_message = 0;
411 		if ((mt >= 0) && (s->s3->tmp.message_type != mt)) {
412 			al = SSL_AD_UNEXPECTED_MESSAGE;
413 			SSLerr(SSL_F_DTLS1_GET_MESSAGE,
414 			    SSL_R_UNEXPECTED_MESSAGE);
415 			goto f_err;
416 		}
417 		*ok = 1;
418 		s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
419 		s->init_num = (int)s->s3->tmp.message_size;
420 		return s->init_num;
421 	}
422 
423 	msg_hdr = &s->d1->r_msg_hdr;
424 	memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
425 
426 again:
427 	i = dtls1_get_message_fragment(s, st1, stn, max, ok);
428 	if (i == DTLS1_HM_BAD_FRAGMENT ||
429 	    i == DTLS1_HM_FRAGMENT_RETRY)  /* bad fragment received */
430 		goto again;
431 	else if (i <= 0 && !*ok)
432 		return i;
433 
434 	p = (unsigned char *)s->init_buf->data;
435 	msg_len = msg_hdr->msg_len;
436 
437 	/* reconstruct message header */
438 	*(p++) = msg_hdr->type;
439 	l2n3(msg_len, p);
440 	s2n (msg_hdr->seq, p);
441 	l2n3(0, p);
442 	l2n3(msg_len, p);
443 
444 	p -= DTLS1_HM_HEADER_LENGTH;
445 	msg_len += DTLS1_HM_HEADER_LENGTH;
446 
447 	tls1_finish_mac(s, p, msg_len);
448 	if (s->msg_callback)
449 		s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, p, msg_len,
450 		    s, s->msg_callback_arg);
451 
452 	memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
453 
454 	/* Don't change sequence numbers while listening */
455 	if (!s->d1->listen)
456 		s->d1->handshake_read_seq++;
457 
458 	s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
459 	return s->init_num;
460 
461 f_err:
462 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
463 	*ok = 0;
464 	return -1;
465 }
466 
467 
468 static int
469 dtls1_preprocess_fragment(SSL *s, struct hm_header_st *msg_hdr, int max)
470 {
471 	size_t frag_off, frag_len, msg_len;
472 
473 	msg_len = msg_hdr->msg_len;
474 	frag_off = msg_hdr->frag_off;
475 	frag_len = msg_hdr->frag_len;
476 
477 	/* sanity checking */
478 	if ((frag_off + frag_len) > msg_len) {
479 		SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,
480 		    SSL_R_EXCESSIVE_MESSAGE_SIZE);
481 		return SSL_AD_ILLEGAL_PARAMETER;
482 	}
483 
484 	if ((frag_off + frag_len) > (unsigned long)max) {
485 		SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,
486 		    SSL_R_EXCESSIVE_MESSAGE_SIZE);
487 		return SSL_AD_ILLEGAL_PARAMETER;
488 	}
489 
490 	if ( s->d1->r_msg_hdr.frag_off == 0) /* first fragment */
491 	{
492 		/*
493 		 * msg_len is limited to 2^24, but is effectively checked
494 		 * against max above
495 		 */
496 		if (!BUF_MEM_grow_clean(s->init_buf,
497 		    msg_len + DTLS1_HM_HEADER_LENGTH)) {
498 			SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, ERR_R_BUF_LIB);
499 			return SSL_AD_INTERNAL_ERROR;
500 		}
501 
502 		s->s3->tmp.message_size = msg_len;
503 		s->d1->r_msg_hdr.msg_len = msg_len;
504 		s->s3->tmp.message_type = msg_hdr->type;
505 		s->d1->r_msg_hdr.type = msg_hdr->type;
506 		s->d1->r_msg_hdr.seq = msg_hdr->seq;
507 	} else if (msg_len != s->d1->r_msg_hdr.msg_len) {
508 		/*
509 		 * They must be playing with us! BTW, failure to enforce
510 		 * upper limit would open possibility for buffer overrun.
511 		 */
512 		SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,
513 		    SSL_R_EXCESSIVE_MESSAGE_SIZE);
514 		return SSL_AD_ILLEGAL_PARAMETER;
515 	}
516 
517 	return 0; /* no error */
518 }
519 
520 static int
521 dtls1_retrieve_buffered_fragment(SSL *s, long max, int *ok)
522 {
523 	/*
524 	 * (0) check whether the desired fragment is available
525 	 * if so:
526 	 * (1) copy over the fragment to s->init_buf->data[]
527 	 * (2) update s->init_num
528 	 */
529 	pitem *item;
530 	hm_fragment *frag;
531 	int al;
532 
533 	*ok = 0;
534 	item = pqueue_peek(s->d1->buffered_messages);
535 	if (item == NULL)
536 		return 0;
537 
538 	frag = (hm_fragment *)item->data;
539 
540 	/* Don't return if reassembly still in progress */
541 	if (frag->reassembly != NULL)
542 		return 0;
543 
544 	if (s->d1->handshake_read_seq == frag->msg_header.seq) {
545 		unsigned long frag_len = frag->msg_header.frag_len;
546 		pqueue_pop(s->d1->buffered_messages);
547 
548 		al = dtls1_preprocess_fragment(s, &frag->msg_header, max);
549 
550 		if (al == 0) /* no alert */
551 		{
552 			unsigned char *p = (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
553 			memcpy(&p[frag->msg_header.frag_off],
554 			    frag->fragment, frag->msg_header.frag_len);
555 		}
556 
557 		dtls1_hm_fragment_free(frag);
558 		pitem_free(item);
559 
560 		if (al == 0) {
561 			*ok = 1;
562 			return frag_len;
563 		}
564 
565 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
566 		s->init_num = 0;
567 		*ok = 0;
568 		return -1;
569 	} else
570 		return 0;
571 }
572 
573 /*
574  * dtls1_max_handshake_message_len returns the maximum number of bytes
575  * permitted in a DTLS handshake message for |s|. The minimum is 16KB,
576  * but may be greater if the maximum certificate list size requires it.
577  */
578 static unsigned long
579 dtls1_max_handshake_message_len(const SSL *s)
580 {
581 	unsigned long max_len;
582 
583 	max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
584 	if (max_len < (unsigned long)s->max_cert_list)
585 		return s->max_cert_list;
586 	return max_len;
587 }
588 
589 static int
590 dtls1_reassemble_fragment(SSL *s, struct hm_header_st* msg_hdr, int *ok)
591 {
592 	hm_fragment *frag = NULL;
593 	pitem *item = NULL;
594 	int i = -1, is_complete;
595 	unsigned char seq64be[8];
596 	unsigned long frag_len = msg_hdr->frag_len;
597 
598 	if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len ||
599 	    msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
600 		goto err;
601 
602 	if (frag_len == 0) {
603 		i = DTLS1_HM_FRAGMENT_RETRY;
604 		goto err;
605 	}
606 
607 	/* Try to find item in queue */
608 	memset(seq64be, 0, sizeof(seq64be));
609 	seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
610 	seq64be[7] = (unsigned char)msg_hdr->seq;
611 	item = pqueue_find(s->d1->buffered_messages, seq64be);
612 
613 	if (item == NULL) {
614 		frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
615 		if (frag == NULL)
616 			goto err;
617 		memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
618 		frag->msg_header.frag_len = frag->msg_header.msg_len;
619 		frag->msg_header.frag_off = 0;
620 	} else {
621 		frag = (hm_fragment*)item->data;
622 		if (frag->msg_header.msg_len != msg_hdr->msg_len) {
623 			item = NULL;
624 			frag = NULL;
625 			goto err;
626 		}
627 	}
628 
629 	/*
630 	 * If message is already reassembled, this must be a
631 	 * retransmit and can be dropped.
632 	 */
633 	if (frag->reassembly == NULL) {
634 		unsigned char devnull [256];
635 
636 		while (frag_len) {
637 			i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
638 			    devnull, frag_len > sizeof(devnull) ?
639 			    sizeof(devnull) : frag_len, 0);
640 			if (i <= 0)
641 				goto err;
642 			frag_len -= i;
643 		}
644 		i = DTLS1_HM_FRAGMENT_RETRY;
645 		goto err;
646 	}
647 
648 	/* read the body of the fragment (header has already been read */
649 	i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
650 	    frag->fragment + msg_hdr->frag_off, frag_len, 0);
651 	if (i <= 0 || (unsigned long)i != frag_len)
652 		goto err;
653 
654 	RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
655 	    (long)(msg_hdr->frag_off + frag_len));
656 
657 	RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
658 	    is_complete);
659 
660 	if (is_complete) {
661 		free(frag->reassembly);
662 		frag->reassembly = NULL;
663 	}
664 
665 	if (item == NULL) {
666 		memset(seq64be, 0, sizeof(seq64be));
667 		seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
668 		seq64be[7] = (unsigned char)(msg_hdr->seq);
669 
670 		item = pitem_new(seq64be, frag);
671 		if (item == NULL) {
672 			i = -1;
673 			goto err;
674 		}
675 
676 		pqueue_insert(s->d1->buffered_messages, item);
677 	}
678 
679 	return DTLS1_HM_FRAGMENT_RETRY;
680 
681 err:
682 	if (item == NULL && frag != NULL)
683 		dtls1_hm_fragment_free(frag);
684 	*ok = 0;
685 	return i;
686 }
687 
688 
689 static int
690 dtls1_process_out_of_seq_message(SSL *s, struct hm_header_st* msg_hdr, int *ok)
691 {
692 	int i = -1;
693 	hm_fragment *frag = NULL;
694 	pitem *item = NULL;
695 	unsigned char seq64be[8];
696 	unsigned long frag_len = msg_hdr->frag_len;
697 
698 	if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
699 		goto err;
700 
701 	/* Try to find item in queue, to prevent duplicate entries */
702 	memset(seq64be, 0, sizeof(seq64be));
703 	seq64be[6] = (unsigned char) (msg_hdr->seq >> 8);
704 	seq64be[7] = (unsigned char) msg_hdr->seq;
705 	item = pqueue_find(s->d1->buffered_messages, seq64be);
706 
707 	/*
708 	 * If we already have an entry and this one is a fragment,
709 	 * don't discard it and rather try to reassemble it.
710 	 */
711 	if (item != NULL && frag_len < msg_hdr->msg_len)
712 		item = NULL;
713 
714 	/*
715 	 * Discard the message if sequence number was already there, is
716 	 * too far in the future, already in the queue or if we received
717 	 * a FINISHED before the SERVER_HELLO, which then must be a stale
718 	 * retransmit.
719 	 */
720 	if (msg_hdr->seq <= s->d1->handshake_read_seq ||
721 	    msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL ||
722 	    (s->d1->handshake_read_seq == 0 &&
723 	    msg_hdr->type == SSL3_MT_FINISHED)) {
724 		unsigned char devnull [256];
725 
726 		while (frag_len) {
727 			i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
728 			    devnull, frag_len > sizeof(devnull) ?
729 			    sizeof(devnull) : frag_len, 0);
730 			if (i <= 0)
731 				goto err;
732 			frag_len -= i;
733 		}
734 	} else {
735 		if (frag_len < msg_hdr->msg_len)
736 			return dtls1_reassemble_fragment(s, msg_hdr, ok);
737 
738 		if (frag_len > dtls1_max_handshake_message_len(s))
739 			goto err;
740 
741 		frag = dtls1_hm_fragment_new(frag_len, 0);
742 		if (frag == NULL)
743 			goto err;
744 
745 		memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
746 
747 		if (frag_len) {
748 			/* read the body of the fragment (header has already been read */
749 			i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
750 			    frag->fragment, frag_len, 0);
751 			if (i <= 0 || (unsigned long)i != frag_len)
752 				goto err;
753 		}
754 
755 		memset(seq64be, 0, sizeof(seq64be));
756 		seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
757 		seq64be[7] = (unsigned char)(msg_hdr->seq);
758 
759 		item = pitem_new(seq64be, frag);
760 		if (item == NULL)
761 			goto err;
762 
763 		pqueue_insert(s->d1->buffered_messages, item);
764 	}
765 
766 	return DTLS1_HM_FRAGMENT_RETRY;
767 
768 err:
769 	if (item == NULL && frag != NULL)
770 		dtls1_hm_fragment_free(frag);
771 	*ok = 0;
772 	return i;
773 }
774 
775 
776 static long
777 dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok)
778 {
779 	unsigned char wire[DTLS1_HM_HEADER_LENGTH];
780 	unsigned long len, frag_off, frag_len;
781 	int i, al;
782 	struct hm_header_st msg_hdr;
783 
784 again:
785 	/* see if we have the required fragment already */
786 	if ((frag_len = dtls1_retrieve_buffered_fragment(s, max, ok)) || *ok) {
787 		if (*ok)
788 			s->init_num = frag_len;
789 		return frag_len;
790 	}
791 
792 	/* read handshake message header */
793 	i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, wire,
794 	    DTLS1_HM_HEADER_LENGTH, 0);
795 	if (i <= 0) 	/* nbio, or an error */
796 	{
797 		s->rwstate = SSL_READING;
798 		*ok = 0;
799 		return i;
800 	}
801 	/* Handshake fails if message header is incomplete */
802 	if (i != DTLS1_HM_HEADER_LENGTH ||
803 	    /* parse the message fragment header */
804 	    dtls1_get_message_header(wire, &msg_hdr) == 0) {
805 		al = SSL_AD_UNEXPECTED_MESSAGE;
806 		SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,
807 		    SSL_R_UNEXPECTED_MESSAGE);
808 		goto f_err;
809 	}
810 
811 	/*
812 	 * if this is a future (or stale) message it gets buffered
813 	 * (or dropped)--no further processing at this time
814 	 * While listening, we accept seq 1 (ClientHello with cookie)
815 	 * although we're still expecting seq 0 (ClientHello)
816 	 */
817 	if (msg_hdr.seq != s->d1->handshake_read_seq &&
818 	    !(s->d1->listen && msg_hdr.seq == 1))
819 		return dtls1_process_out_of_seq_message(s, &msg_hdr, ok);
820 
821 	len = msg_hdr.msg_len;
822 	frag_off = msg_hdr.frag_off;
823 	frag_len = msg_hdr.frag_len;
824 
825 	if (frag_len && frag_len < len)
826 		return dtls1_reassemble_fragment(s, &msg_hdr, ok);
827 
828 	if (!s->server && s->d1->r_msg_hdr.frag_off == 0 &&
829 	    wire[0] == SSL3_MT_HELLO_REQUEST) {
830 		/*
831 		 * The server may always send 'Hello Request' messages --
832 		 * we are doing a handshake anyway now, so ignore them
833 		 * if their format is correct. Does not count for
834 		 * 'Finished' MAC.
835 		 */
836 		if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) {
837 			if (s->msg_callback)
838 				s->msg_callback(0, s->version,
839 				    SSL3_RT_HANDSHAKE, wire,
840 				    DTLS1_HM_HEADER_LENGTH, s,
841 				    s->msg_callback_arg);
842 
843 			s->init_num = 0;
844 			goto again;
845 		}
846 		else /* Incorrectly formated Hello request */
847 		{
848 			al = SSL_AD_UNEXPECTED_MESSAGE;
849 			SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,
850 			    SSL_R_UNEXPECTED_MESSAGE);
851 			goto f_err;
852 		}
853 	}
854 
855 	if ((al = dtls1_preprocess_fragment(s, &msg_hdr, max)))
856 		goto f_err;
857 
858 	/* XDTLS:  ressurect this when restart is in place */
859 	s->state = stn;
860 
861 	if (frag_len > 0) {
862 		unsigned char *p = (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
863 
864 		i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
865 		    &p[frag_off], frag_len, 0);
866 		/* XDTLS:  fix this--message fragments cannot span multiple packets */
867 		if (i <= 0) {
868 			s->rwstate = SSL_READING;
869 			*ok = 0;
870 			return i;
871 		}
872 	} else
873 		i = 0;
874 
875 	/*
876 	 * XDTLS:  an incorrectly formatted fragment should cause the
877 	 * handshake to fail
878 	 */
879 	if (i != (int)frag_len) {
880 		al = SSL3_AD_ILLEGAL_PARAMETER;
881 		SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,
882 		    SSL3_AD_ILLEGAL_PARAMETER);
883 		goto f_err;
884 	}
885 
886 	*ok = 1;
887 
888 	/*
889 	 * Note that s->init_num is *not* used as current offset in
890 	 * s->init_buf->data, but as a counter summing up fragments'
891 	 * lengths: as soon as they sum up to handshake packet
892 	 * length, we assume we have got all the fragments.
893 	 */
894 	s->init_num = frag_len;
895 	return frag_len;
896 
897 f_err:
898 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
899 	s->init_num = 0;
900 
901 	*ok = 0;
902 	return (-1);
903 }
904 
905 /*
906  * for these 2 messages, we need to
907  * ssl->enc_read_ctx			re-init
908  * ssl->s3->read_sequence		zero
909  * ssl->s3->read_mac_secret		re-init
910  * ssl->session->read_sym_enc		assign
911  * ssl->session->read_hash		assign
912  */
913 int
914 dtls1_send_change_cipher_spec(SSL *s, int a, int b)
915 {
916 	unsigned char *p;
917 
918 	if (s->state == a) {
919 		p = (unsigned char *)s->init_buf->data;
920 		*p++=SSL3_MT_CCS;
921 		s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
922 		s->init_num = DTLS1_CCS_HEADER_LENGTH;
923 
924 		s->init_off = 0;
925 
926 		dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
927 		    s->d1->handshake_write_seq, 0, 0);
928 
929 		/* buffer the message to handle re-xmits */
930 		dtls1_buffer_message(s, 1);
931 
932 		s->state = b;
933 	}
934 
935 	/* SSL3_ST_CW_CHANGE_B */
936 	return (dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC));
937 }
938 
939 static int
940 dtls1_add_cert_to_buf(BUF_MEM *buf, unsigned long *l, X509 *x)
941 {
942 	int n;
943 	unsigned char *p;
944 
945 	n = i2d_X509(x, NULL);
946 	if (!BUF_MEM_grow_clean(buf, n + (*l) + 3)) {
947 		SSLerr(SSL_F_DTLS1_ADD_CERT_TO_BUF, ERR_R_BUF_LIB);
948 		return 0;
949 	}
950 	p = (unsigned char *)&(buf->data[*l]);
951 	l2n3(n, p);
952 	i2d_X509(x, &p);
953 	*l += n + 3;
954 
955 	return 1;
956 }
957 
958 unsigned long
959 dtls1_output_cert_chain(SSL *s, X509 *x)
960 {
961 	unsigned char *p;
962 	int i;
963 	unsigned long l = 3 + DTLS1_HM_HEADER_LENGTH;
964 	BUF_MEM *buf;
965 
966 	/* TLSv1 sends a chain with nothing in it, instead of an alert */
967 	buf = s->init_buf;
968 	if (!BUF_MEM_grow_clean(buf, 10)) {
969 		SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN, ERR_R_BUF_LIB);
970 		return (0);
971 	}
972 	if (x != NULL) {
973 		X509_STORE_CTX xs_ctx;
974 
975 		if (!X509_STORE_CTX_init(&xs_ctx, s->ctx->cert_store,
976 		    x, NULL)) {
977 			SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN, ERR_R_X509_LIB);
978 			return (0);
979 		}
980 
981 		X509_verify_cert(&xs_ctx);
982 		/* Don't leave errors in the queue */
983 		ERR_clear_error();
984 		for (i = 0; i < sk_X509_num(xs_ctx.chain); i++) {
985 			x = sk_X509_value(xs_ctx.chain, i);
986 
987 			if (!dtls1_add_cert_to_buf(buf, &l, x)) {
988 				X509_STORE_CTX_cleanup(&xs_ctx);
989 				return 0;
990 			}
991 		}
992 		X509_STORE_CTX_cleanup(&xs_ctx);
993 	}
994 	/* Thawte special :-) */
995 	for (i = 0; i < sk_X509_num(s->ctx->extra_certs); i++) {
996 		x = sk_X509_value(s->ctx->extra_certs, i);
997 		if (!dtls1_add_cert_to_buf(buf, &l, x))
998 			return 0;
999 	}
1000 
1001 	l -= (3 + DTLS1_HM_HEADER_LENGTH);
1002 
1003 	p = (unsigned char *)&(buf->data[DTLS1_HM_HEADER_LENGTH]);
1004 	l2n3(l, p);
1005 	l += 3;
1006 	p = (unsigned char *)&(buf->data[0]);
1007 	p = dtls1_set_message_header(s, p, SSL3_MT_CERTIFICATE, l, 0, l);
1008 
1009 	l += DTLS1_HM_HEADER_LENGTH;
1010 	return (l);
1011 }
1012 
1013 int
1014 dtls1_read_failed(SSL *s, int code)
1015 {
1016 	if (code > 0) {
1017 #ifdef DEBUG
1018 		fprintf(stderr, "invalid state reached %s:%d",
1019 		    __FILE__, __LINE__);
1020 #endif
1021 		return 1;
1022 	}
1023 
1024 	if (!dtls1_is_timer_expired(s)) {
1025 		/*
1026 		 * not a timeout, none of our business, let higher layers
1027 		 * handle this.  in fact it's probably an error
1028 		 */
1029 		return code;
1030 	}
1031 
1032 	if (!SSL_in_init(s))  /* done, no need to send a retransmit */
1033 	{
1034 		BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
1035 		return code;
1036 	}
1037 
1038 	return dtls1_handle_timeout(s);
1039 }
1040 
1041 int
1042 dtls1_get_queue_priority(unsigned short seq, int is_ccs)
1043 {
1044 	/*
1045 	 * The index of the retransmission queue actually is the message
1046 	 * sequence number, since the queue only contains messages of a
1047 	 * single handshake. However, the ChangeCipherSpec has no message
1048 	 * sequence number and so using only the sequence will result in
1049 	 * the CCS and Finished having the same index. To prevent this, the
1050 	 * sequence number is multiplied by 2. In case of a CCS 1 is
1051 	 * subtracted.  This does not only differ CSS and Finished, it also
1052 	 * maintains the order of the index (important for priority queues)
1053 	 * and fits in the unsigned short variable.
1054 	 */
1055 	return seq * 2 - is_ccs;
1056 }
1057 
1058 int
1059 dtls1_retransmit_buffered_messages(SSL *s)
1060 {
1061 	pqueue sent = s->d1->sent_messages;
1062 	piterator iter;
1063 	pitem *item;
1064 	hm_fragment *frag;
1065 	int found = 0;
1066 
1067 	iter = pqueue_iterator(sent);
1068 
1069 	for (item = pqueue_next(&iter); item != NULL;
1070 	    item = pqueue_next(&iter)) {
1071 		frag = (hm_fragment *)item->data;
1072 		if (dtls1_retransmit_message(s,
1073 		    (unsigned short)dtls1_get_queue_priority(
1074 		    frag->msg_header.seq, frag->msg_header.is_ccs), 0,
1075 		    &found) <= 0 && found) {
1076 #ifdef DEBUG
1077 			fprintf(stderr, "dtls1_retransmit_message() failed\n");
1078 #endif
1079 			return -1;
1080 		}
1081 	}
1082 
1083 	return 1;
1084 }
1085 
1086 int
1087 dtls1_buffer_message(SSL *s, int is_ccs)
1088 {
1089 	pitem *item;
1090 	hm_fragment *frag;
1091 	unsigned char seq64be[8];
1092 
1093 	/* Buffer the messsage in order to handle DTLS retransmissions. */
1094 
1095 	/*
1096 	 * This function is called immediately after a message has
1097 	 * been serialized
1098 	 */
1099 	OPENSSL_assert(s->init_off == 0);
1100 
1101 	frag = dtls1_hm_fragment_new(s->init_num, 0);
1102 	if (frag == NULL)
1103 		return 0;
1104 
1105 	memcpy(frag->fragment, s->init_buf->data, s->init_num);
1106 
1107 	if (is_ccs) {
1108 		OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
1109 		    ((s->version == DTLS1_VERSION) ?
1110 		    DTLS1_CCS_HEADER_LENGTH : 3) == (unsigned int)s->init_num);
1111 	} else {
1112 		OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
1113 		    DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num);
1114 	}
1115 
1116 	frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
1117 	frag->msg_header.seq = s->d1->w_msg_hdr.seq;
1118 	frag->msg_header.type = s->d1->w_msg_hdr.type;
1119 	frag->msg_header.frag_off = 0;
1120 	frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
1121 	frag->msg_header.is_ccs = is_ccs;
1122 
1123 	/* save current state*/
1124 	frag->msg_header.saved_retransmit_state.enc_write_ctx = s->enc_write_ctx;
1125 	frag->msg_header.saved_retransmit_state.write_hash = s->write_hash;
1126 	frag->msg_header.saved_retransmit_state.session = s->session;
1127 	frag->msg_header.saved_retransmit_state.epoch = s->d1->w_epoch;
1128 
1129 	memset(seq64be, 0, sizeof(seq64be));
1130 	seq64be[6] = (unsigned char)(dtls1_get_queue_priority(
1131 	    frag->msg_header.seq, frag->msg_header.is_ccs) >> 8);
1132 	seq64be[7] = (unsigned char)(dtls1_get_queue_priority(
1133 	    frag->msg_header.seq, frag->msg_header.is_ccs));
1134 
1135 	item = pitem_new(seq64be, frag);
1136 	if (item == NULL) {
1137 		dtls1_hm_fragment_free(frag);
1138 		return 0;
1139 	}
1140 
1141 	pqueue_insert(s->d1->sent_messages, item);
1142 	return 1;
1143 }
1144 
1145 int
1146 dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off,
1147     int *found)
1148 {
1149 	int ret;
1150 	/* XDTLS: for now assuming that read/writes are blocking */
1151 	pitem *item;
1152 	hm_fragment *frag;
1153 	unsigned long header_length;
1154 	unsigned char seq64be[8];
1155 	struct dtls1_retransmit_state saved_state;
1156 	unsigned char save_write_sequence[8];
1157 
1158 	/*
1159 	  OPENSSL_assert(s->init_num == 0);
1160 	  OPENSSL_assert(s->init_off == 0);
1161 	 */
1162 
1163 	/* XDTLS:  the requested message ought to be found, otherwise error */
1164 	memset(seq64be, 0, sizeof(seq64be));
1165 	seq64be[6] = (unsigned char)(seq >> 8);
1166 	seq64be[7] = (unsigned char)seq;
1167 
1168 	item = pqueue_find(s->d1->sent_messages, seq64be);
1169 	if (item == NULL) {
1170 #ifdef DEBUG
1171 		fprintf(stderr, "retransmit:  message %d non-existant\n", seq);
1172 #endif
1173 		*found = 0;
1174 		return 0;
1175 	}
1176 
1177 	*found = 1;
1178 	frag = (hm_fragment *)item->data;
1179 
1180 	if (frag->msg_header.is_ccs)
1181 		header_length = DTLS1_CCS_HEADER_LENGTH;
1182 	else
1183 		header_length = DTLS1_HM_HEADER_LENGTH;
1184 
1185 	memcpy(s->init_buf->data, frag->fragment,
1186 	    frag->msg_header.msg_len + header_length);
1187 	s->init_num = frag->msg_header.msg_len + header_length;
1188 
1189 	dtls1_set_message_header_int(s, frag->msg_header.type,
1190 	    frag->msg_header.msg_len, frag->msg_header.seq, 0,
1191 	    frag->msg_header.frag_len);
1192 
1193 	/* save current state */
1194 	saved_state.enc_write_ctx = s->enc_write_ctx;
1195 	saved_state.write_hash = s->write_hash;
1196 	saved_state.session = s->session;
1197 	saved_state.epoch = s->d1->w_epoch;
1198 
1199 	s->d1->retransmitting = 1;
1200 
1201 	/* restore state in which the message was originally sent */
1202 	s->enc_write_ctx = frag->msg_header.saved_retransmit_state.enc_write_ctx;
1203 	s->write_hash = frag->msg_header.saved_retransmit_state.write_hash;
1204 	s->session = frag->msg_header.saved_retransmit_state.session;
1205 	s->d1->w_epoch = frag->msg_header.saved_retransmit_state.epoch;
1206 
1207 	if (frag->msg_header.saved_retransmit_state.epoch ==
1208 	    saved_state.epoch - 1) {
1209 		memcpy(save_write_sequence, s->s3->write_sequence,
1210 		    sizeof(s->s3->write_sequence));
1211 		memcpy(s->s3->write_sequence, s->d1->last_write_sequence,
1212 		    sizeof(s->s3->write_sequence));
1213 	}
1214 
1215 	ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
1216 	    SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
1217 
1218 	/* restore current state */
1219 	s->enc_write_ctx = saved_state.enc_write_ctx;
1220 	s->write_hash = saved_state.write_hash;
1221 	s->session = saved_state.session;
1222 	s->d1->w_epoch = saved_state.epoch;
1223 
1224 	if (frag->msg_header.saved_retransmit_state.epoch ==
1225 	    saved_state.epoch - 1) {
1226 		memcpy(s->d1->last_write_sequence, s->s3->write_sequence,
1227 		    sizeof(s->s3->write_sequence));
1228 		memcpy(s->s3->write_sequence, save_write_sequence,
1229 		    sizeof(s->s3->write_sequence));
1230 	}
1231 
1232 	s->d1->retransmitting = 0;
1233 
1234 	(void)BIO_flush(SSL_get_wbio(s));
1235 	return ret;
1236 }
1237 
1238 /* call this function when the buffered messages are no longer needed */
1239 void
1240 dtls1_clear_record_buffer(SSL *s)
1241 {
1242 	pitem *item;
1243 
1244 	for(item = pqueue_pop(s->d1->sent_messages); item != NULL;
1245 	    item = pqueue_pop(s->d1->sent_messages)) {
1246 		dtls1_hm_fragment_free((hm_fragment *)item->data);
1247 		pitem_free(item);
1248 	}
1249 }
1250 
1251 unsigned char *
1252 dtls1_set_message_header(SSL *s, unsigned char *p, unsigned char mt,
1253     unsigned long len, unsigned long frag_off, unsigned long frag_len)
1254 {
1255 	/* Don't change sequence numbers while listening */
1256 	if (frag_off == 0 && !s->d1->listen) {
1257 		s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1258 		s->d1->next_handshake_write_seq++;
1259 	}
1260 
1261 	dtls1_set_message_header_int(s, mt, len, s->d1->handshake_write_seq,
1262 	    frag_off, frag_len);
1263 
1264 	return p += DTLS1_HM_HEADER_LENGTH;
1265 }
1266 
1267 /* don't actually do the writing, wait till the MTU has been retrieved */
1268 static void
1269 dtls1_set_message_header_int(SSL *s, unsigned char mt, unsigned long len,
1270     unsigned short seq_num, unsigned long frag_off, unsigned long frag_len)
1271 {
1272 	struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1273 
1274 	msg_hdr->type = mt;
1275 	msg_hdr->msg_len = len;
1276 	msg_hdr->seq = seq_num;
1277 	msg_hdr->frag_off = frag_off;
1278 	msg_hdr->frag_len = frag_len;
1279 }
1280 
1281 static void
1282 dtls1_fix_message_header(SSL *s, unsigned long frag_off, unsigned long frag_len)
1283 {
1284 	struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1285 
1286 	msg_hdr->frag_off = frag_off;
1287 	msg_hdr->frag_len = frag_len;
1288 }
1289 
1290 static unsigned char *
1291 dtls1_write_message_header(SSL *s, unsigned char *p)
1292 {
1293 	struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1294 
1295 	*p++ = msg_hdr->type;
1296 	l2n3(msg_hdr->msg_len, p);
1297 
1298 	s2n(msg_hdr->seq, p);
1299 	l2n3(msg_hdr->frag_off, p);
1300 	l2n3(msg_hdr->frag_len, p);
1301 
1302 	return p;
1303 }
1304 
1305 unsigned int
1306 dtls1_min_mtu(void)
1307 {
1308 	return (g_probable_mtu[(sizeof(g_probable_mtu) /
1309 	    sizeof(g_probable_mtu[0])) - 1]);
1310 }
1311 
1312 static unsigned int
1313 dtls1_guess_mtu(unsigned int curr_mtu)
1314 {
1315 	unsigned int i;
1316 
1317 	if (curr_mtu == 0)
1318 		return g_probable_mtu[0];
1319 
1320 	for (i = 0; i < sizeof(g_probable_mtu) / sizeof(g_probable_mtu[0]); i++)
1321 		if (curr_mtu > g_probable_mtu[i])
1322 			return g_probable_mtu[i];
1323 
1324 	return curr_mtu;
1325 }
1326 
1327 int
1328 dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr)
1329 {
1330 	CBS header;
1331 	uint32_t msg_len, frag_off, frag_len;
1332 	uint16_t seq;
1333 	uint8_t type;
1334 
1335 	CBS_init(&header, data, sizeof(*msg_hdr));
1336 
1337 	memset(msg_hdr, 0, sizeof(*msg_hdr));
1338 
1339 	if (!CBS_get_u8(&header, &type))
1340 		return 0;
1341 	if (!CBS_get_u24(&header, &msg_len))
1342 		return 0;
1343 	if (!CBS_get_u16(&header, &seq))
1344 		return 0;
1345 	if (!CBS_get_u24(&header, &frag_off))
1346 		return 0;
1347 	if (!CBS_get_u24(&header, &frag_len))
1348 		return 0;
1349 
1350 	msg_hdr->type = type;
1351 	msg_hdr->msg_len = msg_len;
1352 	msg_hdr->seq = seq;
1353 	msg_hdr->frag_off = frag_off;
1354 	msg_hdr->frag_len = frag_len;
1355 
1356 	return 1;
1357 }
1358 
1359 void
1360 dtls1_get_ccs_header(unsigned char *data, struct ccs_header_st *ccs_hdr)
1361 {
1362 	memset(ccs_hdr, 0x00, sizeof(struct ccs_header_st));
1363 
1364 	ccs_hdr->type = *(data++);
1365 }
1366 
1367 int
1368 dtls1_shutdown(SSL *s)
1369 {
1370 	int ret;
1371 
1372 	ret = ssl3_shutdown(s);
1373 	return ret;
1374 }
1375