a5439d544fbeb98bda1436680c3e235e46e0b292
[openssl.git] / ssl / d1_pkt.c
1 /* ssl/d1_pkt.c */
2 /* 
3  * DTLS implementation written by Nagendra Modadugu
4  * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.  
5  */
6 /* ====================================================================
7  * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer. 
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    openssl-core@openssl.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
60  * All rights reserved.
61  *
62  * This package is an SSL implementation written
63  * by Eric Young (eay@cryptsoft.com).
64  * The implementation was written so as to conform with Netscapes SSL.
65  * 
66  * This library is free for commercial and non-commercial use as long as
67  * the following conditions are aheared to.  The following conditions
68  * apply to all code found in this distribution, be it the RC4, RSA,
69  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
70  * included with this distribution is covered by the same copyright terms
71  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
72  * 
73  * Copyright remains Eric Young's, and as such any Copyright notices in
74  * the code are not to be removed.
75  * If this package is used in a product, Eric Young should be given attribution
76  * as the author of the parts of the library used.
77  * This can be in the form of a textual message at program startup or
78  * in documentation (online or textual) provided with the package.
79  * 
80  * Redistribution and use in source and binary forms, with or without
81  * modification, are permitted provided that the following conditions
82  * are met:
83  * 1. Redistributions of source code must retain the copyright
84  *    notice, this list of conditions and the following disclaimer.
85  * 2. Redistributions in binary form must reproduce the above copyright
86  *    notice, this list of conditions and the following disclaimer in the
87  *    documentation and/or other materials provided with the distribution.
88  * 3. All advertising materials mentioning features or use of this software
89  *    must display the following acknowledgement:
90  *    "This product includes cryptographic software written by
91  *     Eric Young (eay@cryptsoft.com)"
92  *    The word 'cryptographic' can be left out if the rouines from the library
93  *    being used are not cryptographic related :-).
94  * 4. If you include any Windows specific code (or a derivative thereof) from 
95  *    the apps directory (application code) you must include an acknowledgement:
96  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
97  * 
98  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
99  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
100  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
101  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
102  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
103  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
104  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
105  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
106  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
107  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
108  * SUCH DAMAGE.
109  * 
110  * The licence and distribution terms for any publically available version or
111  * derivative of this code cannot be changed.  i.e. this code cannot simply be
112  * copied and put under another distribution licence
113  * [including the GNU Public Licence.]
114  */
115
116 #include <stdio.h>
117 #include <errno.h>
118 #define USE_SOCKETS
119 #include "ssl_locl.h"
120 #include <openssl/evp.h>
121 #include <openssl/buffer.h>
122 #include <openssl/pqueue.h>
123 #include <openssl/rand.h>
124
125 /* mod 128 saturating subtract of two 64-bit values in big-endian order */
126 static int satsub64be(const unsigned char *v1,const unsigned char *v2)
127 {       int ret,sat,brw,i;
128
129         if (sizeof(long) == 8) do
130         {       const union { long one; char little; } is_endian = {1};
131                 long l;
132
133                 if (is_endian.little)                   break;
134                 /* not reached on little-endians */
135                 /* following test is redundant, because input is
136                  * always aligned, but I take no chances... */
137                 if (((size_t)v1|(size_t)v2)&0x7)        break;
138
139                 l  = *((long *)v1);
140                 l -= *((long *)v2);
141                 if (l>128)              return 128;
142                 else if (l<-128)        return -128;
143                 else                    return (int)l;
144         } while (0);
145
146         ret = (int)v1[7]-(int)v2[7];
147         sat = 0;
148         brw = ret>>8;   /* brw is either 0 or -1 */
149         if (ret & 0x80)
150         {       for (i=6;i>=0;i--)
151                 {       brw += (int)v1[i]-(int)v2[i];
152                         sat |= ~brw;
153                         brw >>= 8;
154                 }
155         }
156         else
157         {       for (i=6;i>=0;i--)
158                 {       brw += (int)v1[i]-(int)v2[i];
159                         sat |= brw;
160                         brw >>= 8;
161                 }
162         }
163         brw <<= 8;      /* brw is either 0 or -256 */
164
165         if (sat&0xff)   return brw | 0x80;
166         else            return brw + (ret&0xFF);
167 }
168
169 static int have_handshake_fragment(SSL *s, int type, unsigned char *buf, 
170         int len, int peek);
171 static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap);
172 static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
173 static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, 
174     unsigned int *is_next_epoch);
175 #if 0
176 static int dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr,
177         unsigned short *priority, unsigned long *offset);
178 #endif
179 static int dtls1_buffer_record(SSL *s, record_pqueue *q,
180         unsigned char *priority);
181 static int dtls1_process_record(SSL *s);
182 static void dtls1_clear_timeouts(SSL *s);
183
184 /* copy buffered record into SSL structure */
185 static int
186 dtls1_copy_record(SSL *s, pitem *item)
187     {
188     DTLS1_RECORD_DATA *rdata;
189
190     rdata = (DTLS1_RECORD_DATA *)item->data;
191     
192     if (s->s3->rbuf.buf != NULL)
193         OPENSSL_free(s->s3->rbuf.buf);
194     
195     s->packet = rdata->packet;
196     s->packet_length = rdata->packet_length;
197     memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
198     memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
199         
200         /* Set proper sequence number for mac calculation */
201         memcpy(&(s->s3->read_sequence[2]), &(rdata->packet[5]), 6);
202     
203     return(1);
204     }
205
206
207 static int
208 dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
209         {
210         DTLS1_RECORD_DATA *rdata;
211         pitem *item;
212
213         /* Limit the size of the queue to prevent DOS attacks */
214         if (pqueue_size(queue->q) >= 100)
215                 return 0;
216                 
217         rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA));
218         item = pitem_new(priority, rdata);
219         if (rdata == NULL || item == NULL)
220                 {
221                 if (rdata != NULL) OPENSSL_free(rdata);
222                 if (item != NULL) pitem_free(item);
223                 
224                 SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
225                 return(0);
226                 }
227         
228         rdata->packet = s->packet;
229         rdata->packet_length = s->packet_length;
230         memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER));
231         memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD));
232
233         item->data = rdata;
234
235         /* insert should not fail, since duplicates are dropped */
236         if (pqueue_insert(queue->q, item) == NULL)
237                 {
238                 OPENSSL_free(rdata);
239                 pitem_free(item);
240                 return(0);
241                 }
242
243         s->packet = NULL;
244         s->packet_length = 0;
245         memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER));
246         memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD));
247         
248         if (!ssl3_setup_buffers(s))
249                 {
250                 SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
251                 OPENSSL_free(rdata);
252                 pitem_free(item);
253                 return(0);
254                 }
255         
256         return(1);
257         }
258
259
260 static int
261 dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
262     {
263     pitem *item;
264
265     item = pqueue_pop(queue->q);
266     if (item)
267         {
268         dtls1_copy_record(s, item);
269
270         OPENSSL_free(item->data);
271                 pitem_free(item);
272
273         return(1);
274         }
275
276     return(0);
277     }
278
279
280 /* retrieve a buffered record that belongs to the new epoch, i.e., not processed 
281  * yet */
282 #define dtls1_get_unprocessed_record(s) \
283                    dtls1_retrieve_buffered_record((s), \
284                    &((s)->d1->unprocessed_rcds))
285
286 /* retrieve a buffered record that belongs to the current epoch, ie, processed */
287 #define dtls1_get_processed_record(s) \
288                    dtls1_retrieve_buffered_record((s), \
289                    &((s)->d1->processed_rcds))
290
291 static int
292 dtls1_process_buffered_records(SSL *s)
293     {
294     pitem *item;
295     
296     item = pqueue_peek(s->d1->unprocessed_rcds.q);
297     if (item)
298         {
299         DTLS1_RECORD_DATA *rdata;
300         rdata = (DTLS1_RECORD_DATA *)item->data;
301         
302         /* Check if epoch is current. */
303         if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch)
304             return(1);  /* Nothing to do. */
305         
306         /* Process all the records. */
307         while (pqueue_peek(s->d1->unprocessed_rcds.q))
308             {
309             dtls1_get_unprocessed_record(s);
310             if ( ! dtls1_process_record(s))
311                 return(0);
312             dtls1_buffer_record(s, &(s->d1->processed_rcds), 
313                 s->s3->rrec.seq_num);
314             }
315         }
316
317     /* sync epoch numbers once all the unprocessed records 
318      * have been processed */
319     s->d1->processed_rcds.epoch = s->d1->r_epoch;
320     s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1;
321
322     return(1);
323     }
324
325
326 #if 0
327
328 static int
329 dtls1_get_buffered_record(SSL *s)
330         {
331         pitem *item;
332         PQ_64BIT priority = 
333                 (((PQ_64BIT)s->d1->handshake_read_seq) << 32) | 
334                 ((PQ_64BIT)s->d1->r_msg_hdr.frag_off);
335         
336         if ( ! SSL_in_init(s))  /* if we're not (re)negotiating, 
337                                                            nothing buffered */
338                 return 0;
339
340
341         item = pqueue_peek(s->d1->rcvd_records);
342         if (item && item->priority == priority)
343                 {
344                 /* Check if we've received the record of interest.  It must be
345                  * a handshake record, since data records as passed up without
346                  * buffering */
347                 DTLS1_RECORD_DATA *rdata;
348                 item = pqueue_pop(s->d1->rcvd_records);
349                 rdata = (DTLS1_RECORD_DATA *)item->data;
350                 
351                 if (s->s3->rbuf.buf != NULL)
352                         OPENSSL_free(s->s3->rbuf.buf);
353                 
354                 s->packet = rdata->packet;
355                 s->packet_length = rdata->packet_length;
356                 memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
357                 memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
358                 
359                 OPENSSL_free(item->data);
360                 pitem_free(item);
361                 
362                 /* s->d1->next_expected_seq_num++; */
363                 return(1);
364                 }
365         
366         return 0;
367         }
368
369 #endif
370
371 static int
372 dtls1_process_record(SSL *s)
373 {
374         int i,al;
375         int clear=0;
376         int enc_err;
377         SSL_SESSION *sess;
378         SSL3_RECORD *rr;
379         unsigned int mac_size;
380         unsigned char md[EVP_MAX_MD_SIZE];
381
382
383         rr= &(s->s3->rrec);
384         sess = s->session;
385
386         /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
387          * and we have that many bytes in s->packet
388          */
389         rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]);
390
391         /* ok, we can now read from 's->packet' data into 'rr'
392          * rr->input points at rr->length bytes, which
393          * need to be copied into rr->data by either
394          * the decryption or by the decompression
395          * When the data is 'copied' into the rr->data buffer,
396          * rr->input will be pointed at the new buffer */ 
397
398         /* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
399          * rr->length bytes of encrypted compressed stuff. */
400
401         /* check is not needed I believe */
402         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
403                 {
404                 al=SSL_AD_RECORD_OVERFLOW;
405                 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
406                 goto f_err;
407                 }
408
409         /* decrypt in place in 'rr->input' */
410         rr->data=rr->input;
411
412         enc_err = s->method->ssl3_enc->enc(s,0);
413         if (enc_err <= 0)
414                 {
415                 if (enc_err == 0)
416                         /* SSLerr() and ssl3_send_alert() have been called */
417                         goto err;
418
419                 /* otherwise enc_err == -1 */
420                 goto err;
421                 }
422
423 #ifdef TLS_DEBUG
424 printf("dec %d\n",rr->length);
425 { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); }
426 printf("\n");
427 #endif
428
429         /* r->length is now the compressed data plus mac */
430         if (    (sess == NULL) ||
431                 (s->enc_read_ctx == NULL) ||
432                 (s->read_hash == NULL))
433                 clear=1;
434
435         if (!clear)
436                 {
437                 /* !clear => s->read_hash != NULL => mac_size != -1 */
438                 int t;
439                 t=EVP_MD_CTX_size(s->read_hash);
440                 OPENSSL_assert(t >= 0);
441                 mac_size=t;
442
443                 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size)
444                         {
445 #if 0 /* OK only for stream ciphers (then rr->length is visible from ciphertext anyway) */
446                         al=SSL_AD_RECORD_OVERFLOW;
447                         SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_PRE_MAC_LENGTH_TOO_LONG);
448                         goto f_err;
449 #else
450                         goto err;
451 #endif                  
452                         }
453                 /* check the MAC for rr->input (it's in mac_size bytes at the tail) */
454                 if (rr->length < mac_size)
455                         {
456 #if 0 /* OK only for stream ciphers */
457                         al=SSL_AD_DECODE_ERROR;
458                         SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT);
459                         goto f_err;
460 #else
461                         goto err;
462 #endif
463                         }
464                 rr->length-=mac_size;
465                 i=s->method->ssl3_enc->mac(s,md,0);
466                 if (i < 0 || memcmp(md,&(rr->data[rr->length]),mac_size) != 0)
467                         {
468                         goto err;
469                         }
470                 }
471
472         /* r->length is now just compressed */
473         if (s->expand != NULL)
474                 {
475                 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH)
476                         {
477                         al=SSL_AD_RECORD_OVERFLOW;
478                         SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG);
479                         goto f_err;
480                         }
481                 if (!ssl3_do_uncompress(s))
482                         {
483                         al=SSL_AD_DECOMPRESSION_FAILURE;
484                         SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION);
485                         goto f_err;
486                         }
487                 }
488
489         if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH)
490                 {
491                 al=SSL_AD_RECORD_OVERFLOW;
492                 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG);
493                 goto f_err;
494                 }
495
496         rr->off=0;
497         /* So at this point the following is true
498          * ssl->s3->rrec.type   is the type of record
499          * ssl->s3->rrec.length == number of bytes in record
500          * ssl->s3->rrec.off    == offset to first valid byte
501          * ssl->s3->rrec.data   == where to take bytes from, increment
502          *                         after use :-).
503          */
504
505         /* we have pulled in a full packet so zero things */
506         s->packet_length=0;
507         dtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */
508         return(1);
509
510 f_err:
511         ssl3_send_alert(s,SSL3_AL_FATAL,al);
512 err:
513         return(0);
514 }
515
516
517 /* Call this to get a new input record.
518  * It will return <= 0 if more data is needed, normally due to an error
519  * or non-blocking IO.
520  * When it finishes, one packet has been decoded and can be found in
521  * ssl->s3->rrec.type    - is the type of record
522  * ssl->s3->rrec.data,   - data
523  * ssl->s3->rrec.length, - number of bytes
524  */
525 /* used only by dtls1_read_bytes */
526 int dtls1_get_record(SSL *s)
527         {
528         int ssl_major,ssl_minor;
529         int i,n;
530         SSL3_RECORD *rr;
531         SSL_SESSION *sess;
532         unsigned char *p = NULL;
533         unsigned short version;
534         DTLS1_BITMAP *bitmap;
535         unsigned int is_next_epoch;
536
537         rr= &(s->s3->rrec);
538         sess=s->session;
539
540         /* The epoch may have changed.  If so, process all the
541          * pending records.  This is a non-blocking operation. */
542         dtls1_process_buffered_records(s);
543
544         /* if we're renegotiating, then there may be buffered records */
545         if (dtls1_get_processed_record(s))
546                 return 1;
547
548         /* get something from the wire */
549 again:
550         /* check if we have the header */
551         if (    (s->rstate != SSL_ST_READ_BODY) ||
552                 (s->packet_length < DTLS1_RT_HEADER_LENGTH)) 
553                 {
554                 n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
555                 /* read timeout is handled by dtls1_read_bytes */
556                 if (n <= 0) return(n); /* error or non-blocking */
557
558                 /* this packet contained a partial record, dump it */
559                 if (s->packet_length != DTLS1_RT_HEADER_LENGTH)
560                         {
561                         s->packet_length = 0;
562                         goto again;
563                         }
564
565                 s->rstate=SSL_ST_READ_BODY;
566
567                 p=s->packet;
568
569                 /* Pull apart the header into the DTLS1_RECORD */
570                 rr->type= *(p++);
571                 ssl_major= *(p++);
572                 ssl_minor= *(p++);
573                 version=(ssl_major<<8)|ssl_minor;
574
575                 /* sequence number is 64 bits, with top 2 bytes = epoch */ 
576                 n2s(p,rr->epoch);
577
578                 memcpy(&(s->s3->read_sequence[2]), p, 6);
579                 p+=6;
580
581                 n2s(p,rr->length);
582
583                 /* Lets check version */
584                 if (!s->first_packet)
585                         {
586                         if (version != s->version)
587                                 {
588                                 /* unexpected version, silently discard */
589                                 rr->length = 0;
590                                 s->packet_length = 0;
591                                 goto again;
592                                 }
593                         }
594
595                 if ((version & 0xff00) != (s->version & 0xff00))
596                         {
597                         /* wrong version, silently discard record */
598                         rr->length = 0;
599                         s->packet_length = 0;
600                         goto again;
601                         }
602
603                 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
604                         {
605                         /* record too long, silently discard it */
606                         rr->length = 0;
607                         s->packet_length = 0;
608                         goto again;
609                         }
610
611                 /* now s->rstate == SSL_ST_READ_BODY */
612                 }
613
614         /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
615
616         if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
617                 {
618                 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
619                 i=rr->length;
620                 n=ssl3_read_n(s,i,i,1);
621                 if (n <= 0) return(n); /* error or non-blocking io */
622
623                 /* this packet contained a partial record, dump it */
624                 if ( n != i)
625                         {
626                         rr->length = 0;
627                         s->packet_length = 0;
628                         goto again;
629                         }
630
631                 /* now n == rr->length,
632                  * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
633                 }
634         s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
635
636         /* match epochs.  NULL means the packet is dropped on the floor */
637         bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
638         if ( bitmap == NULL)
639                 {
640                 rr->length = 0;
641                 s->packet_length = 0;  /* dump this record */
642                 goto again;   /* get another record */
643                 }
644
645         /* Check whether this is a repeat, or aged record.
646          * Don't check if we're listening and this message is
647          * a ClientHello. They can look as if they're replayed,
648          * since they arrive from different connections and
649          * would be dropped unnecessarily.
650          */
651         if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
652                 *p == SSL3_MT_CLIENT_HELLO) &&
653                 !dtls1_record_replay_check(s, bitmap))
654                 {
655                 rr->length = 0;
656                 s->packet_length=0; /* dump this record */
657                 goto again;     /* get another record */
658                 }
659
660         /* just read a 0 length packet */
661         if (rr->length == 0) goto again;
662
663         /* If this record is from the next epoch (either HM or ALERT),
664          * and a handshake is currently in progress, buffer it since it
665          * cannot be processed at this time. */
666         if (is_next_epoch)
667                 {
668                 if (SSL_in_init(s) || s->in_handshake)
669                         {
670                         dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
671                         }
672                 rr->length = 0;
673                 s->packet_length = 0;
674                 goto again;
675                 }
676
677         if (!dtls1_process_record(s))
678                 {
679                 rr->length = 0;
680                 s->packet_length = 0;  /* dump this record */
681                 goto again;   /* get another record */
682                 }
683
684         dtls1_clear_timeouts(s);  /* done waiting */
685         return(1);
686
687         }
688
689 /* Return up to 'len' payload bytes received in 'type' records.
690  * 'type' is one of the following:
691  *
692  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
693  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
694  *   -  0 (during a shutdown, no data has to be returned)
695  *
696  * If we don't have stored data to work from, read a SSL/TLS record first
697  * (possibly multiple records if we still don't have anything to return).
698  *
699  * This function must handle any surprises the peer may have for us, such as
700  * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
701  * a surprise, but handled as if it were), or renegotiation requests.
702  * Also if record payloads contain fragments too small to process, we store
703  * them until there is enough for the respective protocol (the record protocol
704  * may use arbitrary fragmentation and even interleaving):
705  *     Change cipher spec protocol
706  *             just 1 byte needed, no need for keeping anything stored
707  *     Alert protocol
708  *             2 bytes needed (AlertLevel, AlertDescription)
709  *     Handshake protocol
710  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
711  *             to detect unexpected Client Hello and Hello Request messages
712  *             here, anything else is handled by higher layers
713  *     Application data protocol
714  *             none of our business
715  */
716 int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
717         {
718         int al,i,j,ret;
719         unsigned int n;
720         SSL3_RECORD *rr;
721         void (*cb)(const SSL *ssl,int type2,int val)=NULL;
722
723         if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
724                 if (!ssl3_setup_buffers(s))
725                         return(-1);
726
727     /* XXX: check what the second '&& type' is about */
728         if ((type && (type != SSL3_RT_APPLICATION_DATA) && 
729                 (type != SSL3_RT_HANDSHAKE) && type) ||
730             (peek && (type != SSL3_RT_APPLICATION_DATA)))
731                 {
732                 SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
733                 return -1;
734                 }
735
736         /* check whether there's a handshake message (client hello?) waiting */
737         if ( (ret = have_handshake_fragment(s, type, buf, len, peek)))
738                 return ret;
739
740         /* Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
741
742         if (!s->in_handshake && SSL_in_init(s))
743                 {
744                 /* type == SSL3_RT_APPLICATION_DATA */
745                 i=s->handshake_func(s);
746                 if (i < 0) return(i);
747                 if (i == 0)
748                         {
749                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
750                         return(-1);
751                         }
752                 }
753
754 start:
755         s->rwstate=SSL_NOTHING;
756
757         /* s->s3->rrec.type         - is the type of record
758          * s->s3->rrec.data,    - data
759          * s->s3->rrec.off,     - offset into 'data' for next read
760          * s->s3->rrec.length,  - number of bytes. */
761         rr = &(s->s3->rrec);
762
763         /* We are not handshaking and have no data yet,
764          * so process data buffered during the last handshake
765          * in advance, if any.
766          */
767         if (s->state == SSL_ST_OK && rr->length == 0)
768                 {
769                 pitem *item;
770                 item = pqueue_pop(s->d1->buffered_app_data.q);
771                 if (item)
772                         {
773                         dtls1_copy_record(s, item);
774
775                         OPENSSL_free(item->data);
776                         pitem_free(item);
777                         }
778                 }
779
780         /* Check for timeout */
781         if (dtls1_handle_timeout(s) > 0)
782                 goto start;
783
784         /* get new packet if necessary */
785         if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
786                 {
787                 ret=dtls1_get_record(s);
788                 if (ret <= 0) 
789                         {
790                         ret = dtls1_read_failed(s, ret);
791                         /* anything other than a timeout is an error */
792                         if (ret <= 0)  
793                                 return(ret);
794                         else
795                                 goto start;
796                         }
797                 }
798
799         /* we now have a packet which can be read and processed */
800
801         if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
802                                        * reset by ssl3_get_finished */
803                 && (rr->type != SSL3_RT_HANDSHAKE))
804                 {
805                 /* We now have application data between CCS and Finished.
806                  * Most likely the packets were reordered on their way, so
807                  * buffer the application data for later processing rather
808                  * than dropping the connection.
809                  */
810                 dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num);
811                 rr->length = 0;
812                 goto start;
813                 }
814
815         /* If the other end has shut down, throw anything we read away
816          * (even in 'peek' mode) */
817         if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
818                 {
819                 rr->length=0;
820                 s->rwstate=SSL_NOTHING;
821                 return(0);
822                 }
823
824
825         if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
826                 {
827                 /* make sure that we are not getting application data when we
828                  * are doing a handshake for the first time */
829                 if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
830                         (s->enc_read_ctx == NULL))
831                         {
832                         al=SSL_AD_UNEXPECTED_MESSAGE;
833                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE);
834                         goto f_err;
835                         }
836
837                 if (len <= 0) return(len);
838
839                 if ((unsigned int)len > rr->length)
840                         n = rr->length;
841                 else
842                         n = (unsigned int)len;
843
844                 memcpy(buf,&(rr->data[rr->off]),n);
845                 if (!peek)
846                         {
847                         rr->length-=n;
848                         rr->off+=n;
849                         if (rr->length == 0)
850                                 {
851                                 s->rstate=SSL_ST_READ_HEADER;
852                                 rr->off=0;
853                                 }
854                         }
855                 return(n);
856                 }
857
858
859         /* If we get here, then type != rr->type; if we have a handshake
860          * message, then it was unexpected (Hello Request or Client Hello). */
861
862         /* In case of record types for which we have 'fragment' storage,
863          * fill that so that we can process the data at a fixed place.
864          */
865                 {
866                 unsigned int k, dest_maxlen = 0;
867                 unsigned char *dest = NULL;
868                 unsigned int *dest_len = NULL;
869
870                 if (rr->type == SSL3_RT_HANDSHAKE)
871                         {
872                         dest_maxlen = sizeof s->d1->handshake_fragment;
873                         dest = s->d1->handshake_fragment;
874                         dest_len = &s->d1->handshake_fragment_len;
875                         }
876                 else if (rr->type == SSL3_RT_ALERT)
877                         {
878                         dest_maxlen = sizeof(s->d1->alert_fragment);
879                         dest = s->d1->alert_fragment;
880                         dest_len = &s->d1->alert_fragment_len;
881                         }
882                 /* else it's a CCS message, or application data or wrong */
883                 else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC)
884                         {
885                         /* Application data while renegotiating
886                          * is allowed. Try again reading.
887                          */
888                         if (rr->type == SSL3_RT_APPLICATION_DATA)
889                                 {
890                                 BIO *bio;
891                                 s->s3->in_read_app_data=2;
892                                 bio=SSL_get_rbio(s);
893                                 s->rwstate=SSL_READING;
894                                 BIO_clear_retry_flags(bio);
895                                 BIO_set_retry_read(bio);
896                                 return(-1);
897                                 }
898
899                         /* Not certain if this is the right error handling */
900                         al=SSL_AD_UNEXPECTED_MESSAGE;
901                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
902                         goto f_err;
903                         }
904
905                 if (dest_maxlen > 0)
906                         {
907             /* XDTLS:  In a pathalogical case, the Client Hello
908              *  may be fragmented--don't always expect dest_maxlen bytes */
909                         if ( rr->length < dest_maxlen)
910                                 {
911 #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
912                                 /*
913                                  * for normal alerts rr->length is 2, while
914                                  * dest_maxlen is 7 if we were to handle this
915                                  * non-existing alert...
916                                  */
917                                 FIX ME
918 #endif
919                                 s->rstate=SSL_ST_READ_HEADER;
920                                 rr->length = 0;
921                                 goto start;
922                                 }
923
924                         /* now move 'n' bytes: */
925                         for ( k = 0; k < dest_maxlen; k++)
926                                 {
927                                 dest[k] = rr->data[rr->off++];
928                                 rr->length--;
929                                 }
930                         *dest_len = dest_maxlen;
931                         }
932                 }
933
934         /* s->d1->handshake_fragment_len == 12  iff  rr->type == SSL3_RT_HANDSHAKE;
935          * s->d1->alert_fragment_len == 7      iff  rr->type == SSL3_RT_ALERT.
936          * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
937
938         /* If we are a client, check for an incoming 'Hello Request': */
939         if ((!s->server) &&
940                 (s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
941                 (s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
942                 (s->session != NULL) && (s->session->cipher != NULL))
943                 {
944                 s->d1->handshake_fragment_len = 0;
945
946                 if ((s->d1->handshake_fragment[1] != 0) ||
947                         (s->d1->handshake_fragment[2] != 0) ||
948                         (s->d1->handshake_fragment[3] != 0))
949                         {
950                         al=SSL_AD_DECODE_ERROR;
951                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_HELLO_REQUEST);
952                         goto err;
953                         }
954
955                 /* no need to check sequence number on HELLO REQUEST messages */
956
957                 if (s->msg_callback)
958                         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, 
959                                 s->d1->handshake_fragment, 4, s, s->msg_callback_arg);
960
961                 if (SSL_is_init_finished(s) &&
962                         !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
963                         !s->s3->renegotiate)
964                         {
965                         ssl3_renegotiate(s);
966                         if (ssl3_renegotiate_check(s))
967                                 {
968                                 i=s->handshake_func(s);
969                                 if (i < 0) return(i);
970                                 if (i == 0)
971                                         {
972                                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
973                                         return(-1);
974                                         }
975
976                                 if (!(s->mode & SSL_MODE_AUTO_RETRY))
977                                         {
978                                         if (s->s3->rbuf.left == 0) /* no read-ahead left? */
979                                                 {
980                                                 BIO *bio;
981                                                 /* In the case where we try to read application data,
982                                                  * but we trigger an SSL handshake, we return -1 with
983                                                  * the retry option set.  Otherwise renegotiation may
984                                                  * cause nasty problems in the blocking world */
985                                                 s->rwstate=SSL_READING;
986                                                 bio=SSL_get_rbio(s);
987                                                 BIO_clear_retry_flags(bio);
988                                                 BIO_set_retry_read(bio);
989                                                 return(-1);
990                                                 }
991                                         }
992                                 }
993                         }
994                 /* we either finished a handshake or ignored the request,
995                  * now try again to obtain the (application) data we were asked for */
996                 goto start;
997                 }
998
999         if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH)
1000                 {
1001                 int alert_level = s->d1->alert_fragment[0];
1002                 int alert_descr = s->d1->alert_fragment[1];
1003
1004                 s->d1->alert_fragment_len = 0;
1005
1006                 if (s->msg_callback)
1007                         s->msg_callback(0, s->version, SSL3_RT_ALERT, 
1008                                 s->d1->alert_fragment, 2, s, s->msg_callback_arg);
1009
1010                 if (s->info_callback != NULL)
1011                         cb=s->info_callback;
1012                 else if (s->ctx->info_callback != NULL)
1013                         cb=s->ctx->info_callback;
1014
1015                 if (cb != NULL)
1016                         {
1017                         j = (alert_level << 8) | alert_descr;
1018                         cb(s, SSL_CB_READ_ALERT, j);
1019                         }
1020
1021                 if (alert_level == 1) /* warning */
1022                         {
1023                         s->s3->warn_alert = alert_descr;
1024                         if (alert_descr == SSL_AD_CLOSE_NOTIFY)
1025                                 {
1026                                 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1027                                 return(0);
1028                                 }
1029 #if 0
1030             /* XXX: this is a possible improvement in the future */
1031                         /* now check if it's a missing record */
1032                         if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE)
1033                                 {
1034                                 unsigned short seq;
1035                                 unsigned int frag_off;
1036                                 unsigned char *p = &(s->d1->alert_fragment[2]);
1037
1038                                 n2s(p, seq);
1039                                 n2l3(p, frag_off);
1040
1041                                 dtls1_retransmit_message(s,
1042                                                                                  dtls1_get_queue_priority(frag->msg_header.seq, 0),
1043                                                                                  frag_off, &found);
1044                                 if ( ! found  && SSL_in_init(s))
1045                                         {
1046                                         /* fprintf( stderr,"in init = %d\n", SSL_in_init(s)); */
1047                                         /* requested a message not yet sent, 
1048                                            send an alert ourselves */
1049                                         ssl3_send_alert(s,SSL3_AL_WARNING,
1050                                                 DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
1051                                         }
1052                                 }
1053 #endif
1054                         }
1055                 else if (alert_level == 2) /* fatal */
1056                         {
1057                         char tmp[16];
1058
1059                         s->rwstate=SSL_NOTHING;
1060                         s->s3->fatal_alert = alert_descr;
1061                         SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
1062                         BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
1063                         ERR_add_error_data(2,"SSL alert number ",tmp);
1064                         s->shutdown|=SSL_RECEIVED_SHUTDOWN;
1065                         SSL_CTX_remove_session(s->ctx,s->session);
1066                         return(0);
1067                         }
1068                 else
1069                         {
1070                         al=SSL_AD_ILLEGAL_PARAMETER;
1071                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE);
1072                         goto f_err;
1073                         }
1074
1075                 goto start;
1076                 }
1077
1078         if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
1079                 {
1080                 s->rwstate=SSL_NOTHING;
1081                 rr->length=0;
1082                 return(0);
1083                 }
1084
1085         if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
1086                 {
1087                 struct ccs_header_st ccs_hdr;
1088                 unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH;
1089
1090                 dtls1_get_ccs_header(rr->data, &ccs_hdr);
1091
1092                 if (s->version == DTLS1_BAD_VER)
1093                         ccs_hdr_len = 3;
1094
1095                 /* 'Change Cipher Spec' is just a single byte, so we know
1096                  * exactly what the record payload has to look like */
1097                 /* XDTLS: check that epoch is consistent */
1098                 if (    (rr->length != ccs_hdr_len) || 
1099                         (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS))
1100                         {
1101                         i=SSL_AD_ILLEGAL_PARAMETER;
1102                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC);
1103                         goto err;
1104                         }
1105
1106                 rr->length=0;
1107
1108                 if (s->msg_callback)
1109                         s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, 
1110                                 rr->data, 1, s, s->msg_callback_arg);
1111
1112                 /* We can't process a CCS now, because previous handshake
1113                  * messages are still missing, so just drop it.
1114                  */
1115                 if (!s->d1->change_cipher_spec_ok)
1116                         {
1117                         goto start;
1118                         }
1119
1120                 s->d1->change_cipher_spec_ok = 0;
1121
1122                 s->s3->change_cipher_spec=1;
1123                 if (!ssl3_do_change_cipher_spec(s))
1124                         goto err;
1125
1126                 /* do this whenever CCS is processed */
1127                 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
1128
1129                 if (s->version == DTLS1_BAD_VER)
1130                         s->d1->handshake_read_seq++;
1131
1132                 goto start;
1133                 }
1134
1135         /* Unexpected handshake message (Client Hello, or protocol violation) */
1136         if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && 
1137                 !s->in_handshake)
1138                 {
1139                 struct hm_header_st msg_hdr;
1140                 
1141                 /* this may just be a stale retransmit */
1142                 dtls1_get_message_header(rr->data, &msg_hdr);
1143                 if( rr->epoch != s->d1->r_epoch)
1144                         {
1145                         rr->length = 0;
1146                         goto start;
1147                         }
1148
1149                 /* If we are server, we may have a repeated FINISHED of the
1150                  * client here, then retransmit our CCS and FINISHED.
1151                  */
1152                 if (msg_hdr.type == SSL3_MT_FINISHED)
1153                         {
1154                         dtls1_retransmit_buffered_messages(s);
1155                         rr->length = 0;
1156                         goto start;
1157                         }
1158
1159                 if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
1160                         !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
1161                         {
1162 #if 0 /* worked only because C operator preferences are not as expected (and
1163        * because this is not really needed for clients except for detecting
1164        * protocol violations): */
1165                         s->state=SSL_ST_BEFORE|(s->server)
1166                                 ?SSL_ST_ACCEPT
1167                                 :SSL_ST_CONNECT;
1168 #else
1169                         s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
1170 #endif
1171                         s->new_session=1;
1172                         }
1173                 i=s->handshake_func(s);
1174                 if (i < 0) return(i);
1175                 if (i == 0)
1176                         {
1177                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
1178                         return(-1);
1179                         }
1180
1181                 if (!(s->mode & SSL_MODE_AUTO_RETRY))
1182                         {
1183                         if (s->s3->rbuf.left == 0) /* no read-ahead left? */
1184                                 {
1185                                 BIO *bio;
1186                                 /* In the case where we try to read application data,
1187                                  * but we trigger an SSL handshake, we return -1 with
1188                                  * the retry option set.  Otherwise renegotiation may
1189                                  * cause nasty problems in the blocking world */
1190                                 s->rwstate=SSL_READING;
1191                                 bio=SSL_get_rbio(s);
1192                                 BIO_clear_retry_flags(bio);
1193                                 BIO_set_retry_read(bio);
1194                                 return(-1);
1195                                 }
1196                         }
1197                 goto start;
1198                 }
1199
1200         switch (rr->type)
1201                 {
1202         default:
1203 #ifndef OPENSSL_NO_TLS
1204                 /* TLS just ignores unknown message types */
1205                 if (s->version == TLS1_VERSION)
1206                         {
1207                         rr->length = 0;
1208                         goto start;
1209                         }
1210 #endif
1211                 al=SSL_AD_UNEXPECTED_MESSAGE;
1212                 SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
1213                 goto f_err;
1214         case SSL3_RT_CHANGE_CIPHER_SPEC:
1215         case SSL3_RT_ALERT:
1216         case SSL3_RT_HANDSHAKE:
1217                 /* we already handled all of these, with the possible exception
1218                  * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
1219                  * should not happen when type != rr->type */
1220                 al=SSL_AD_UNEXPECTED_MESSAGE;
1221                 SSLerr(SSL_F_DTLS1_READ_BYTES,ERR_R_INTERNAL_ERROR);
1222                 goto f_err;
1223         case SSL3_RT_APPLICATION_DATA:
1224                 /* At this point, we were expecting handshake data,
1225                  * but have application data.  If the library was
1226                  * running inside ssl3_read() (i.e. in_read_app_data
1227                  * is set) and it makes sense to read application data
1228                  * at this point (session renegotiation not yet started),
1229                  * we will indulge it.
1230                  */
1231                 if (s->s3->in_read_app_data &&
1232                         (s->s3->total_renegotiations != 0) &&
1233                         ((
1234                                 (s->state & SSL_ST_CONNECT) &&
1235                                 (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1236                                 (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
1237                                 ) || (
1238                                         (s->state & SSL_ST_ACCEPT) &&
1239                                         (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
1240                                         (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
1241                                         )
1242                                 ))
1243                         {
1244                         s->s3->in_read_app_data=2;
1245                         return(-1);
1246                         }
1247                 else
1248                         {
1249                         al=SSL_AD_UNEXPECTED_MESSAGE;
1250                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
1251                         goto f_err;
1252                         }
1253                 }
1254         /* not reached */
1255
1256 f_err:
1257         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1258 err:
1259         return(-1);
1260         }
1261
1262 int
1263 dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
1264         {
1265         int i;
1266
1267         if (SSL_in_init(s) && !s->in_handshake)
1268                 {
1269                 i=s->handshake_func(s);
1270                 if (i < 0) return(i);
1271                 if (i == 0)
1272                         {
1273                         SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
1274                         return -1;
1275                         }
1276                 }
1277
1278         if (len > SSL3_RT_MAX_PLAIN_LENGTH)
1279                 {
1280                         SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,SSL_R_DTLS_MESSAGE_TOO_BIG);
1281                         return -1;
1282                 }
1283
1284         i = dtls1_write_bytes(s, type, buf_, len);
1285         return i;
1286         }
1287
1288
1289         /* this only happens when a client hello is received and a handshake 
1290          * is started. */
1291 static int
1292 have_handshake_fragment(SSL *s, int type, unsigned char *buf, 
1293         int len, int peek)
1294         {
1295         
1296         if ((type == SSL3_RT_HANDSHAKE) && (s->d1->handshake_fragment_len > 0))
1297                 /* (partially) satisfy request from storage */
1298                 {
1299                 unsigned char *src = s->d1->handshake_fragment;
1300                 unsigned char *dst = buf;
1301                 unsigned int k,n;
1302                 
1303                 /* peek == 0 */
1304                 n = 0;
1305                 while ((len > 0) && (s->d1->handshake_fragment_len > 0))
1306                         {
1307                         *dst++ = *src++;
1308                         len--; s->d1->handshake_fragment_len--;
1309                         n++;
1310                         }
1311                 /* move any remaining fragment bytes: */
1312                 for (k = 0; k < s->d1->handshake_fragment_len; k++)
1313                         s->d1->handshake_fragment[k] = *src++;
1314                 return n;
1315                 }
1316         
1317         return 0;
1318         }
1319
1320
1321
1322
1323 /* Call this to write data in records of type 'type'
1324  * It will return <= 0 if not all data has been sent or non-blocking IO.
1325  */
1326 int dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
1327         {
1328         int i;
1329
1330         OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
1331         s->rwstate=SSL_NOTHING;
1332         i=do_dtls1_write(s, type, buf, len, 0);
1333         return i;
1334         }
1335
1336 int do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len, int create_empty_fragment)
1337         {
1338         unsigned char *p,*pseq;
1339         int i,mac_size,clear=0;
1340         int prefix_len = 0;
1341         SSL3_RECORD *wr;
1342         SSL3_BUFFER *wb;
1343         SSL_SESSION *sess;
1344         int bs;
1345
1346         /* first check if there is a SSL3_BUFFER still being written
1347          * out.  This will happen with non blocking IO */
1348         if (s->s3->wbuf.left != 0)
1349                 {
1350                 OPENSSL_assert(0); /* XDTLS:  want to see if we ever get here */
1351                 return(ssl3_write_pending(s,type,buf,len));
1352                 }
1353
1354         /* If we have an alert to send, lets send it */
1355         if (s->s3->alert_dispatch)
1356                 {
1357                 i=s->method->ssl_dispatch_alert(s);
1358                 if (i <= 0)
1359                         return(i);
1360                 /* if it went, fall through and send more stuff */
1361                 }
1362
1363         if (len == 0 && !create_empty_fragment)
1364                 return 0;
1365
1366         wr= &(s->s3->wrec);
1367         wb= &(s->s3->wbuf);
1368         sess=s->session;
1369
1370         if (    (sess == NULL) ||
1371                 (s->enc_write_ctx == NULL) ||
1372                 (EVP_MD_CTX_md(s->write_hash) == NULL))
1373                 clear=1;
1374
1375         if (clear)
1376                 mac_size=0;
1377         else
1378                 {
1379                 mac_size=EVP_MD_CTX_size(s->write_hash);
1380                 if (mac_size < 0)
1381                         goto err;
1382                 }
1383
1384         /* DTLS implements explicit IV, so no need for empty fragments */
1385 #if 0
1386         /* 'create_empty_fragment' is true only when this function calls itself */
1387         if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done
1388             && SSL_version(s) != DTLS1_VERSION && SSL_version(s) != DTLS1_BAD_VER)
1389                 {
1390                 /* countermeasure against known-IV weakness in CBC ciphersuites
1391                  * (see http://www.openssl.org/~bodo/tls-cbc.txt) 
1392                  */
1393
1394                 if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA)
1395                         {
1396                         /* recursive function call with 'create_empty_fragment' set;
1397                          * this prepares and buffers the data for an empty fragment
1398                          * (these 'prefix_len' bytes are sent out later
1399                          * together with the actual payload) */
1400                         prefix_len = s->method->do_ssl_write(s, type, buf, 0, 1);
1401                         if (prefix_len <= 0)
1402                                 goto err;
1403
1404                         if (s->s3->wbuf.len < (size_t)prefix_len + SSL3_RT_MAX_PACKET_SIZE)
1405                                 {
1406                                 /* insufficient space */
1407                                 SSLerr(SSL_F_DO_DTLS1_WRITE, ERR_R_INTERNAL_ERROR);
1408                                 goto err;
1409                                 }
1410                         }
1411                 
1412                 s->s3->empty_fragment_done = 1;
1413                 }
1414 #endif
1415         p = wb->buf + prefix_len;
1416
1417         /* write the header */
1418
1419         *(p++)=type&0xff;
1420         wr->type=type;
1421
1422         *(p++)=(s->version>>8);
1423         *(p++)=s->version&0xff;
1424
1425         /* field where we are to write out packet epoch, seq num and len */
1426         pseq=p; 
1427         p+=10;
1428
1429         /* lets setup the record stuff. */
1430
1431         /* Make space for the explicit IV in case of CBC.
1432          * (this is a bit of a boundary violation, but what the heck).
1433          */
1434         if ( s->enc_write_ctx && 
1435                 (EVP_CIPHER_mode( s->enc_write_ctx->cipher ) & EVP_CIPH_CBC_MODE))
1436                 bs = EVP_CIPHER_block_size(s->enc_write_ctx->cipher);
1437         else
1438                 bs = 0;
1439
1440         wr->data=p + bs;  /* make room for IV in case of CBC */
1441         wr->length=(int)len;
1442         wr->input=(unsigned char *)buf;
1443
1444         /* we now 'read' from wr->input, wr->length bytes into
1445          * wr->data */
1446
1447         /* first we compress */
1448         if (s->compress != NULL)
1449                 {
1450                 if (!ssl3_do_compress(s))
1451                         {
1452                         SSLerr(SSL_F_DO_DTLS1_WRITE,SSL_R_COMPRESSION_FAILURE);
1453                         goto err;
1454                         }
1455                 }
1456         else
1457                 {
1458                 memcpy(wr->data,wr->input,wr->length);
1459                 wr->input=wr->data;
1460                 }
1461
1462         /* we should still have the output to wr->data and the input
1463          * from wr->input.  Length should be wr->length.
1464          * wr->data still points in the wb->buf */
1465
1466         if (mac_size != 0)
1467                 {
1468                 if(s->method->ssl3_enc->mac(s,&(p[wr->length + bs]),1) < 0)
1469                         goto err;
1470                 wr->length+=mac_size;
1471                 }
1472
1473         /* this is true regardless of mac size */
1474         wr->input=p;
1475         wr->data=p;
1476
1477
1478         /* ssl3_enc can only have an error on read */
1479         if (bs) /* bs != 0 in case of CBC */
1480                 {
1481                 RAND_pseudo_bytes(p,bs);
1482                 /* master IV and last CBC residue stand for
1483                  * the rest of randomness */
1484                 wr->length += bs;
1485                 }
1486
1487         s->method->ssl3_enc->enc(s,1);
1488
1489         /* record length after mac and block padding */
1490 /*      if (type == SSL3_RT_APPLICATION_DATA ||
1491         (type == SSL3_RT_ALERT && ! SSL_in_init(s))) */
1492         
1493         /* there's only one epoch between handshake and app data */
1494         
1495         s2n(s->d1->w_epoch, pseq);
1496
1497         /* XDTLS: ?? */
1498 /*      else
1499         s2n(s->d1->handshake_epoch, pseq); */
1500
1501         memcpy(pseq, &(s->s3->write_sequence[2]), 6);
1502         pseq+=6;
1503         s2n(wr->length,pseq);
1504
1505         /* we should now have
1506          * wr->data pointing to the encrypted data, which is
1507          * wr->length long */
1508         wr->type=type; /* not needed but helps for debugging */
1509         wr->length+=DTLS1_RT_HEADER_LENGTH;
1510
1511 #if 0  /* this is now done at the message layer */
1512         /* buffer the record, making it easy to handle retransmits */
1513         if ( type == SSL3_RT_HANDSHAKE || type == SSL3_RT_CHANGE_CIPHER_SPEC)
1514                 dtls1_buffer_record(s, wr->data, wr->length, 
1515                         *((PQ_64BIT *)&(s->s3->write_sequence[0])));
1516 #endif
1517
1518         ssl3_record_sequence_update(&(s->s3->write_sequence[0]));
1519
1520         if (create_empty_fragment)
1521                 {
1522                 /* we are in a recursive call;
1523                  * just return the length, don't write out anything here
1524                  */
1525                 return wr->length;
1526                 }
1527
1528         /* now let's set up wb */
1529         wb->left = prefix_len + wr->length;
1530         wb->offset = 0;
1531
1532         /* memorize arguments so that ssl3_write_pending can detect bad write retries later */
1533         s->s3->wpend_tot=len;
1534         s->s3->wpend_buf=buf;
1535         s->s3->wpend_type=type;
1536         s->s3->wpend_ret=len;
1537
1538         /* we now just need to write the buffer */
1539         return ssl3_write_pending(s,type,buf,len);
1540 err:
1541         return -1;
1542         }
1543
1544
1545
1546 static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap)
1547         {
1548         int cmp;
1549         unsigned int shift;
1550         const unsigned char *seq = s->s3->read_sequence;
1551
1552         cmp = satsub64be(seq,bitmap->max_seq_num);
1553         if (cmp > 0)
1554                 {
1555                 memcpy (s->s3->rrec.seq_num,seq,8);
1556                 return 1; /* this record in new */
1557                 }
1558         shift = -cmp;
1559         if (shift >= sizeof(bitmap->map)*8)
1560                 return 0; /* stale, outside the window */
1561         else if (bitmap->map & (1UL<<shift))
1562                 return 0; /* record previously received */
1563
1564         memcpy (s->s3->rrec.seq_num,seq,8);
1565         return 1;
1566         }
1567
1568
1569 static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap)
1570         {
1571         int cmp;
1572         unsigned int shift;
1573         const unsigned char *seq = s->s3->read_sequence;
1574
1575         cmp = satsub64be(seq,bitmap->max_seq_num);
1576         if (cmp > 0)
1577                 {
1578                 shift = cmp;
1579                 if (shift < sizeof(bitmap->map)*8)
1580                         bitmap->map <<= shift, bitmap->map |= 1UL;
1581                 else
1582                         bitmap->map = 1UL;
1583                 memcpy(bitmap->max_seq_num,seq,8);
1584                 }
1585         else    {
1586                 shift = -cmp;
1587                 if (shift < sizeof(bitmap->map)*8)
1588                         bitmap->map |= 1UL<<shift;
1589                 }
1590         }
1591
1592
1593 int dtls1_dispatch_alert(SSL *s)
1594         {
1595         int i,j;
1596         void (*cb)(const SSL *ssl,int type,int val)=NULL;
1597         unsigned char buf[DTLS1_AL_HEADER_LENGTH];
1598         unsigned char *ptr = &buf[0];
1599
1600         s->s3->alert_dispatch=0;
1601
1602         memset(buf, 0x00, sizeof(buf));
1603         *ptr++ = s->s3->send_alert[0];
1604         *ptr++ = s->s3->send_alert[1];
1605
1606 #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
1607         if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE)
1608                 {       
1609                 s2n(s->d1->handshake_read_seq, ptr);
1610 #if 0
1611                 if ( s->d1->r_msg_hdr.frag_off == 0)  /* waiting for a new msg */
1612
1613                 else
1614                         s2n(s->d1->r_msg_hdr.seq, ptr); /* partial msg read */
1615 #endif
1616
1617 #if 0
1618                 fprintf(stderr, "s->d1->handshake_read_seq = %d, s->d1->r_msg_hdr.seq = %d\n",s->d1->handshake_read_seq,s->d1->r_msg_hdr.seq);
1619 #endif
1620                 l2n3(s->d1->r_msg_hdr.frag_off, ptr);
1621                 }
1622 #endif
1623
1624         i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), 0);
1625         if (i <= 0)
1626                 {
1627                 s->s3->alert_dispatch=1;
1628                 /* fprintf( stderr, "not done with alert\n" ); */
1629                 }
1630         else
1631                 {
1632                 if (s->s3->send_alert[0] == SSL3_AL_FATAL
1633 #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
1634                     || s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
1635 #endif
1636                     )
1637                         (void)BIO_flush(s->wbio);
1638
1639                 if (s->msg_callback)
1640                         s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 
1641                                 2, s, s->msg_callback_arg);
1642
1643                 if (s->info_callback != NULL)
1644                         cb=s->info_callback;
1645                 else if (s->ctx->info_callback != NULL)
1646                         cb=s->ctx->info_callback;
1647
1648                 if (cb != NULL)
1649                         {
1650                         j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
1651                         cb(s,SSL_CB_WRITE_ALERT,j);
1652                         }
1653                 }
1654         return(i);
1655         }
1656
1657
1658 static DTLS1_BITMAP *
1659 dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, unsigned int *is_next_epoch)
1660     {
1661     
1662     *is_next_epoch = 0;
1663
1664     /* In current epoch, accept HM, CCS, DATA, & ALERT */
1665     if (rr->epoch == s->d1->r_epoch)
1666         return &s->d1->bitmap;
1667
1668     /* Only HM and ALERT messages can be from the next epoch */
1669     else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) &&
1670         (rr->type == SSL3_RT_HANDSHAKE ||
1671             rr->type == SSL3_RT_ALERT))
1672         {
1673         *is_next_epoch = 1;
1674         return &s->d1->next_bitmap;
1675         }
1676
1677     return NULL;
1678     }
1679
1680 #if 0
1681 static int
1682 dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr, unsigned short *priority,
1683         unsigned long *offset)
1684         {
1685
1686         /* alerts are passed up immediately */
1687         if ( rr->type == SSL3_RT_APPLICATION_DATA ||
1688                 rr->type == SSL3_RT_ALERT)
1689                 return 0;
1690
1691         /* Only need to buffer if a handshake is underway.
1692          * (this implies that Hello Request and Client Hello are passed up
1693          * immediately) */
1694         if ( SSL_in_init(s))
1695                 {
1696                 unsigned char *data = rr->data;
1697                 /* need to extract the HM/CCS sequence number here */
1698                 if ( rr->type == SSL3_RT_HANDSHAKE ||
1699                         rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
1700                         {
1701                         unsigned short seq_num;
1702                         struct hm_header_st msg_hdr;
1703                         struct ccs_header_st ccs_hdr;
1704
1705                         if ( rr->type == SSL3_RT_HANDSHAKE)
1706                                 {
1707                                 dtls1_get_message_header(data, &msg_hdr);
1708                                 seq_num = msg_hdr.seq;
1709                                 *offset = msg_hdr.frag_off;
1710                                 }
1711                         else
1712                                 {
1713                                 dtls1_get_ccs_header(data, &ccs_hdr);
1714                                 seq_num = ccs_hdr.seq;
1715                                 *offset = 0;
1716                                 }
1717                                 
1718                         /* this is either a record we're waiting for, or a
1719                          * retransmit of something we happened to previously 
1720                          * receive (higher layers will drop the repeat silently */
1721                         if ( seq_num < s->d1->handshake_read_seq)
1722                                 return 0;
1723                         if (rr->type == SSL3_RT_HANDSHAKE && 
1724                                 seq_num == s->d1->handshake_read_seq &&
1725                                 msg_hdr.frag_off < s->d1->r_msg_hdr.frag_off)
1726                                 return 0;
1727                         else if ( seq_num == s->d1->handshake_read_seq &&
1728                                 (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC ||
1729                                         msg_hdr.frag_off == s->d1->r_msg_hdr.frag_off))
1730                                 return 0;
1731                         else
1732                                 {
1733                                 *priority = seq_num;
1734                                 return 1;
1735                                 }
1736                         }
1737                 else /* unknown record type */
1738                         return 0;
1739                 }
1740
1741         return 0;
1742         }
1743 #endif
1744
1745 void
1746 dtls1_reset_seq_numbers(SSL *s, int rw)
1747         {
1748         unsigned char *seq;
1749         unsigned int seq_bytes = sizeof(s->s3->read_sequence);
1750
1751         if ( rw & SSL3_CC_READ)
1752                 {
1753                 seq = s->s3->read_sequence;
1754                 s->d1->r_epoch++;
1755                 memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
1756                 memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
1757                 }
1758         else
1759                 {
1760                 seq = s->s3->write_sequence;
1761                 memcpy(s->d1->last_write_sequence, seq, sizeof(s->s3->write_sequence));
1762                 s->d1->w_epoch++;
1763                 }
1764
1765         memset(seq, 0x00, seq_bytes);
1766         }
1767
1768
1769 static void
1770 dtls1_clear_timeouts(SSL *s)
1771         {
1772         memset(&(s->d1->timeout), 0x00, sizeof(struct dtls1_timeout_st));
1773         }