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