os/ossrv/ssl/libssl/src/d1_both.c
changeset 0 bde4ae8d615e
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/os/ossrv/ssl/libssl/src/d1_both.c	Fri Jun 15 03:10:57 2012 +0200
     1.3 @@ -0,0 +1,1202 @@
     1.4 +/* ssl/d1_both.c */
     1.5 +/* 
     1.6 + * DTLS implementation written by Nagendra Modadugu
     1.7 + * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.  
     1.8 + */
     1.9 +/* ====================================================================
    1.10 + * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
    1.11 + *
    1.12 + * Redistribution and use in source and binary forms, with or without
    1.13 + * modification, are permitted provided that the following conditions
    1.14 + * are met:
    1.15 + *
    1.16 + * 1. Redistributions of source code must retain the above copyright
    1.17 + *    notice, this list of conditions and the following disclaimer. 
    1.18 + *
    1.19 + * 2. Redistributions in binary form must reproduce the above copyright
    1.20 + *    notice, this list of conditions and the following disclaimer in
    1.21 + *    the documentation and/or other materials provided with the
    1.22 + *    distribution.
    1.23 + *
    1.24 + * 3. All advertising materials mentioning features or use of this
    1.25 + *    software must display the following acknowledgment:
    1.26 + *    "This product includes software developed by the OpenSSL Project
    1.27 + *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
    1.28 + *
    1.29 + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
    1.30 + *    endorse or promote products derived from this software without
    1.31 + *    prior written permission. For written permission, please contact
    1.32 + *    openssl-core@openssl.org.
    1.33 + *
    1.34 + * 5. Products derived from this software may not be called "OpenSSL"
    1.35 + *    nor may "OpenSSL" appear in their names without prior written
    1.36 + *    permission of the OpenSSL Project.
    1.37 + *
    1.38 + * 6. Redistributions of any form whatsoever must retain the following
    1.39 + *    acknowledgment:
    1.40 + *    "This product includes software developed by the OpenSSL Project
    1.41 + *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
    1.42 + *
    1.43 + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
    1.44 + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    1.45 + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    1.46 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
    1.47 + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    1.48 + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
    1.49 + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    1.50 + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    1.51 + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
    1.52 + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    1.53 + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
    1.54 + * OF THE POSSIBILITY OF SUCH DAMAGE.
    1.55 + * ====================================================================
    1.56 + *
    1.57 + * This product includes cryptographic software written by Eric Young
    1.58 + * (eay@cryptsoft.com).  This product includes software written by Tim
    1.59 + * Hudson (tjh@cryptsoft.com).
    1.60 + *
    1.61 + */
    1.62 +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
    1.63 + * All rights reserved.
    1.64 + *
    1.65 + * This package is an SSL implementation written
    1.66 + * by Eric Young (eay@cryptsoft.com).
    1.67 + * The implementation was written so as to conform with Netscapes SSL.
    1.68 + * 
    1.69 + * This library is free for commercial and non-commercial use as long as
    1.70 + * the following conditions are aheared to.  The following conditions
    1.71 + * apply to all code found in this distribution, be it the RC4, RSA,
    1.72 + * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
    1.73 + * included with this distribution is covered by the same copyright terms
    1.74 + * except that the holder is Tim Hudson (tjh@cryptsoft.com).
    1.75 + * 
    1.76 + * Copyright remains Eric Young's, and as such any Copyright notices in
    1.77 + * the code are not to be removed.
    1.78 + * If this package is used in a product, Eric Young should be given attribution
    1.79 + * as the author of the parts of the library used.
    1.80 + * This can be in the form of a textual message at program startup or
    1.81 + * in documentation (online or textual) provided with the package.
    1.82 + * 
    1.83 + * Redistribution and use in source and binary forms, with or without
    1.84 + * modification, are permitted provided that the following conditions
    1.85 + * are met:
    1.86 + * 1. Redistributions of source code must retain the copyright
    1.87 + *    notice, this list of conditions and the following disclaimer.
    1.88 + * 2. Redistributions in binary form must reproduce the above copyright
    1.89 + *    notice, this list of conditions and the following disclaimer in the
    1.90 + *    documentation and/or other materials provided with the distribution.
    1.91 + * 3. All advertising materials mentioning features or use of this software
    1.92 + *    must display the following acknowledgement:
    1.93 + *    "This product includes cryptographic software written by
    1.94 + *     Eric Young (eay@cryptsoft.com)"
    1.95 + *    The word 'cryptographic' can be left out if the rouines from the library
    1.96 + *    being used are not cryptographic related :-).
    1.97 + * 4. If you include any Windows specific code (or a derivative thereof) from 
    1.98 + *    the apps directory (application code) you must include an acknowledgement:
    1.99 + *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
   1.100 + * 
   1.101 + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
   1.102 + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   1.103 + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   1.104 + * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   1.105 + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   1.106 + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   1.107 + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   1.108 + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   1.109 + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   1.110 + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   1.111 + * SUCH DAMAGE.
   1.112 + * 
   1.113 + * The licence and distribution terms for any publically available version or
   1.114 + * derivative of this code cannot be changed.  i.e. this code cannot simply be
   1.115 + * copied and put under another distribution licence
   1.116 + * [including the GNU Public Licence.]
   1.117 + */
   1.118 +/*
   1.119 + © Portions copyright (c) 2006 Nokia Corporation.  All rights reserved.
   1.120 + */
   1.121 + 
   1.122 +#include <limits.h>
   1.123 +#include <string.h>
   1.124 +#include <stdio.h>
   1.125 +#include "ssl_locl.h"
   1.126 +#include <openssl/buffer.h>
   1.127 +#include <openssl/rand.h>
   1.128 +#include <openssl/objects.h>
   1.129 +#include <openssl/evp.h>
   1.130 +#include <openssl/x509.h>
   1.131 +
   1.132 +
   1.133 +/* XDTLS:  figure out the right values */
   1.134 +#ifdef EMULATOR
   1.135 +static const unsigned int g_probable_mtu[] = {1500 - 28, 512 - 28, 256 - 28};
   1.136 +#else
   1.137 +static unsigned int g_probable_mtu[] = {1500 - 28, 512 - 28, 256 - 28};
   1.138 +#endif
   1.139 +
   1.140 +static unsigned int dtls1_min_mtu(void);
   1.141 +static unsigned int dtls1_guess_mtu(unsigned int curr_mtu);
   1.142 +static void dtls1_fix_message_header(SSL *s, unsigned long frag_off, 
   1.143 +	unsigned long frag_len);
   1.144 +static unsigned char *dtls1_write_message_header(SSL *s,
   1.145 +	unsigned char *p);
   1.146 +static void dtls1_set_message_header_int(SSL *s, unsigned char mt,
   1.147 +	unsigned long len, unsigned short seq_num, unsigned long frag_off, 
   1.148 +	unsigned long frag_len);
   1.149 +static int dtls1_retransmit_buffered_messages(SSL *s);
   1.150 +static long dtls1_get_message_fragment(SSL *s, int st1, int stn, 
   1.151 +    long max, int *ok);
   1.152 +
   1.153 +static hm_fragment *
   1.154 +dtls1_hm_fragment_new(unsigned long frag_len)
   1.155 +    {
   1.156 +    hm_fragment *frag = NULL;
   1.157 +    unsigned char *buf = NULL;
   1.158 +
   1.159 +    frag = (hm_fragment *)OPENSSL_malloc(sizeof(hm_fragment));
   1.160 +    if ( frag == NULL)
   1.161 +        return NULL;
   1.162 +
   1.163 +	if (frag_len)
   1.164 +		{
   1.165 +		buf = (unsigned char *)OPENSSL_malloc(frag_len);
   1.166 +    if ( buf == NULL)
   1.167 +        {
   1.168 +        OPENSSL_free(frag);
   1.169 +        return NULL;
   1.170 +        }
   1.171 +		}
   1.172 +    
   1.173 +	/* zero length fragment gets zero frag->fragment */
   1.174 +    frag->fragment = buf;
   1.175 +
   1.176 +    return frag;
   1.177 +    }
   1.178 +
   1.179 +static void
   1.180 +dtls1_hm_fragment_free(hm_fragment *frag)
   1.181 +    {
   1.182 +	if (frag->fragment) OPENSSL_free(frag->fragment);
   1.183 +    OPENSSL_free(frag);
   1.184 +    }
   1.185 +
   1.186 +/* send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or SSL3_RT_CHANGE_CIPHER_SPEC) */
   1.187 +int dtls1_do_write(SSL *s, int type)
   1.188 +	{
   1.189 +	int ret;
   1.190 +	int curr_mtu;
   1.191 +	unsigned int len, frag_off;
   1.192 +
   1.193 +	/* AHA!  Figure out the MTU, and stick to the right size */
   1.194 +	if ( ! (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU))
   1.195 +        {
   1.196 +		s->d1->mtu = 
   1.197 +			BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
   1.198 +
   1.199 +		/* I've seen the kernel return bogus numbers when it doesn't know
   1.200 +		 * (initial write), so just make sure we have a reasonable number */
   1.201 +		if ( s->d1->mtu < dtls1_min_mtu())
   1.202 +			{
   1.203 +			s->d1->mtu = 0;
   1.204 +			s->d1->mtu = dtls1_guess_mtu(s->d1->mtu);
   1.205 +			BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU, 
   1.206 +				s->d1->mtu, NULL);
   1.207 +			}
   1.208 +		}
   1.209 +#if 0 
   1.210 +	mtu = s->d1->mtu;
   1.211 +
   1.212 +	fprintf(stderr, "using MTU = %d\n", mtu);
   1.213 +
   1.214 +	mtu -= (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH);
   1.215 +
   1.216 +	curr_mtu = mtu - BIO_wpending(SSL_get_wbio(s));
   1.217 +
   1.218 +	if ( curr_mtu > 0)
   1.219 +		mtu = curr_mtu;
   1.220 +	else if ( ( ret = BIO_flush(SSL_get_wbio(s))) <= 0)
   1.221 +		return ret;
   1.222 +		
   1.223 +	if ( BIO_wpending(SSL_get_wbio(s)) + s->init_num >= mtu)
   1.224 +		{
   1.225 +		ret = BIO_flush(SSL_get_wbio(s));
   1.226 +		if ( ret <= 0)
   1.227 +			return ret;
   1.228 +		mtu = s->d1->mtu - (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH);
   1.229 +		}
   1.230 +
   1.231 +	OPENSSL_assert(mtu > 0);  /* should have something reasonable now */
   1.232 +
   1.233 +#endif
   1.234 +
   1.235 +	if ( s->init_off == 0  && type == SSL3_RT_HANDSHAKE)
   1.236 +		OPENSSL_assert(s->init_num == 
   1.237 +			(int)s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH);
   1.238 +
   1.239 +	frag_off = 0;
   1.240 +	while( s->init_num)
   1.241 +		{
   1.242 +		curr_mtu = s->d1->mtu - BIO_wpending(SSL_get_wbio(s)) - 
   1.243 +			DTLS1_RT_HEADER_LENGTH;
   1.244 +
   1.245 +		if ( curr_mtu <= DTLS1_HM_HEADER_LENGTH)
   1.246 +			{
   1.247 +			/* grr.. we could get an error if MTU picked was wrong */
   1.248 +			ret = BIO_flush(SSL_get_wbio(s));
   1.249 +			if ( ret <= 0)
   1.250 +				return ret;
   1.251 +			curr_mtu = s->d1->mtu - DTLS1_RT_HEADER_LENGTH;
   1.252 +			}
   1.253 +
   1.254 +		if ( s->init_num > curr_mtu)
   1.255 +			len = curr_mtu;
   1.256 +		else
   1.257 +			len = s->init_num;
   1.258 +
   1.259 +
   1.260 +		/* XDTLS: this function is too long.  split out the CCS part */
   1.261 +		if ( type == SSL3_RT_HANDSHAKE)
   1.262 +			{
   1.263 +			if ( s->init_off != 0)
   1.264 +				{
   1.265 +				OPENSSL_assert(s->init_off > DTLS1_HM_HEADER_LENGTH);
   1.266 +				s->init_off -= DTLS1_HM_HEADER_LENGTH;
   1.267 +				s->init_num += DTLS1_HM_HEADER_LENGTH;
   1.268 +
   1.269 +                /* write atleast DTLS1_HM_HEADER_LENGTH bytes */
   1.270 +				if ( len <= DTLS1_HM_HEADER_LENGTH)  
   1.271 +					len += DTLS1_HM_HEADER_LENGTH;
   1.272 +				}
   1.273 +			
   1.274 +			dtls1_fix_message_header(s, frag_off, 
   1.275 +				len - DTLS1_HM_HEADER_LENGTH);
   1.276 +
   1.277 +			dtls1_write_message_header(s, (unsigned char *)&s->init_buf->data[s->init_off]);
   1.278 +
   1.279 +			OPENSSL_assert(len >= DTLS1_HM_HEADER_LENGTH);
   1.280 +			}
   1.281 +
   1.282 +		ret=dtls1_write_bytes(s,type,&s->init_buf->data[s->init_off],
   1.283 +			len);
   1.284 +		if (ret < 0)
   1.285 +			{
   1.286 +			/* might need to update MTU here, but we don't know
   1.287 +			 * which previous packet caused the failure -- so can't
   1.288 +			 * really retransmit anything.  continue as if everything
   1.289 +			 * is fine and wait for an alert to handle the
   1.290 +			 * retransmit 
   1.291 +			 */
   1.292 +			if ( BIO_ctrl(SSL_get_wbio(s),
   1.293 +				BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL))
   1.294 +				s->d1->mtu = BIO_ctrl(SSL_get_wbio(s),
   1.295 +					BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
   1.296 +			else
   1.297 +				return(-1);
   1.298 +			}
   1.299 +		else
   1.300 +			{
   1.301 +			
   1.302 +			/* bad if this assert fails, only part of the handshake
   1.303 +			 * message got sent.  but why would this happen? */
   1.304 +			OPENSSL_assert(len == (unsigned int)ret); 
   1.305 +			
   1.306 +			if (type == SSL3_RT_HANDSHAKE && ! s->d1->retransmitting)
   1.307 +				{
   1.308 +				/* should not be done for 'Hello Request's, but in that case
   1.309 +				 * we'll ignore the result anyway */
   1.310 +				unsigned char *p = (unsigned char *)&s->init_buf->data[s->init_off];
   1.311 +				const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
   1.312 +				int xlen;
   1.313 +
   1.314 +				if (frag_off == 0 && s->client_version != DTLS1_BAD_VER)
   1.315 +					{
   1.316 +					/* reconstruct message header is if it
   1.317 +					 * is being sent in single fragment */
   1.318 +					*p++ = msg_hdr->type;
   1.319 +					l2n3(msg_hdr->msg_len,p);
   1.320 +					s2n (msg_hdr->seq,p);
   1.321 +					l2n3(0,p);
   1.322 +					l2n3(msg_hdr->msg_len,p);
   1.323 +					p  -= DTLS1_HM_HEADER_LENGTH;
   1.324 +					xlen = ret;
   1.325 +					}
   1.326 +				else
   1.327 +					{
   1.328 +					p  += DTLS1_HM_HEADER_LENGTH;
   1.329 +					xlen = ret - DTLS1_HM_HEADER_LENGTH;
   1.330 +					}
   1.331 +
   1.332 +				ssl3_finish_mac(s, p, xlen);
   1.333 +				}
   1.334 +			
   1.335 +			if (ret == s->init_num)
   1.336 +				{
   1.337 +				if (s->msg_callback)
   1.338 +					s->msg_callback(1, s->version, type, s->init_buf->data, 
   1.339 +						(size_t)(s->init_off + s->init_num), s, 
   1.340 +						s->msg_callback_arg);
   1.341 +
   1.342 +				s->init_off = 0;  /* done writing this message */
   1.343 +				s->init_num = 0;
   1.344 +				
   1.345 +				return(1);
   1.346 +				}
   1.347 +			s->init_off+=ret;
   1.348 +			s->init_num-=ret;
   1.349 +			frag_off += (ret -= DTLS1_HM_HEADER_LENGTH);
   1.350 +			}
   1.351 +		}
   1.352 +	return(0);
   1.353 +	}
   1.354 +
   1.355 +
   1.356 +/* Obtain handshake message of message type 'mt' (any if mt == -1),
   1.357 + * maximum acceptable body length 'max'.
   1.358 + * Read an entire handshake message.  Handshake messages arrive in
   1.359 + * fragments.
   1.360 + */
   1.361 +long dtls1_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok)
   1.362 +	{
   1.363 +	int i, al;
   1.364 +	struct hm_header_st *msg_hdr;
   1.365 +
   1.366 +	/* s3->tmp is used to store messages that are unexpected, caused
   1.367 +	 * by the absence of an optional handshake message */
   1.368 +	if (s->s3->tmp.reuse_message)
   1.369 +		{
   1.370 +		s->s3->tmp.reuse_message=0;
   1.371 +		if ((mt >= 0) && (s->s3->tmp.message_type != mt))
   1.372 +			{
   1.373 +			al=SSL_AD_UNEXPECTED_MESSAGE;
   1.374 +			SSLerr(SSL_F_DTLS1_GET_MESSAGE,SSL_R_UNEXPECTED_MESSAGE);
   1.375 +			goto f_err;
   1.376 +			}
   1.377 +		*ok=1;
   1.378 +		s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
   1.379 +		s->init_num = (int)s->s3->tmp.message_size;
   1.380 +		return s->init_num;
   1.381 +		}
   1.382 +	
   1.383 +	msg_hdr = &s->d1->r_msg_hdr;
   1.384 +	do
   1.385 +		{
   1.386 +		if ( msg_hdr->frag_off == 0)
   1.387 +			{
   1.388 +			/* s->d1->r_message_header.msg_len = 0; */
   1.389 +			memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
   1.390 +			}
   1.391 +
   1.392 +		i = dtls1_get_message_fragment(s, st1, stn, max, ok);
   1.393 +		if ( i == DTLS1_HM_BAD_FRAGMENT ||
   1.394 +            i == DTLS1_HM_FRAGMENT_RETRY)  /* bad fragment received */
   1.395 +			continue;
   1.396 +		else if ( i <= 0 && !*ok)
   1.397 +			return i;
   1.398 +
   1.399 +		/* Note that s->init_sum is used as a counter summing
   1.400 +		 * up fragments' lengths: as soon as they sum up to
   1.401 +		 * handshake packet length, we assume we have got all
   1.402 +		 * the fragments. Overlapping fragments would cause
   1.403 +		 * premature termination, so we don't expect overlaps.
   1.404 +		 * Well, handling overlaps would require something more
   1.405 +		 * drastic. Indeed, as it is now there is no way to
   1.406 +		 * tell if out-of-order fragment from the middle was
   1.407 +		 * the last. '>=' is the best/least we can do to control
   1.408 +		 * the potential damage caused by malformed overlaps. */
   1.409 +		if ((unsigned int)s->init_num >= msg_hdr->msg_len)
   1.410 +			{
   1.411 +			unsigned char *p = (unsigned char *)s->init_buf->data;
   1.412 +			unsigned long msg_len = msg_hdr->msg_len;
   1.413 +
   1.414 +			/* reconstruct message header as if it was
   1.415 +			 * sent in single fragment */
   1.416 +			*(p++) = msg_hdr->type;
   1.417 +			l2n3(msg_len,p);
   1.418 +			s2n (msg_hdr->seq,p);
   1.419 +			l2n3(0,p);
   1.420 +			l2n3(msg_len,p);
   1.421 +			if (s->client_version != DTLS1_BAD_VER)
   1.422 +				p       -= DTLS1_HM_HEADER_LENGTH,
   1.423 +				msg_len += DTLS1_HM_HEADER_LENGTH;
   1.424 +
   1.425 +			ssl3_finish_mac(s, p, msg_len);
   1.426 +			if (s->msg_callback)
   1.427 +				s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
   1.428 +					p, msg_len,
   1.429 +					s, s->msg_callback_arg);
   1.430 +
   1.431 +			memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
   1.432 +
   1.433 +			s->d1->handshake_read_seq++;
   1.434 +			/* we just read a handshake message from the other side:
   1.435 +			 * this means that we don't need to retransmit of the
   1.436 +			 * buffered messages.  
   1.437 +			 * XDTLS: may be able clear out this
   1.438 +			 * buffer a little sooner (i.e if an out-of-order
   1.439 +			 * handshake message/record is received at the record
   1.440 +			 * layer.  
   1.441 +			 * XDTLS: exception is that the server needs to
   1.442 +			 * know that change cipher spec and finished messages
   1.443 +			 * have been received by the client before clearing this
   1.444 +			 * buffer.  this can simply be done by waiting for the
   1.445 +			 * first data  segment, but is there a better way?  */
   1.446 +			dtls1_clear_record_buffer(s);
   1.447 +
   1.448 +			s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
   1.449 +			return s->init_num;
   1.450 +			}
   1.451 +		else
   1.452 +			msg_hdr->frag_off = i;
   1.453 +		} while(1) ;
   1.454 +
   1.455 +f_err:
   1.456 +	ssl3_send_alert(s,SSL3_AL_FATAL,al);
   1.457 +	*ok = 0;
   1.458 +	return -1;
   1.459 +	}
   1.460 +
   1.461 +
   1.462 +static int dtls1_preprocess_fragment(SSL *s,struct hm_header_st *msg_hdr,int max)
   1.463 +	{
   1.464 +	size_t frag_off,frag_len,msg_len;
   1.465 +
   1.466 +	msg_len  = msg_hdr->msg_len;
   1.467 +	frag_off = msg_hdr->frag_off;
   1.468 +	frag_len = msg_hdr->frag_len;
   1.469 +
   1.470 +	/* sanity checking */
   1.471 +	if ( (frag_off+frag_len) > msg_len)
   1.472 +		{
   1.473 +		SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,SSL_R_EXCESSIVE_MESSAGE_SIZE);
   1.474 +		return SSL_AD_ILLEGAL_PARAMETER;
   1.475 +		}
   1.476 +
   1.477 +	if ( (frag_off+frag_len) > (unsigned long)max)
   1.478 +		{
   1.479 +		SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,SSL_R_EXCESSIVE_MESSAGE_SIZE);
   1.480 +		return SSL_AD_ILLEGAL_PARAMETER;
   1.481 +		}
   1.482 +
   1.483 +	if ( s->d1->r_msg_hdr.frag_off == 0) /* first fragment */
   1.484 +		{
   1.485 +		/* msg_len is limited to 2^24, but is effectively checked
   1.486 +		 * against max above */
   1.487 +		if (!BUF_MEM_grow_clean(s->init_buf,(int)msg_len+DTLS1_HM_HEADER_LENGTH))
   1.488 +			{
   1.489 +			SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,ERR_R_BUF_LIB);
   1.490 +			return SSL_AD_INTERNAL_ERROR;
   1.491 +			}
   1.492 +
   1.493 +		s->s3->tmp.message_size  = msg_len;
   1.494 +		s->d1->r_msg_hdr.msg_len = msg_len;
   1.495 +		s->s3->tmp.message_type  = msg_hdr->type;
   1.496 +		s->d1->r_msg_hdr.type    = msg_hdr->type;
   1.497 +		s->d1->r_msg_hdr.seq     = msg_hdr->seq;
   1.498 +		}
   1.499 +	else if (msg_len != s->d1->r_msg_hdr.msg_len)
   1.500 +		{
   1.501 +		/* They must be playing with us! BTW, failure to enforce
   1.502 +		 * upper limit would open possibility for buffer overrun. */
   1.503 +		SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,SSL_R_EXCESSIVE_MESSAGE_SIZE);
   1.504 +		return SSL_AD_ILLEGAL_PARAMETER;
   1.505 +		}
   1.506 +
   1.507 +	return 0; /* no error */
   1.508 +	}
   1.509 +
   1.510 +
   1.511 +static int
   1.512 +dtls1_retrieve_buffered_fragment(SSL *s, long max, int *ok)
   1.513 +    {
   1.514 +    /* (0) check whether the desired fragment is available
   1.515 +     * if so:
   1.516 +     * (1) copy over the fragment to s->init_buf->data[]
   1.517 +     * (2) update s->init_num
   1.518 +     */
   1.519 +    pitem *item;
   1.520 +    hm_fragment *frag;
   1.521 +	int al;
   1.522 +
   1.523 +	*ok = 0;
   1.524 +    item = pqueue_peek(s->d1->buffered_messages);
   1.525 +    if ( item == NULL)
   1.526 +        return 0;
   1.527 +
   1.528 +    frag = (hm_fragment *)item->data;
   1.529 +    
   1.530 +	if ( s->d1->handshake_read_seq == frag->msg_header.seq)
   1.531 +        {
   1.532 +        pqueue_pop(s->d1->buffered_messages);
   1.533 +
   1.534 +		al=dtls1_preprocess_fragment(s,&frag->msg_header,max);
   1.535 +
   1.536 +		if (al==0) /* no alert */
   1.537 +			{
   1.538 +			unsigned char *p = (unsigned char *)s->init_buf->data+DTLS1_HM_HEADER_LENGTH;
   1.539 +			memcpy(&p[frag->msg_header.frag_off],
   1.540 +				frag->fragment,frag->msg_header.frag_len);
   1.541 +			}
   1.542 +
   1.543 +		dtls1_hm_fragment_free(frag);
   1.544 +        pitem_free(item);
   1.545 +
   1.546 +		if (al==0)
   1.547 +			{
   1.548 +			*ok = 1;
   1.549 +			return frag->msg_header.frag_len;
   1.550 +			}
   1.551 +
   1.552 +		ssl3_send_alert(s,SSL3_AL_FATAL,al);
   1.553 +		s->init_num = 0;
   1.554 +		*ok = 0;
   1.555 +		return -1;
   1.556 +        }
   1.557 +    else
   1.558 +        return 0;
   1.559 +    }
   1.560 +
   1.561 +
   1.562 +static int
   1.563 +dtls1_process_out_of_seq_message(SSL *s, struct hm_header_st* msg_hdr, int *ok)
   1.564 +{
   1.565 +	int i=-1;
   1.566 +    hm_fragment *frag = NULL;
   1.567 +    pitem *item = NULL;
   1.568 +	PQ_64BIT seq64;
   1.569 +	unsigned long frag_len = msg_hdr->frag_len;
   1.570 +
   1.571 +	if ((msg_hdr->frag_off+frag_len) > msg_hdr->msg_len)
   1.572 +		goto err;
   1.573 +
   1.574 +	if (msg_hdr->seq <= s->d1->handshake_read_seq)
   1.575 +		{
   1.576 +		unsigned char devnull [256];
   1.577 +
   1.578 +		while (frag_len)
   1.579 +			{
   1.580 +			i = s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,
   1.581 +				devnull,
   1.582 +				frag_len>sizeof(devnull)?sizeof(devnull):frag_len,0);
   1.583 +			if (i<=0) goto err;
   1.584 +			frag_len -= i;
   1.585 +			}
   1.586 +		}
   1.587 +	frag = dtls1_hm_fragment_new(frag_len);
   1.588 +    if ( frag == NULL)
   1.589 +        goto err;
   1.590 +
   1.591 +
   1.592 +    memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
   1.593 +
   1.594 +	if (frag_len)
   1.595 +		{
   1.596 +		/* read the body of the fragment (header has already been read */
   1.597 +		i = s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,
   1.598 +			frag->fragment,frag_len,0);
   1.599 +		if (i<=0 || (unsigned long)i!=frag_len)
   1.600 +			goto err;
   1.601 +		}
   1.602 +    pq_64bit_init(&seq64);
   1.603 +    pq_64bit_assign_word(&seq64, msg_hdr->seq);
   1.604 +
   1.605 +    item = pitem_new(seq64, frag);
   1.606 +	pq_64bit_free(&seq64);
   1.607 +    if ( item == NULL)
   1.608 +        goto err;
   1.609 +
   1.610 +    pqueue_insert(s->d1->buffered_messages, item);
   1.611 +	return DTLS1_HM_FRAGMENT_RETRY;
   1.612 +
   1.613 +err:
   1.614 +    if ( frag != NULL) dtls1_hm_fragment_free(frag);
   1.615 +    if ( item != NULL) OPENSSL_free(item);
   1.616 +	*ok = 0;
   1.617 +	return i;
   1.618 +	}
   1.619 +
   1.620 +
   1.621 +static long
   1.622 +dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok)
   1.623 +	{
   1.624 +	unsigned char wire[DTLS1_HM_HEADER_LENGTH];
   1.625 +	unsigned long l, frag_off, frag_len;
   1.626 +	int i,al;
   1.627 +	struct hm_header_st msg_hdr;
   1.628 +    
   1.629 +    /* see if we have the required fragment already */
   1.630 +	if ((frag_len = dtls1_retrieve_buffered_fragment(s,max,ok)) || *ok)
   1.631 +    {
   1.632 +		if (*ok)	s->init_num += frag_len;
   1.633 +		return frag_len;
   1.634 +    }
   1.635 +
   1.636 +    /* read handshake message header */
   1.637 +	i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,wire,
   1.638 +		DTLS1_HM_HEADER_LENGTH, 0);
   1.639 +	if (i <= 0) 	/* nbio, or an error */
   1.640 +		{
   1.641 +		s->rwstate=SSL_READING;
   1.642 +		*ok = 0;
   1.643 +		return i;
   1.644 +		}
   1.645 +
   1.646 +	OPENSSL_assert(i == DTLS1_HM_HEADER_LENGTH);
   1.647 +
   1.648 +    /* parse the message fragment header */
   1.649 +    
   1.650 +	dtls1_get_message_header(wire, &msg_hdr);
   1.651 +
   1.652 +    /* 
   1.653 +     * if this is a future (or stale) message it gets buffered
   1.654 +     * (or dropped)--no further processing at this time 
   1.655 +     */
   1.656 +    if ( msg_hdr.seq != s->d1->handshake_read_seq)
   1.657 +        return dtls1_process_out_of_seq_message(s, &msg_hdr, ok);
   1.658 +
   1.659 +    l = msg_hdr.msg_len;
   1.660 +    frag_off = msg_hdr.frag_off;
   1.661 +	frag_len = msg_hdr.frag_len;
   1.662 +
   1.663 +	if (!s->server && s->d1->r_msg_hdr.frag_off == 0 &&
   1.664 +		wire[0] == SSL3_MT_HELLO_REQUEST)
   1.665 +        {
   1.666 +        /* The server may always send 'Hello Request' messages --
   1.667 +         * we are doing a handshake anyway now, so ignore them
   1.668 +         * if their format is correct. Does not count for
   1.669 +         * 'Finished' MAC. */
   1.670 +		if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0)
   1.671 +            {
   1.672 +            if (s->msg_callback)
   1.673 +                s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, 
   1.674 +					wire, DTLS1_HM_HEADER_LENGTH, s, 
   1.675 +                    s->msg_callback_arg);
   1.676 +            
   1.677 +            s->init_num = 0;
   1.678 +            return dtls1_get_message_fragment(s, st1, stn,
   1.679 +                max, ok);
   1.680 +            }
   1.681 +        else /* Incorrectly formated Hello request */
   1.682 +            {
   1.683 +            al=SSL_AD_UNEXPECTED_MESSAGE;
   1.684 +            SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,SSL_R_UNEXPECTED_MESSAGE);
   1.685 +            goto f_err;
   1.686 +            }
   1.687 +        }
   1.688 +
   1.689 +	if ((al=dtls1_preprocess_fragment(s,&msg_hdr,max)))
   1.690 +		goto f_err;
   1.691 +
   1.692 +	/* XDTLS:  ressurect this when restart is in place */
   1.693 +	s->state=stn;
   1.694 +
   1.695 +	if ( frag_len > 0)
   1.696 +		{
   1.697 +		unsigned char *p=(unsigned char *)s->init_buf->data+DTLS1_HM_HEADER_LENGTH;
   1.698 +
   1.699 +		i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,
   1.700 +			&p[frag_off],frag_len,0);
   1.701 +        /* XDTLS:  fix this--message fragments cannot span multiple packets */
   1.702 +		if (i <= 0)
   1.703 +			{
   1.704 +			s->rwstate=SSL_READING;
   1.705 +			*ok = 0;
   1.706 +			return i;
   1.707 +			}
   1.708 +		}
   1.709 +	else
   1.710 +		i = 0;
   1.711 +
   1.712 +    /* XDTLS:  an incorrectly formatted fragment should cause the 
   1.713 +     * handshake to fail */
   1.714 +	OPENSSL_assert(i == (int)frag_len);
   1.715 +
   1.716 +	*ok = 1;
   1.717 +
   1.718 +	/* Note that s->init_num is *not* used as current offset in
   1.719 +	 * s->init_buf->data, but as a counter summing up fragments'
   1.720 +	 * lengths: as soon as they sum up to handshake packet
   1.721 +	 * length, we assume we have got all the fragments. */
   1.722 +	s->init_num += frag_len;
   1.723 +	return frag_len;
   1.724 +
   1.725 +f_err:
   1.726 +	ssl3_send_alert(s,SSL3_AL_FATAL,al);
   1.727 +    s->init_num = 0;
   1.728 +
   1.729 +	*ok=0;
   1.730 +	return(-1);
   1.731 +	}
   1.732 +
   1.733 +int dtls1_send_finished(SSL *s, int a, int b, const char *sender, int slen)
   1.734 +	{
   1.735 +	unsigned char *p,*d;
   1.736 +	int i;
   1.737 +	unsigned long l;
   1.738 +
   1.739 +	if (s->state == a)
   1.740 +		{
   1.741 +		d=(unsigned char *)s->init_buf->data;
   1.742 +		p= &(d[DTLS1_HM_HEADER_LENGTH]);
   1.743 +
   1.744 +		i=s->method->ssl3_enc->final_finish_mac(s,
   1.745 +			&(s->s3->finish_dgst1),
   1.746 +			&(s->s3->finish_dgst2),
   1.747 +			sender,slen,s->s3->tmp.finish_md);
   1.748 +		s->s3->tmp.finish_md_len = i;
   1.749 +		memcpy(p, s->s3->tmp.finish_md, i);
   1.750 +		p+=i;
   1.751 +		l=i;
   1.752 +
   1.753 +#ifdef OPENSSL_SYS_WIN16
   1.754 +		/* MSVC 1.5 does not clear the top bytes of the word unless
   1.755 +		 * I do this.
   1.756 +		 */
   1.757 +		l&=0xffff;
   1.758 +#endif
   1.759 +
   1.760 +		d = dtls1_set_message_header(s, d, SSL3_MT_FINISHED, l, 0, l);
   1.761 +		s->init_num=(int)l+DTLS1_HM_HEADER_LENGTH;
   1.762 +		s->init_off=0;
   1.763 +
   1.764 +		/* buffer the message to handle re-xmits */
   1.765 +		dtls1_buffer_message(s, 0);
   1.766 +		
   1.767 +		s->state=b;
   1.768 +		}
   1.769 +
   1.770 +	/* SSL3_ST_SEND_xxxxxx_HELLO_B */
   1.771 +	return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
   1.772 +	}
   1.773 +
   1.774 +/* for these 2 messages, we need to
   1.775 + * ssl->enc_read_ctx			re-init
   1.776 + * ssl->s3->read_sequence		zero
   1.777 + * ssl->s3->read_mac_secret		re-init
   1.778 + * ssl->session->read_sym_enc		assign
   1.779 + * ssl->session->read_compression	assign
   1.780 + * ssl->session->read_hash		assign
   1.781 + */
   1.782 +int dtls1_send_change_cipher_spec(SSL *s, int a, int b)
   1.783 +	{ 
   1.784 +	unsigned char *p;
   1.785 +
   1.786 +	if (s->state == a)
   1.787 +		{
   1.788 +		p=(unsigned char *)s->init_buf->data;
   1.789 +		*p++=SSL3_MT_CCS;
   1.790 +		s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
   1.791 +		s->init_num=DTLS1_CCS_HEADER_LENGTH;
   1.792 +
   1.793 +		if (s->client_version == DTLS1_BAD_VER)
   1.794 +			{
   1.795 +			s->d1->next_handshake_write_seq++;
   1.796 +			s2n(s->d1->handshake_write_seq,p);
   1.797 +			s->init_num+=2;
   1.798 +			}
   1.799 +
   1.800 +		s->init_off=0;
   1.801 +
   1.802 +		dtls1_set_message_header_int(s, SSL3_MT_CCS, 0, 
   1.803 +			s->d1->handshake_write_seq, 0, 0);
   1.804 +
   1.805 +		/* buffer the message to handle re-xmits */
   1.806 +		dtls1_buffer_message(s, 1);
   1.807 +
   1.808 +		s->state=b;
   1.809 +		}
   1.810 +
   1.811 +	/* SSL3_ST_CW_CHANGE_B */
   1.812 +	return(dtls1_do_write(s,SSL3_RT_CHANGE_CIPHER_SPEC));
   1.813 +	}
   1.814 +
   1.815 +unsigned long dtls1_output_cert_chain(SSL *s, X509 *x)
   1.816 +	{
   1.817 +	unsigned char *p;
   1.818 +	int n,i;
   1.819 +	unsigned long l= 3 + DTLS1_HM_HEADER_LENGTH;
   1.820 +	BUF_MEM *buf;
   1.821 +	X509_STORE_CTX xs_ctx;
   1.822 +	X509_OBJECT obj;
   1.823 +
   1.824 +	/* TLSv1 sends a chain with nothing in it, instead of an alert */
   1.825 +	buf=s->init_buf;
   1.826 +	if (!BUF_MEM_grow_clean(buf,10))
   1.827 +		{
   1.828 +		SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN,ERR_R_BUF_LIB);
   1.829 +		return(0);
   1.830 +		}
   1.831 +	if (x != NULL)
   1.832 +		{
   1.833 +		if(!X509_STORE_CTX_init(&xs_ctx,s->ctx->cert_store,NULL,NULL))
   1.834 +			{
   1.835 +			SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN,ERR_R_X509_LIB);
   1.836 +			return(0);
   1.837 +			}
   1.838 +
   1.839 +		for (;;)
   1.840 +			{
   1.841 +			n=i2d_X509(x,NULL);
   1.842 +			if (!BUF_MEM_grow_clean(buf,(int)(n+l+3)))
   1.843 +				{
   1.844 +				SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN,ERR_R_BUF_LIB);
   1.845 +				return(0);
   1.846 +				}
   1.847 +			p=(unsigned char *)&(buf->data[l]);
   1.848 +			l2n3(n,p);
   1.849 +			i2d_X509(x,&p);
   1.850 +			l+=n+3;
   1.851 +			if (X509_NAME_cmp(X509_get_subject_name(x),
   1.852 +				X509_get_issuer_name(x)) == 0) break;
   1.853 +
   1.854 +			i=X509_STORE_get_by_subject(&xs_ctx,X509_LU_X509,
   1.855 +				X509_get_issuer_name(x),&obj);
   1.856 +			if (i <= 0) break;
   1.857 +			x=obj.data.x509;
   1.858 +			/* Count is one too high since the X509_STORE_get uped the
   1.859 +			 * ref count */
   1.860 +			X509_free(x);
   1.861 +			}
   1.862 +
   1.863 +		X509_STORE_CTX_cleanup(&xs_ctx);
   1.864 +		}
   1.865 +
   1.866 +	/* Thawte special :-) */
   1.867 +	if (s->ctx->extra_certs != NULL)
   1.868 +	for (i=0; i<sk_X509_num(s->ctx->extra_certs); i++)
   1.869 +		{
   1.870 +		x=sk_X509_value(s->ctx->extra_certs,i);
   1.871 +		n=i2d_X509(x,NULL);
   1.872 +		if (!BUF_MEM_grow_clean(buf,(int)(n+l+3)))
   1.873 +			{
   1.874 +			SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN,ERR_R_BUF_LIB);
   1.875 +			return(0);
   1.876 +			}
   1.877 +		p=(unsigned char *)&(buf->data[l]);
   1.878 +		l2n3(n,p);
   1.879 +		i2d_X509(x,&p);
   1.880 +		l+=n+3;
   1.881 +		}
   1.882 +
   1.883 +	l-= (3 + DTLS1_HM_HEADER_LENGTH);
   1.884 +
   1.885 +	p=(unsigned char *)&(buf->data[DTLS1_HM_HEADER_LENGTH]);
   1.886 +	l2n3(l,p);
   1.887 +	l+=3;
   1.888 +	p=(unsigned char *)&(buf->data[0]);
   1.889 +	p = dtls1_set_message_header(s, p, SSL3_MT_CERTIFICATE, l, 0, l);
   1.890 +
   1.891 +	l+=DTLS1_HM_HEADER_LENGTH;
   1.892 +	return(l);
   1.893 +	}
   1.894 +
   1.895 +int dtls1_read_failed(SSL *s, int code)
   1.896 +    {
   1.897 +    DTLS1_STATE *state;
   1.898 +    BIO *bio;
   1.899 +    int send_alert = 0;
   1.900 +
   1.901 +    if ( code > 0)
   1.902 +        {
   1.903 +        fprintf( stderr, "invalid state reached %s:%d", __FILE__, __LINE__);
   1.904 +        return 1;
   1.905 +        }
   1.906 +
   1.907 +    bio = SSL_get_rbio(s);
   1.908 +    if ( ! BIO_dgram_recv_timedout(bio))
   1.909 +        {
   1.910 +        /* not a timeout, none of our business, 
   1.911 +           let higher layers handle this.  in fact it's probably an error */
   1.912 +        return code;
   1.913 +        }
   1.914 +
   1.915 +    if ( ! SSL_in_init(s))  /* done, no need to send a retransmit */
   1.916 +        {
   1.917 +        BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
   1.918 +        return code;
   1.919 +        }
   1.920 +
   1.921 +    state = s->d1;
   1.922 +    state->timeout.num_alerts++;
   1.923 +    if ( state->timeout.num_alerts > DTLS1_TMO_ALERT_COUNT)
   1.924 +        {
   1.925 +        /* fail the connection, enough alerts have been sent */
   1.926 +        SSLerr(SSL_F_DTLS1_READ_FAILED,SSL_R_READ_TIMEOUT_EXPIRED);
   1.927 +        return 0;
   1.928 +        }
   1.929 +	
   1.930 +    state->timeout.read_timeouts++;
   1.931 +    if ( state->timeout.read_timeouts > DTLS1_TMO_READ_COUNT)
   1.932 +        {
   1.933 +        send_alert = 1;
   1.934 +        state->timeout.read_timeouts = 1;
   1.935 +        }
   1.936 +
   1.937 +	
   1.938 +#if 0 /* for now, each alert contains only one record number */
   1.939 +    item = pqueue_peek(state->rcvd_records);
   1.940 +    if ( item )
   1.941 +        {
   1.942 +        /* send an alert immediately for all the missing records */
   1.943 +        }
   1.944 +    else
   1.945 +#endif
   1.946 +
   1.947 +#if 0  /* no more alert sending, just retransmit the last set of messages */
   1.948 +        if ( send_alert)
   1.949 +            ssl3_send_alert(s,SSL3_AL_WARNING,
   1.950 +                DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
   1.951 +#endif
   1.952 +
   1.953 +    return dtls1_retransmit_buffered_messages(s) ;
   1.954 +    }
   1.955 +
   1.956 +
   1.957 +static int
   1.958 +dtls1_retransmit_buffered_messages(SSL *s)
   1.959 +    {
   1.960 +    pqueue sent = s->d1->sent_messages;
   1.961 +    piterator iter;
   1.962 +    pitem *item;
   1.963 +    hm_fragment *frag;
   1.964 +    int found = 0;
   1.965 +
   1.966 +    iter = pqueue_iterator(sent);
   1.967 +
   1.968 +    for ( item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter))
   1.969 +        {
   1.970 +        frag = (hm_fragment *)item->data;
   1.971 +        if ( dtls1_retransmit_message(s, frag->msg_header.seq, 0, &found) <= 0 &&
   1.972 +            found)
   1.973 +            {
   1.974 +            fprintf(stderr, "dtls1_retransmit_message() failed\n");
   1.975 +            return -1;
   1.976 +            }
   1.977 +        }
   1.978 +
   1.979 +    return 1;
   1.980 +    }
   1.981 +
   1.982 +
   1.983 +int
   1.984 +dtls1_buffer_message(SSL *s, int is_ccs)
   1.985 +    {
   1.986 +    pitem *item;
   1.987 +    hm_fragment *frag;
   1.988 +	PQ_64BIT seq64;
   1.989 +	unsigned int epoch = s->d1->w_epoch;
   1.990 +
   1.991 +    /* this function is called immediately after a message has 
   1.992 +     * been serialized */
   1.993 +    OPENSSL_assert(s->init_off == 0);
   1.994 +
   1.995 +    frag = dtls1_hm_fragment_new(s->init_num);
   1.996 +
   1.997 +    memcpy(frag->fragment, s->init_buf->data, s->init_num);
   1.998 +
   1.999 +    if ( is_ccs)
  1.1000 +        {
  1.1001 +        OPENSSL_assert(s->d1->w_msg_hdr.msg_len + 
  1.1002 +			DTLS1_CCS_HEADER_LENGTH <= (unsigned int)s->init_num);
  1.1003 +		epoch++;
  1.1004 +        }
  1.1005 +    else
  1.1006 +        {
  1.1007 +        OPENSSL_assert(s->d1->w_msg_hdr.msg_len + 
  1.1008 +            DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num);
  1.1009 +        }
  1.1010 +
  1.1011 +    frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
  1.1012 +    frag->msg_header.seq = s->d1->w_msg_hdr.seq;
  1.1013 +    frag->msg_header.type = s->d1->w_msg_hdr.type;
  1.1014 +    frag->msg_header.frag_off = 0;
  1.1015 +    frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
  1.1016 +    frag->msg_header.is_ccs = is_ccs;
  1.1017 +
  1.1018 +    pq_64bit_init(&seq64);
  1.1019 +	pq_64bit_assign_word(&seq64, epoch<<16 | frag->msg_header.seq);
  1.1020 +
  1.1021 +    item = pitem_new(seq64, frag);
  1.1022 +    pq_64bit_free(&seq64);
  1.1023 +    if ( item == NULL)
  1.1024 +        {
  1.1025 +        dtls1_hm_fragment_free(frag);
  1.1026 +        return 0;
  1.1027 +        }
  1.1028 +
  1.1029 +#if 0
  1.1030 +    fprintf( stderr, "buffered messge: \ttype = %xx\n", msg_buf->type);
  1.1031 +    fprintf( stderr, "\t\t\t\t\tlen = %d\n", msg_buf->len);
  1.1032 +    fprintf( stderr, "\t\t\t\t\tseq_num = %d\n", msg_buf->seq_num);
  1.1033 +#endif
  1.1034 +
  1.1035 +    pqueue_insert(s->d1->sent_messages, item);
  1.1036 +    return 1;
  1.1037 +    }
  1.1038 +
  1.1039 +int
  1.1040 +dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off,
  1.1041 +    int *found)
  1.1042 +    {
  1.1043 +    int ret;
  1.1044 +    /* XDTLS: for now assuming that read/writes are blocking */
  1.1045 +    pitem *item;
  1.1046 +    hm_fragment *frag ;
  1.1047 +    unsigned long header_length;
  1.1048 +	PQ_64BIT seq64;
  1.1049 +
  1.1050 +    /*
  1.1051 +      OPENSSL_assert(s->init_num == 0);
  1.1052 +      OPENSSL_assert(s->init_off == 0);
  1.1053 +     */
  1.1054 +
  1.1055 +    /* XDTLS:  the requested message ought to be found, otherwise error */
  1.1056 +    pq_64bit_init(&seq64);
  1.1057 +    pq_64bit_assign_word(&seq64, seq);
  1.1058 +
  1.1059 +    item = pqueue_find(s->d1->sent_messages, seq64);
  1.1060 +    pq_64bit_free(&seq64);
  1.1061 +    if ( item == NULL)
  1.1062 +        {
  1.1063 +        fprintf(stderr, "retransmit:  message %d non-existant\n", seq);
  1.1064 +        *found = 0;
  1.1065 +        return 0;
  1.1066 +        }
  1.1067 +
  1.1068 +    *found = 1;
  1.1069 +    frag = (hm_fragment *)item->data;
  1.1070 +
  1.1071 +    if ( frag->msg_header.is_ccs)
  1.1072 +        header_length = DTLS1_CCS_HEADER_LENGTH;
  1.1073 +    else
  1.1074 +        header_length = DTLS1_HM_HEADER_LENGTH;
  1.1075 +
  1.1076 +    memcpy(s->init_buf->data, frag->fragment, 
  1.1077 +        frag->msg_header.msg_len + header_length);
  1.1078 +        s->init_num = frag->msg_header.msg_len + header_length;
  1.1079 +    
  1.1080 +    dtls1_set_message_header_int(s, frag->msg_header.type, 
  1.1081 +        frag->msg_header.msg_len, frag->msg_header.seq, 0, 
  1.1082 +        frag->msg_header.frag_len);
  1.1083 +
  1.1084 +    s->d1->retransmitting = 1;
  1.1085 +    ret = dtls1_do_write(s, frag->msg_header.is_ccs ? 
  1.1086 +        SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
  1.1087 +    s->d1->retransmitting = 0;
  1.1088 +
  1.1089 +	(void)BIO_flush(SSL_get_wbio(s));
  1.1090 +    return ret;
  1.1091 +    }
  1.1092 +
  1.1093 +/* call this function when the buffered messages are no longer needed */
  1.1094 +void
  1.1095 +dtls1_clear_record_buffer(SSL *s)
  1.1096 +    {
  1.1097 +    pitem *item;
  1.1098 +    
  1.1099 +    for(item = pqueue_pop(s->d1->sent_messages);
  1.1100 +        item != NULL; item = pqueue_pop(s->d1->sent_messages))
  1.1101 +        {
  1.1102 +        dtls1_hm_fragment_free((hm_fragment *)item->data);
  1.1103 +        pitem_free(item);
  1.1104 +        }
  1.1105 +    }
  1.1106 +
  1.1107 +
  1.1108 +unsigned char *
  1.1109 +dtls1_set_message_header(SSL *s, unsigned char *p, unsigned char mt,
  1.1110 +    unsigned long len, unsigned long frag_off, unsigned long frag_len)
  1.1111 +    {
  1.1112 +    if ( frag_off == 0)
  1.1113 +        {
  1.1114 +        s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
  1.1115 +        s->d1->next_handshake_write_seq++;
  1.1116 +        }
  1.1117 +    
  1.1118 +    dtls1_set_message_header_int(s, mt, len, s->d1->handshake_write_seq,
  1.1119 +        frag_off, frag_len);
  1.1120 +    
  1.1121 +    return p += DTLS1_HM_HEADER_LENGTH;
  1.1122 +    }
  1.1123 +
  1.1124 +
  1.1125 +/* don't actually do the writing, wait till the MTU has been retrieved */
  1.1126 +static void
  1.1127 +dtls1_set_message_header_int(SSL *s, unsigned char mt,
  1.1128 +    unsigned long len, unsigned short seq_num, unsigned long frag_off, 
  1.1129 +    unsigned long frag_len)
  1.1130 +    {
  1.1131 +    struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  1.1132 +    
  1.1133 +    msg_hdr->type = mt;
  1.1134 +    msg_hdr->msg_len = len;
  1.1135 +    msg_hdr->seq = seq_num;
  1.1136 +    msg_hdr->frag_off = frag_off;
  1.1137 +    msg_hdr->frag_len = frag_len;
  1.1138 +}
  1.1139 +
  1.1140 +static void
  1.1141 +dtls1_fix_message_header(SSL *s, unsigned long frag_off,
  1.1142 +	unsigned long frag_len)
  1.1143 +    {
  1.1144 +    struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  1.1145 +    
  1.1146 +    msg_hdr->frag_off = frag_off;
  1.1147 +    msg_hdr->frag_len = frag_len;
  1.1148 +    }
  1.1149 +
  1.1150 +static unsigned char *
  1.1151 +dtls1_write_message_header(SSL *s, unsigned char *p)
  1.1152 +    {
  1.1153 +    struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  1.1154 +    
  1.1155 +    *p++ = msg_hdr->type;
  1.1156 +    l2n3(msg_hdr->msg_len, p);
  1.1157 +    
  1.1158 +    s2n(msg_hdr->seq, p);
  1.1159 +    l2n3(msg_hdr->frag_off, p);
  1.1160 +    l2n3(msg_hdr->frag_len, p);
  1.1161 +    
  1.1162 +    return p;
  1.1163 +    }
  1.1164 +
  1.1165 +static unsigned int 
  1.1166 +dtls1_min_mtu(void)
  1.1167 +    {
  1.1168 +	return (g_probable_mtu[(sizeof(g_probable_mtu) / 
  1.1169 +		sizeof(g_probable_mtu[0])) - 1]);
  1.1170 +    }
  1.1171 +
  1.1172 +static unsigned int 
  1.1173 +dtls1_guess_mtu(unsigned int curr_mtu)
  1.1174 +	{
  1.1175 +	size_t i;
  1.1176 +
  1.1177 +	if ( curr_mtu == 0 )
  1.1178 +		return g_probable_mtu[0] ;
  1.1179 +
  1.1180 +	for ( i = 0; i < sizeof(g_probable_mtu)/sizeof(g_probable_mtu[0]); i++)
  1.1181 +		if ( curr_mtu > g_probable_mtu[i])
  1.1182 +			return g_probable_mtu[i];
  1.1183 +	
  1.1184 +	return curr_mtu;
  1.1185 +	}
  1.1186 +
  1.1187 +void
  1.1188 +dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr)
  1.1189 +    {
  1.1190 +    memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
  1.1191 +    msg_hdr->type = *(data++);
  1.1192 +    n2l3(data, msg_hdr->msg_len);
  1.1193 +    
  1.1194 +    n2s(data, msg_hdr->seq);
  1.1195 +    n2l3(data, msg_hdr->frag_off);
  1.1196 +    n2l3(data, msg_hdr->frag_len);
  1.1197 +    }
  1.1198 +
  1.1199 +void
  1.1200 +dtls1_get_ccs_header(unsigned char *data, struct ccs_header_st *ccs_hdr)
  1.1201 +    {
  1.1202 +    memset(ccs_hdr, 0x00, sizeof(struct ccs_header_st));
  1.1203 +    
  1.1204 +    ccs_hdr->type = *(data++);
  1.1205 +}