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