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