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