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