83f5cf56db91072b623b4c11ce30dadb195725ba
[openssl.git] / ssl / record / rec_layer_s3.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110
111 #include <stdio.h>
112 #include <limits.h>
113 #include <errno.h>
114 #define USE_SOCKETS
115 #include "../ssl_locl.h"
116 #include <openssl/evp.h>
117 #include <openssl/buffer.h>
118 #include <openssl/rand.h>
119 #include "record_locl.h"
120
121 #ifndef  EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
122 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
123 #endif
124
125 #if     defined(OPENSSL_SMALL_FOOTPRINT) || \
126         !(      defined(AES_ASM) &&     ( \
127                 defined(__x86_64)       || defined(__x86_64__)  || \
128                 defined(_M_AMD64)       || defined(_M_X64)      || \
129                 defined(__INTEL__)      ) \
130         )
131 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
132 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
133 #endif
134
135 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL *s)
136 {
137     rl->s = s;
138     SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
139     SSL3_RECORD_clear(&rl->wrec, 1);
140 }
141
142 void RECORD_LAYER_clear(RECORD_LAYER *rl)
143 {
144     unsigned int pipes;
145
146     rl->rstate = SSL_ST_READ_HEADER;
147
148     /* Do I need to clear read_ahead? As far as I can tell read_ahead did not
149      * previously get reset by SSL_clear...so I'll keep it that way..but is
150      * that right?
151      */
152
153     rl->packet = NULL;
154     rl->packet_length = 0;
155     rl->wnum = 0;
156     memset(rl->alert_fragment, 0, sizeof(rl->alert_fragment));
157     rl->alert_fragment_len = 0;
158     memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
159     rl->handshake_fragment_len = 0;
160     rl->wpend_tot = 0;
161     rl->wpend_type = 0;
162     rl->wpend_ret = 0;
163     rl->wpend_buf = NULL;
164
165     SSL3_BUFFER_clear(&rl->rbuf);
166     for(pipes = 0; pipes < rl->numwpipes; pipes++)
167         SSL3_BUFFER_clear(&rl->wbuf[pipes]);
168     rl->numwpipes = 0;
169     SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
170     SSL3_RECORD_clear(&rl->wrec, 1);
171
172     RECORD_LAYER_reset_read_sequence(rl);
173     RECORD_LAYER_reset_write_sequence(rl);
174     
175     if (rl->d)
176         DTLS_RECORD_LAYER_clear(rl);
177 }
178
179 void RECORD_LAYER_release(RECORD_LAYER *rl)
180 {
181     if (SSL3_BUFFER_is_initialised(&rl->rbuf))
182         ssl3_release_read_buffer(rl->s);
183     if (rl->numwpipes > 0)
184         ssl3_release_write_buffer(rl->s);
185     /* TODO: Check why there is no release of wrec here?? */
186     SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
187 }
188
189 int RECORD_LAYER_read_pending(RECORD_LAYER *rl)
190 {
191     return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
192 }
193
194 int RECORD_LAYER_write_pending(RECORD_LAYER *rl)
195 {
196     return (rl->numwpipes > 0)
197             && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes-1]) != 0;
198 }
199
200 int RECORD_LAYER_set_data(RECORD_LAYER *rl, const unsigned char *buf, int len)
201 {
202     rl->packet_length = len;
203     if (len != 0) {
204         rl->rstate = SSL_ST_READ_HEADER;
205         if (!SSL3_BUFFER_is_initialised(&rl->rbuf))
206             if (!ssl3_setup_read_buffer(rl->s))
207                 return 0;
208     }
209
210     rl->packet = SSL3_BUFFER_get_buf(&rl->rbuf);
211     SSL3_BUFFER_set_data(&rl->rbuf, buf, len);
212
213     return 1;
214 }
215
216 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
217 {
218     memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
219 }
220
221 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
222 {
223     memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
224 }
225
226 int ssl3_pending(const SSL *s)
227 {
228     unsigned int i;
229     int num = 0;
230
231     if (s->rlayer.rstate == SSL_ST_READ_BODY)
232         return 0;
233
234     for (i = 0; i < RECORD_LAYER_get_numrpipes(&s->rlayer); i++) {
235         if (SSL3_RECORD_get_type(&s->rlayer.rrec[i])
236                 != SSL3_RT_APPLICATION_DATA)
237             return 0;
238         num += SSL3_RECORD_get_length(&s->rlayer.rrec[i]);
239     }
240
241     return num;
242 }
243
244 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
245 {
246     ctx->default_read_buf_len = len;
247 }
248
249 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
250 {
251     SSL3_BUFFER_set_default_len(RECORD_LAYER_get_rbuf(&s->rlayer), len);
252 }
253
254 const char *SSL_rstate_string_long(const SSL *s)
255 {
256     const char *str;
257
258     switch (s->rlayer.rstate) {
259     case SSL_ST_READ_HEADER:
260         str = "read header";
261         break;
262     case SSL_ST_READ_BODY:
263         str = "read body";
264         break;
265     case SSL_ST_READ_DONE:
266         str = "read done";
267         break;
268     default:
269         str = "unknown";
270         break;
271     }
272     return (str);
273 }
274
275 const char *SSL_rstate_string(const SSL *s)
276 {
277     const char *str;
278
279     switch (s->rlayer.rstate) {
280     case SSL_ST_READ_HEADER:
281         str = "RH";
282         break;
283     case SSL_ST_READ_BODY:
284         str = "RB";
285         break;
286     case SSL_ST_READ_DONE:
287         str = "RD";
288         break;
289     default:
290         str = "unknown";
291         break;
292     }
293     return (str);
294 }
295
296 int ssl3_read_n(SSL *s, int n, int max, int extend, int clearold)
297 {
298     /*
299      * If extend == 0, obtain new n-byte packet; if extend == 1, increase
300      * packet by another n bytes. The packet will be in the sub-array of
301      * s->s3->rbuf.buf specified by s->packet and s->packet_length. (If
302      * s->rlayer.read_ahead is set, 'max' bytes may be stored in rbuf [plus
303      * s->packet_length bytes if extend == 1].)
304      * if clearold == 1, move the packet to the start of the buffer; if
305      * clearold == 0 then leave any old packets where they were
306      */
307     int i, len, left;
308     size_t align = 0;
309     unsigned char *pkt;
310     SSL3_BUFFER *rb;
311
312     if (n <= 0)
313         return n;
314
315     rb = &s->rlayer.rbuf;
316     if (rb->buf == NULL)
317         if (!ssl3_setup_read_buffer(s))
318             return -1;
319
320     left = rb->left;
321 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
322     align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
323     align = (0-align) & (SSL3_ALIGN_PAYLOAD - 1);
324 #endif
325
326     if (!extend) {
327         /* start with empty packet ... */
328         if (left == 0)
329             rb->offset = align;
330         else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
331             /*
332              * check if next packet length is large enough to justify payload
333              * alignment...
334              */
335             pkt = rb->buf + rb->offset;
336             if (pkt[0] == SSL3_RT_APPLICATION_DATA
337                 && (pkt[3] << 8 | pkt[4]) >= 128) {
338                 /*
339                  * Note that even if packet is corrupted and its length field
340                  * is insane, we can only be led to wrong decision about
341                  * whether memmove will occur or not. Header values has no
342                  * effect on memmove arguments and therefore no buffer
343                  * overrun can be triggered.
344                  */
345                 memmove(rb->buf + align, pkt, left);
346                 rb->offset = align;
347             }
348         }
349         s->rlayer.packet = rb->buf + rb->offset;
350         s->rlayer.packet_length = 0;
351         /* ... now we can act as if 'extend' was set */
352     }
353
354     /*
355      * For DTLS/UDP reads should not span multiple packets because the read
356      * operation returns the whole packet at once (as long as it fits into
357      * the buffer).
358      */
359     if (SSL_IS_DTLS(s)) {
360         if (left == 0 && extend)
361             return 0;
362         if (left > 0 && n > left)
363             n = left;
364     }
365
366     /* if there is enough in the buffer from a previous read, take some */
367     if (left >= n) {
368         s->rlayer.packet_length += n;
369         rb->left = left - n;
370         rb->offset += n;
371         return (n);
372     }
373
374     /* else we need to read more data */
375
376     len = s->rlayer.packet_length;
377     pkt = rb->buf + align;
378     /*
379      * Move any available bytes to front of buffer: 'len' bytes already
380      * pointed to by 'packet', 'left' extra ones at the end
381      */
382     if (s->rlayer.packet != pkt && clearold == 1) {     /* len > 0 */
383         memmove(pkt, s->rlayer.packet, len + left);
384         s->rlayer.packet = pkt;
385         rb->offset = len + align;
386     }
387
388     if (n > (int)(rb->len - rb->offset)) { /* does not happen */
389         SSLerr(SSL_F_SSL3_READ_N, ERR_R_INTERNAL_ERROR);
390         return -1;
391     }
392
393     /* We always act like read_ahead is set for DTLS */
394     if (!s->rlayer.read_ahead && !SSL_IS_DTLS(s))
395         /* ignore max parameter */
396         max = n;
397     else {
398         if (max < n)
399             max = n;
400         if (max > (int)(rb->len - rb->offset))
401             max = rb->len - rb->offset;
402     }
403
404     while (left < n) {
405         /*
406          * Now we have len+left bytes at the front of s->s3->rbuf.buf and
407          * need to read in more until we have len+n (up to len+max if
408          * possible)
409          */
410
411         clear_sys_error();
412         if (s->rbio != NULL) {
413             s->rwstate = SSL_READING;
414             i = BIO_read(s->rbio, pkt + len + left, max - left);
415         } else {
416             SSLerr(SSL_F_SSL3_READ_N, SSL_R_READ_BIO_NOT_SET);
417             i = -1;
418         }
419
420         if (i <= 0) {
421             rb->left = left;
422             if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
423                 if (len + left == 0)
424                     ssl3_release_read_buffer(s);
425             return (i);
426         }
427         left += i;
428         /*
429          * reads should *never* span multiple packets for DTLS because the
430          * underlying transport protocol is message oriented as opposed to
431          * byte oriented as in the TLS case.
432          */
433         if (SSL_IS_DTLS(s)) {
434             if (n > left)
435                 n = left;       /* makes the while condition false */
436         }
437     }
438
439     /* done reading, now the book-keeping */
440     rb->offset += n;
441     rb->left = left - n;
442     s->rlayer.packet_length += n;
443     s->rwstate = SSL_NOTHING;
444     return (n);
445 }
446
447
448 /*
449  * Call this to write data in records of type 'type' It will return <= 0 if
450  * not all data has been sent or non-blocking IO.
451  */
452 int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
453 {
454     const unsigned char *buf = buf_;
455     int tot;
456     unsigned int n, nw;
457 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
458     unsigned int max_send_fragment, split_send_fragment, maxpipes;
459     unsigned int u_len = (unsigned int)len;
460 #endif
461     SSL3_BUFFER *wb = &s->rlayer.wbuf[0];
462     int i;
463
464     if (len < 0) {
465         SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_NEGATIVE_LENGTH);
466         return -1;
467     }
468
469     s->rwstate = SSL_NOTHING;
470     tot = s->rlayer.wnum;
471     /*
472      * ensure that if we end up with a smaller value of data to write out
473      * than the the original len from a write which didn't complete for
474      * non-blocking I/O and also somehow ended up avoiding the check for
475      * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
476      * possible to end up with (len-tot) as a large number that will then
477      * promptly send beyond the end of the users buffer ... so we trap and
478      * report the error in a way the user will notice
479      */
480     if ((unsigned int)len < s->rlayer.wnum) {
481         SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH);
482         return -1;
483     }
484
485
486     s->rlayer.wnum = 0;
487
488     if (SSL_in_init(s) && !ossl_statem_get_in_handshake(s)) {
489         i = s->handshake_func(s);
490         if (i < 0)
491             return (i);
492         if (i == 0) {
493             SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
494             return -1;
495         }
496     }
497
498     /*
499      * first check if there is a SSL3_BUFFER still being written out.  This
500      * will happen with non blocking IO
501      */
502     if (wb->left != 0) {
503         i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot);
504         if (i <= 0) {
505             /* XXX should we ssl3_release_write_buffer if i<0? */
506             s->rlayer.wnum = tot;
507             return i;
508         }
509         tot += i;               /* this might be last fragment */
510     }
511 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
512     /*
513      * Depending on platform multi-block can deliver several *times*
514      * better performance. Downside is that it has to allocate
515      * jumbo buffer to accomodate up to 8 records, but the
516      * compromise is considered worthy.
517      */
518     if (type == SSL3_RT_APPLICATION_DATA &&
519         u_len >= 4 * (max_send_fragment = s->max_send_fragment) &&
520         s->compress == NULL && s->msg_callback == NULL &&
521         !SSL_USE_ETM(s) && SSL_USE_EXPLICIT_IV(s) &&
522         EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx)) &
523         EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) {
524         unsigned char aad[13];
525         EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
526         int packlen;
527
528         /* minimize address aliasing conflicts */
529         if ((max_send_fragment & 0xfff) == 0)
530             max_send_fragment -= 512;
531
532         if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
533             ssl3_release_write_buffer(s);
534
535             packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
536                                           EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
537                                           max_send_fragment, NULL);
538
539             if (u_len >= 8 * max_send_fragment)
540                 packlen *= 8;
541             else
542                 packlen *= 4;
543
544             wb->buf = OPENSSL_malloc(packlen);
545             if (wb->buf == NULL) {
546                 SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_MALLOC_FAILURE);
547                 return -1;
548             }
549             wb->len = packlen;
550         } else if (tot == len) { /* done? */
551             OPENSSL_free(wb->buf); /* free jumbo buffer */
552             wb->buf = NULL;
553             return tot;
554         }
555
556         n = (len - tot);
557         for (;;) {
558             if (n < 4 * max_send_fragment) {
559                 OPENSSL_free(wb->buf); /* free jumbo buffer */
560                 wb->buf = NULL;
561                 break;
562             }
563
564             if (s->s3->alert_dispatch) {
565                 i = s->method->ssl_dispatch_alert(s);
566                 if (i <= 0) {
567                     s->rlayer.wnum = tot;
568                     return i;
569                 }
570             }
571
572             if (n >= 8 * max_send_fragment)
573                 nw = max_send_fragment * (mb_param.interleave = 8);
574             else
575                 nw = max_send_fragment * (mb_param.interleave = 4);
576
577             memcpy(aad, s->rlayer.write_sequence, 8);
578             aad[8] = type;
579             aad[9] = (unsigned char)(s->version >> 8);
580             aad[10] = (unsigned char)(s->version);
581             aad[11] = 0;
582             aad[12] = 0;
583             mb_param.out = NULL;
584             mb_param.inp = aad;
585             mb_param.len = nw;
586
587             packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
588                                           EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
589                                           sizeof(mb_param), &mb_param);
590
591             if (packlen <= 0 || packlen > (int)wb->len) { /* never happens */
592                 OPENSSL_free(wb->buf); /* free jumbo buffer */
593                 wb->buf = NULL;
594                 break;
595             }
596
597             mb_param.out = wb->buf;
598             mb_param.inp = &buf[tot];
599             mb_param.len = nw;
600
601             if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
602                                     EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
603                                     sizeof(mb_param), &mb_param) <= 0)
604                 return -1;
605
606             s->rlayer.write_sequence[7] += mb_param.interleave;
607             if (s->rlayer.write_sequence[7] < mb_param.interleave) {
608                 int j = 6;
609                 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
610             }
611
612             wb->offset = 0;
613             wb->left = packlen;
614
615             s->rlayer.wpend_tot = nw;
616             s->rlayer.wpend_buf = &buf[tot];
617             s->rlayer.wpend_type = type;
618             s->rlayer.wpend_ret = nw;
619
620             i = ssl3_write_pending(s, type, &buf[tot], nw);
621             if (i <= 0) {
622                 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
623                     OPENSSL_free(wb->buf);
624                     wb->buf = NULL;
625                 }
626                 s->rlayer.wnum = tot;
627                 return i;
628             }
629             if (i == (int)n) {
630                 OPENSSL_free(wb->buf); /* free jumbo buffer */
631                 wb->buf = NULL;
632                 return tot + i;
633             }
634             n -= i;
635             tot += i;
636         }
637     } else
638 #endif
639     if (tot == len) {           /* done? */
640         if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
641             ssl3_release_write_buffer(s);
642
643         return tot;
644     }
645
646     n = (len - tot);
647
648     split_send_fragment = s->split_send_fragment;
649     /*
650      * If max_pipelines is 0 then this means "undefined" and we default to
651      * 1 pipeline. Similaraly if the cipher does not support pipelined
652      * processing then we also only use 1 pipeline, or if we're not using
653      * explicit IVs
654      */
655     maxpipes = s->max_pipelines;
656     if (maxpipes > SSL_MAX_PIPELINES) {
657         /*
658          * We should have prevented this when we set max_pipelines so we
659          * shouldn't get here
660         */
661         SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR);
662         return -1;
663     }
664     if (maxpipes == 0
665             || s->enc_write_ctx == NULL
666             || !(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx))
667                  & EVP_CIPH_FLAG_PIPELINE)
668             || !SSL_USE_EXPLICIT_IV(s))
669         maxpipes = 1;
670     if (s->max_send_fragment == 0 || split_send_fragment > s->max_send_fragment
671             || split_send_fragment == 0) {
672         /*
673          * We should have prevented this when we set the split and max send
674          * fragments so we shouldn't get here
675         */
676         SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR);
677         return -1;
678     }
679
680     for (;;) {
681         unsigned int pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
682         unsigned int numpipes, j;
683
684         if (n == 0)
685             numpipes = 1;
686         else
687             numpipes = ((n - 1) / split_send_fragment) + 1;
688         if (numpipes > maxpipes)
689             numpipes = maxpipes;
690
691         if (n / numpipes >= s->max_send_fragment) {
692             /*
693              * We have enough data to completely fill all available
694              * pipelines
695              */
696             for (j = 0; j < numpipes; j++) {
697                 pipelens[j] = s->max_send_fragment;
698             }
699         } else {
700             /* We can partially fill all available pipelines */
701             tmppipelen = n / numpipes;
702             remain = n % numpipes;
703             for (j = 0; j < numpipes; j++) {
704                 pipelens[j] = tmppipelen;
705                 if (j < remain)
706                     pipelens[j]++;
707             }
708         }
709
710         i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0);
711         if (i <= 0) {
712             /* XXX should we ssl3_release_write_buffer if i<0? */
713             s->rlayer.wnum = tot;
714             return i;
715         }
716
717         if ((i == (int)n) ||
718             (type == SSL3_RT_APPLICATION_DATA &&
719              (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
720             /*
721              * next chunk of data should get another prepended empty fragment
722              * in ciphersuites with known-IV weakness:
723              */
724             s->s3->empty_fragment_done = 0;
725
726             if ((i == (int)n) && s->mode & SSL_MODE_RELEASE_BUFFERS &&
727                 !SSL_IS_DTLS(s))
728                 ssl3_release_write_buffer(s);
729
730             return tot + i;
731         }
732
733         n -= i;
734         tot += i;
735     }
736 }
737
738 int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
739                   unsigned int *pipelens, unsigned int numpipes,
740                   int create_empty_fragment)
741 {
742     unsigned char *outbuf[SSL_MAX_PIPELINES], *plen[SSL_MAX_PIPELINES];
743     SSL3_RECORD wr[SSL_MAX_PIPELINES];
744     int i, mac_size, clear = 0;
745     int prefix_len = 0;
746     int eivlen;
747     size_t align = 0;
748     SSL3_BUFFER *wb;
749     SSL_SESSION *sess;
750     unsigned int totlen = 0;
751     unsigned int j;
752
753     for (j = 0; j < numpipes; j++)
754         totlen += pipelens[j];
755     /*
756      * first check if there is a SSL3_BUFFER still being written out.  This
757      * will happen with non blocking IO
758      */
759     if (RECORD_LAYER_write_pending(&s->rlayer))
760         return (ssl3_write_pending(s, type, buf, totlen));
761
762     /* If we have an alert to send, lets send it */
763     if (s->s3->alert_dispatch) {
764         i = s->method->ssl_dispatch_alert(s);
765         if (i <= 0)
766             return (i);
767         /* if it went, fall through and send more stuff */
768     }
769
770     if (s->rlayer.numwpipes < numpipes)
771         if (!ssl3_setup_write_buffer(s, numpipes))
772             return -1;
773
774     if (totlen == 0 && !create_empty_fragment)
775         return 0;
776
777     sess = s->session;
778
779     if ((sess == NULL) ||
780         (s->enc_write_ctx == NULL) ||
781         (EVP_MD_CTX_md(s->write_hash) == NULL)) {
782         clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
783         mac_size = 0;
784     } else {
785         mac_size = EVP_MD_CTX_size(s->write_hash);
786         if (mac_size < 0)
787             goto err;
788     }
789
790     /*
791      * 'create_empty_fragment' is true only when this function calls itself
792      */
793     if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) {
794         /*
795          * countermeasure against known-IV weakness in CBC ciphersuites (see
796          * http://www.openssl.org/~bodo/tls-cbc.txt)
797          */
798
799         if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
800             /*
801              * recursive function call with 'create_empty_fragment' set; this
802              * prepares and buffers the data for an empty fragment (these
803              * 'prefix_len' bytes are sent out later together with the actual
804              * payload)
805              */
806             unsigned int tmppipelen = 0;
807
808             prefix_len = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1);
809             if (prefix_len <= 0)
810                 goto err;
811
812             if (prefix_len >
813                 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD))
814             {
815                 /* insufficient space */
816                 SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
817                 goto err;
818             }
819         }
820
821         s->s3->empty_fragment_done = 1;
822     }
823
824     if (create_empty_fragment) {
825         wb = &s->rlayer.wbuf[0];
826 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
827         /*
828          * extra fragment would be couple of cipher blocks, which would be
829          * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
830          * payload, then we can just pretent we simply have two headers.
831          */
832         align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
833         align = (0-align) & (SSL3_ALIGN_PAYLOAD - 1);
834 #endif
835         outbuf[0] = SSL3_BUFFER_get_buf(wb) + align;
836         SSL3_BUFFER_set_offset(wb, align);
837     } else if (prefix_len) {
838         wb = &s->rlayer.wbuf[0];
839         outbuf[0] = SSL3_BUFFER_get_buf(wb) + SSL3_BUFFER_get_offset(wb)
840                     + prefix_len;
841     } else {
842         for (j=0; j < numpipes; j++) {
843             wb = &s->rlayer.wbuf[j];
844 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
845             align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
846             align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
847 #endif
848             outbuf[j] = SSL3_BUFFER_get_buf(wb) + align;
849             SSL3_BUFFER_set_offset(wb, align);
850         }
851     }
852
853     /* Explicit IV length, block ciphers appropriate version flag */
854     if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)) {
855         int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
856         if (mode == EVP_CIPH_CBC_MODE) {
857             eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
858             if (eivlen <= 1)
859                 eivlen = 0;
860         }
861         /* Need explicit part of IV for GCM mode */
862         else if (mode == EVP_CIPH_GCM_MODE)
863             eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
864         else if (mode == EVP_CIPH_CCM_MODE)
865             eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
866         else
867             eivlen = 0;
868     } else
869         eivlen = 0;
870
871
872     totlen = 0;
873     /* Clear our SSL3_RECORD structures */
874     memset(wr, 0, sizeof wr);
875     for (j=0; j < numpipes; j++) {
876         /* write the header */
877         *(outbuf[j]++) = type & 0xff;
878         SSL3_RECORD_set_type(&wr[j], type);
879
880         *(outbuf[j]++) = (s->version >> 8);
881         /*
882          * Some servers hang if iniatial client hello is larger than 256 bytes
883          * and record version number > TLS 1.0
884          */
885         if (SSL_get_state(s) == TLS_ST_CW_CLNT_HELLO
886             && !s->renegotiate && TLS1_get_version(s) > TLS1_VERSION)
887             *(outbuf[j]++) = 0x1;
888         else
889             *(outbuf[j]++) = s->version & 0xff;
890
891         /* field where we are to write out packet length */
892         plen[j] = outbuf[j];
893         outbuf[j] += 2;
894
895         /* lets setup the record stuff. */
896         SSL3_RECORD_set_data(&wr[j], outbuf[j] + eivlen);
897         SSL3_RECORD_set_length(&wr[j], (int)pipelens[j]);
898         SSL3_RECORD_set_input(&wr[j], (unsigned char *)&buf[totlen]);
899         totlen += pipelens[j];
900
901         /*
902          * we now 'read' from wr->input, wr->length bytes into wr->data
903          */
904
905         /* first we compress */
906         if (s->compress != NULL) {
907             if (!ssl3_do_compress(s, &wr[j])) {
908                 SSLerr(SSL_F_DO_SSL3_WRITE, SSL_R_COMPRESSION_FAILURE);
909                 goto err;
910             }
911         } else {
912             memcpy(wr[j].data, wr[j].input, wr[j].length);
913             SSL3_RECORD_reset_input(&wr[j]);
914         }
915
916         /*
917          * we should still have the output to wr->data and the input from
918          * wr->input.  Length should be wr->length. wr->data still points in the
919          * wb->buf
920          */
921
922         if (!SSL_USE_ETM(s) && mac_size != 0) {
923             if (s->method->ssl3_enc->mac(s, &wr[j],
924                     &(outbuf[j][wr[j].length + eivlen]), 1) < 0)
925                 goto err;
926             SSL3_RECORD_add_length(&wr[j], mac_size);
927         }
928
929
930         SSL3_RECORD_set_data(&wr[j], outbuf[j]);
931         SSL3_RECORD_reset_input(&wr[j]);
932
933         if (eivlen) {
934             /*
935              * if (RAND_pseudo_bytes(p, eivlen) <= 0) goto err;
936              */
937             SSL3_RECORD_add_length(&wr[j], eivlen);
938         }
939     }
940
941     if (s->method->ssl3_enc->enc(s, wr, numpipes, 1) < 1)
942         goto err;
943
944     for (j=0; j < numpipes; j++) {
945         if (SSL_USE_ETM(s) && mac_size != 0) {
946             if (s->method->ssl3_enc->mac(s, &wr[j],
947                                          outbuf[j] + wr[j].length, 1) < 0)
948                 goto err;
949             SSL3_RECORD_add_length(&wr[j], mac_size);
950         }
951
952         /* record length after mac and block padding */
953         s2n(SSL3_RECORD_get_length(&wr[j]), plen[j]);
954
955         if (s->msg_callback)
956             s->msg_callback(1, 0, SSL3_RT_HEADER, plen[j] - 5, 5, s,
957                             s->msg_callback_arg);
958
959         /*
960          * we should now have wr->data pointing to the encrypted data, which is
961          * wr->length long
962          */
963         SSL3_RECORD_set_type(&wr[j], type);  /* not needed but helps for debugging */
964         SSL3_RECORD_add_length(&wr[j], SSL3_RT_HEADER_LENGTH);
965
966         if (create_empty_fragment) {
967             /*
968              * we are in a recursive call; just return the length, don't write
969              * out anything here
970              */
971             if (j > 0) {
972                 /* We should never be pipelining an empty fragment!! */
973                 SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
974                 goto err;
975             }
976             return SSL3_RECORD_get_length(wr);
977         }
978
979         /* now let's set up wb */
980         SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
981             prefix_len + SSL3_RECORD_get_length(&wr[j]));
982     }
983
984
985
986     /*
987      * memorize arguments so that ssl3_write_pending can detect bad write
988      * retries later
989      */
990     s->rlayer.wpend_tot = totlen;
991     s->rlayer.wpend_buf = buf;
992     s->rlayer.wpend_type = type;
993     s->rlayer.wpend_ret = totlen;
994
995     /* we now just need to write the buffer */
996     return ssl3_write_pending(s, type, buf, totlen);
997  err:
998     return -1;
999 }
1000
1001 /* if s->s3->wbuf.left != 0, we need to call this */
1002 int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
1003                        unsigned int len)
1004 {
1005     int i;
1006     SSL3_BUFFER *wb = s->rlayer.wbuf;
1007     unsigned int currbuf = 0;
1008
1009 /* XXXX */
1010     if ((s->rlayer.wpend_tot > (int)len)
1011         || ((s->rlayer.wpend_buf != buf) &&
1012             !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
1013         || (s->rlayer.wpend_type != type)) {
1014         SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BAD_WRITE_RETRY);
1015         return (-1);
1016     }
1017
1018     for (;;) {
1019         /* Loop until we find a buffer we haven't written out yet */
1020         if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
1021                 && currbuf < s->rlayer.numwpipes - 1) {
1022             currbuf++;
1023             continue;
1024         }
1025         clear_sys_error();
1026         if (s->wbio != NULL) {
1027             s->rwstate = SSL_WRITING;
1028             i = BIO_write(s->wbio,
1029                 (char *)&(SSL3_BUFFER_get_buf(&wb[currbuf])[
1030                                 SSL3_BUFFER_get_offset(&wb[currbuf])]),
1031                 (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
1032         } else {
1033             SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BIO_NOT_SET);
1034             i = -1;
1035         }
1036         if (i == SSL3_BUFFER_get_left(&wb[currbuf])) {
1037             SSL3_BUFFER_set_left(&wb[currbuf], 0);
1038             SSL3_BUFFER_add_offset(&wb[currbuf], i);
1039             if (currbuf + 1 < s->rlayer.numwpipes)
1040                 continue;
1041             s->rwstate = SSL_NOTHING;
1042             return (s->rlayer.wpend_ret);
1043         } else if (i <= 0) {
1044             if (SSL_IS_DTLS(s)) {
1045                 /*
1046                  * For DTLS, just drop it. That's kind of the whole point in
1047                  * using a datagram service
1048                  */
1049                 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1050             }
1051             return (i);
1052         }
1053         SSL3_BUFFER_add_offset(&wb[currbuf], i);
1054         SSL3_BUFFER_add_left(&wb[currbuf], -i);
1055     }
1056 }
1057
1058 /*-
1059  * Return up to 'len' payload bytes received in 'type' records.
1060  * 'type' is one of the following:
1061  *
1062  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1063  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1064  *   -  0 (during a shutdown, no data has to be returned)
1065  *
1066  * If we don't have stored data to work from, read a SSL/TLS record first
1067  * (possibly multiple records if we still don't have anything to return).
1068  *
1069  * This function must handle any surprises the peer may have for us, such as
1070  * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1071  * messages are treated as if they were handshake messages *if* the |recd_type|
1072  * argument is non NULL.
1073  * Also if record payloads contain fragments too small to process, we store
1074  * them until there is enough for the respective protocol (the record protocol
1075  * may use arbitrary fragmentation and even interleaving):
1076  *     Change cipher spec protocol
1077  *             just 1 byte needed, no need for keeping anything stored
1078  *     Alert protocol
1079  *             2 bytes needed (AlertLevel, AlertDescription)
1080  *     Handshake protocol
1081  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
1082  *             to detect unexpected Client Hello and Hello Request messages
1083  *             here, anything else is handled by higher layers
1084  *     Application data protocol
1085  *             none of our business
1086  */
1087 int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
1088                     int len, int peek)
1089 {
1090     int al, i, j, ret;
1091     unsigned int n, curr_rec, num_recs, read_bytes;
1092     SSL3_RECORD *rr;
1093     SSL3_BUFFER *rbuf;
1094     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
1095
1096     rbuf = &s->rlayer.rbuf;
1097
1098     if (!SSL3_BUFFER_is_initialised(rbuf)) {
1099         /* Not initialized yet */
1100         if (!ssl3_setup_read_buffer(s))
1101             return (-1);
1102     }
1103
1104     if ((type && (type != SSL3_RT_APPLICATION_DATA)
1105          && (type != SSL3_RT_HANDSHAKE)) || (peek
1106                                              && (type !=
1107                                                  SSL3_RT_APPLICATION_DATA))) {
1108         SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1109         return -1;
1110     }
1111
1112     if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
1113         /* (partially) satisfy request from storage */
1114     {
1115         unsigned char *src = s->rlayer.handshake_fragment;
1116         unsigned char *dst = buf;
1117         unsigned int k;
1118
1119         /* peek == 0 */
1120         n = 0;
1121         while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1122             *dst++ = *src++;
1123             len--;
1124             s->rlayer.handshake_fragment_len--;
1125             n++;
1126         }
1127         /* move any remaining fragment bytes: */
1128         for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1129             s->rlayer.handshake_fragment[k] = *src++;
1130
1131         if (recvd_type != NULL)
1132             *recvd_type = SSL3_RT_HANDSHAKE;
1133
1134         return n;
1135     }
1136
1137     /*
1138      * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1139      */
1140
1141     if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) {
1142         /* type == SSL3_RT_APPLICATION_DATA */
1143         i = s->handshake_func(s);
1144         if (i < 0)
1145             return (i);
1146         if (i == 0) {
1147             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1148             return (-1);
1149         }
1150     }
1151  start:
1152     s->rwstate = SSL_NOTHING;
1153
1154     /*-
1155      * For each record 'i' up to |num_recs]
1156      * rr[i].type     - is the type of record
1157      * rr[i].data,    - data
1158      * rr[i].off,     - offset into 'data' for next read
1159      * rr[i].length,  - number of bytes.
1160      */
1161     rr = s->rlayer.rrec;
1162     num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1163
1164     do {
1165         /* get new records if necessary */
1166         if (num_recs == 0) {
1167             ret = ssl3_get_record(s);
1168             if (ret <= 0)
1169                 return (ret);
1170             num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1171             if (num_recs == 0) {
1172                 /* Shouldn't happen */
1173                 al = SSL_AD_INTERNAL_ERROR;
1174                 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1175                 goto f_err;
1176             }
1177         }
1178         /* Skip over any records we have already used or are zero in length */
1179         for (curr_rec = 0;
1180              curr_rec < num_recs && SSL3_RECORD_get_length(&rr[curr_rec]) == 0;
1181              curr_rec++);
1182         if (curr_rec == num_recs) {
1183             RECORD_LAYER_set_numrpipes(&s->rlayer, 0);
1184             num_recs = 0;
1185             curr_rec = 0;
1186         }
1187     } while (num_recs == 0);
1188     rr = &rr[curr_rec];
1189
1190     /* we now have a packet which can be read and processed */
1191
1192     if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
1193                                    * reset by ssl3_get_finished */
1194         && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {
1195         al = SSL_AD_UNEXPECTED_MESSAGE;
1196         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1197         goto f_err;
1198     }
1199
1200     /*
1201      * If the other end has shut down, throw anything we read away (even in
1202      * 'peek' mode)
1203      */
1204     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1205         SSL3_RECORD_set_length(rr, 0);
1206         s->rwstate = SSL_NOTHING;
1207         return (0);
1208     }
1209
1210     if (type == SSL3_RECORD_get_type(rr)
1211             || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1212                 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {
1213         /*
1214          * SSL3_RT_APPLICATION_DATA or
1215          * SSL3_RT_HANDSHAKE or
1216          * SSL3_RT_CHANGE_CIPHER_SPEC
1217          */
1218         /*
1219          * make sure that we are not getting application data when we are
1220          * doing a handshake for the first time
1221          */
1222         if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
1223             (s->enc_read_ctx == NULL)) {
1224             al = SSL_AD_UNEXPECTED_MESSAGE;
1225             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
1226             goto f_err;
1227         }
1228
1229         if (type == SSL3_RT_HANDSHAKE
1230                 && SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1231                 && s->rlayer.handshake_fragment_len > 0) {
1232             al = SSL_AD_UNEXPECTED_MESSAGE;
1233             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1234             goto f_err;
1235         }
1236
1237         if (recvd_type != NULL)
1238             *recvd_type = SSL3_RECORD_get_type(rr);
1239
1240         if (len <= 0)
1241             return (len);
1242
1243         read_bytes = 0;
1244         do {
1245             if ((unsigned int)len - read_bytes > SSL3_RECORD_get_length(rr))
1246                 n = SSL3_RECORD_get_length(rr);
1247             else
1248                 n = (unsigned int)len - read_bytes;
1249
1250             memcpy(buf, &(rr->data[rr->off]), n);
1251             buf += n;
1252             if (!peek) {
1253                 SSL3_RECORD_add_length(rr, -n);
1254                 SSL3_RECORD_add_off(rr, n);
1255                 if (SSL3_RECORD_get_length(rr) == 0) {
1256                     s->rlayer.rstate = SSL_ST_READ_HEADER;
1257                     SSL3_RECORD_set_off(rr, 0);
1258                 }
1259             }
1260             if (SSL3_RECORD_get_length(rr) == 0
1261                 || (peek && n == SSL3_RECORD_get_length(rr))) {
1262                 curr_rec++;
1263                 rr++;
1264             }
1265             read_bytes += n;
1266         } while (type == SSL3_RT_APPLICATION_DATA && curr_rec < num_recs
1267                  && read_bytes < (unsigned int)len);
1268         if (!peek && curr_rec == num_recs
1269                 && (s->mode & SSL_MODE_RELEASE_BUFFERS)
1270                 && SSL3_BUFFER_get_left(rbuf) == 0)
1271             ssl3_release_read_buffer(s);
1272         return read_bytes;
1273     }
1274
1275     /*
1276      * If we get here, then type != rr->type; if we have a handshake message,
1277      * then it was unexpected (Hello Request or Client Hello) or invalid (we
1278      * were actually expecting a CCS).
1279      */
1280
1281     if (rr->type == SSL3_RT_HANDSHAKE && type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1282         al = SSL_AD_UNEXPECTED_MESSAGE;
1283         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_MESSAGE);
1284         goto f_err;
1285     }
1286
1287     /*
1288      * Lets just double check that we've not got an SSLv2 record
1289      */
1290     if (rr->rec_version == SSL2_VERSION) {
1291         /*
1292          * Should never happen. ssl3_get_record() should only give us an SSLv2
1293          * record back if this is the first packet and we are looking for an
1294          * initial ClientHello. Therefore |type| should always be equal to
1295          * |rr->type|. If not then something has gone horribly wrong
1296          */
1297         al = SSL_AD_INTERNAL_ERROR;
1298         SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1299         goto f_err;
1300     }
1301
1302     if(s->method->version == TLS_ANY_VERSION
1303             && (s->server || rr->type != SSL3_RT_ALERT)) {
1304         /*
1305          * If we've got this far and still haven't decided on what version
1306          * we're using then this must be a client side alert we're dealing with
1307          * (we don't allow heartbeats yet). We shouldn't be receiving anything
1308          * other than a ClientHello if we are a server.
1309          */
1310         s->version = rr->rec_version;
1311         al = SSL_AD_UNEXPECTED_MESSAGE;
1312         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_MESSAGE);
1313         goto f_err;
1314     }
1315
1316     /*
1317      * In case of record types for which we have 'fragment' storage, fill
1318      * that so that we can process the data at a fixed place.
1319      */
1320     {
1321         unsigned int dest_maxlen = 0;
1322         unsigned char *dest = NULL;
1323         unsigned int *dest_len = NULL;
1324
1325         if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
1326             dest_maxlen = sizeof s->rlayer.handshake_fragment;
1327             dest = s->rlayer.handshake_fragment;
1328             dest_len = &s->rlayer.handshake_fragment_len;
1329         } else if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {
1330             dest_maxlen = sizeof s->rlayer.alert_fragment;
1331             dest = s->rlayer.alert_fragment;
1332             dest_len = &s->rlayer.alert_fragment_len;
1333         }
1334
1335         if (dest_maxlen > 0) {
1336             n = dest_maxlen - *dest_len; /* available space in 'dest' */
1337             if (SSL3_RECORD_get_length(rr) < n)
1338                 n = SSL3_RECORD_get_length(rr); /* available bytes */
1339
1340             /* now move 'n' bytes: */
1341             while (n-- > 0) {
1342                 dest[(*dest_len)++] =
1343                     SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)];
1344                 SSL3_RECORD_add_off(rr, 1);
1345                 SSL3_RECORD_add_length(rr, -1);
1346             }
1347
1348             if (*dest_len < dest_maxlen)
1349                 goto start;     /* fragment was too small */
1350         }
1351     }
1352
1353     /*-
1354      * s->rlayer.handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
1355      * s->rlayer.alert_fragment_len == 2      iff  rr->type == SSL3_RT_ALERT.
1356      * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1357      */
1358
1359     /* If we are a client, check for an incoming 'Hello Request': */
1360     if ((!s->server) &&
1361         (s->rlayer.handshake_fragment_len >= 4) &&
1362         (s->rlayer.handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
1363         (s->session != NULL) && (s->session->cipher != NULL)) {
1364         s->rlayer.handshake_fragment_len = 0;
1365
1366         if ((s->rlayer.handshake_fragment[1] != 0) ||
1367             (s->rlayer.handshake_fragment[2] != 0) ||
1368             (s->rlayer.handshake_fragment[3] != 0)) {
1369             al = SSL_AD_DECODE_ERROR;
1370             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
1371             goto f_err;
1372         }
1373
1374         if (s->msg_callback)
1375             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1376                             s->rlayer.handshake_fragment, 4, s,
1377                             s->msg_callback_arg);
1378
1379         if (SSL_is_init_finished(s) &&
1380             !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1381             !s->s3->renegotiate) {
1382             ssl3_renegotiate(s);
1383             if (ssl3_renegotiate_check(s)) {
1384                 i = s->handshake_func(s);
1385                 if (i < 0)
1386                     return (i);
1387                 if (i == 0) {
1388                     SSLerr(SSL_F_SSL3_READ_BYTES,
1389                            SSL_R_SSL_HANDSHAKE_FAILURE);
1390                     return (-1);
1391                 }
1392
1393                 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1394                     if (SSL3_BUFFER_get_left(rbuf) == 0) {
1395                         /* no read-ahead left? */
1396                         BIO *bio;
1397                         /*
1398                          * In the case where we try to read application data,
1399                          * but we trigger an SSL handshake, we return -1 with
1400                          * the retry option set.  Otherwise renegotiation may
1401                          * cause nasty problems in the blocking world
1402                          */
1403                         s->rwstate = SSL_READING;
1404                         bio = SSL_get_rbio(s);
1405                         BIO_clear_retry_flags(bio);
1406                         BIO_set_retry_read(bio);
1407                         return (-1);
1408                     }
1409                 }
1410             }
1411         }
1412         /*
1413          * we either finished a handshake or ignored the request, now try
1414          * again to obtain the (application) data we were asked for
1415          */
1416         goto start;
1417     }
1418     /*
1419      * If we are a server and get a client hello when renegotiation isn't
1420      * allowed send back a no renegotiation alert and carry on. WARNING:
1421      * experimental code, needs reviewing (steve)
1422      */
1423     if (s->server &&
1424         SSL_is_init_finished(s) &&
1425         !s->s3->send_connection_binding &&
1426         (s->version > SSL3_VERSION) &&
1427         (s->rlayer.handshake_fragment_len >= 4) &&
1428         (s->rlayer.handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
1429         (s->session != NULL) && (s->session->cipher != NULL) &&
1430         !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
1431         SSL3_RECORD_set_length(rr, 0);
1432         ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1433         goto start;
1434     }
1435     if (s->rlayer.alert_fragment_len >= 2) {
1436         int alert_level = s->rlayer.alert_fragment[0];
1437         int alert_descr = s->rlayer.alert_fragment[1];
1438
1439         s->rlayer.alert_fragment_len = 0;
1440
1441         if (s->msg_callback)
1442             s->msg_callback(0, s->version, SSL3_RT_ALERT,
1443                             s->rlayer.alert_fragment, 2, s,
1444                             s->msg_callback_arg);
1445
1446         if (s->info_callback != NULL)
1447             cb = s->info_callback;
1448         else if (s->ctx->info_callback != NULL)
1449             cb = s->ctx->info_callback;
1450
1451         if (cb != NULL) {
1452             j = (alert_level << 8) | alert_descr;
1453             cb(s, SSL_CB_READ_ALERT, j);
1454         }
1455
1456         if (alert_level == SSL3_AL_WARNING) {
1457             s->s3->warn_alert = alert_descr;
1458             if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
1459                 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1460                 return (0);
1461             }
1462             /*
1463              * This is a warning but we receive it if we requested
1464              * renegotiation and the peer denied it. Terminate with a fatal
1465              * alert because if application tried to renegotiatie it
1466              * presumably had a good reason and expects it to succeed. In
1467              * future we might have a renegotiation where we don't care if
1468              * the peer refused it where we carry on.
1469              */
1470             else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1471                 al = SSL_AD_HANDSHAKE_FAILURE;
1472                 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION);
1473                 goto f_err;
1474             }
1475 #ifdef SSL_AD_MISSING_SRP_USERNAME
1476             else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)
1477                 return (0);
1478 #endif
1479         } else if (alert_level == SSL3_AL_FATAL) {
1480             char tmp[16];
1481
1482             s->rwstate = SSL_NOTHING;
1483             s->s3->fatal_alert = alert_descr;
1484             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
1485             BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
1486             ERR_add_error_data(2, "SSL alert number ", tmp);
1487             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1488             SSL_CTX_remove_session(s->ctx, s->session);
1489             return (0);
1490         } else {
1491             al = SSL_AD_ILLEGAL_PARAMETER;
1492             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
1493             goto f_err;
1494         }
1495
1496         goto start;
1497     }
1498
1499     if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
1500                                             * shutdown */
1501         s->rwstate = SSL_NOTHING;
1502         SSL3_RECORD_set_length(rr, 0);
1503         return (0);
1504     }
1505
1506     if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
1507         al = SSL_AD_UNEXPECTED_MESSAGE;
1508         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1509         goto f_err;
1510     }
1511
1512     /*
1513      * Unexpected handshake message (Client Hello, or protocol violation)
1514      */
1515     if ((s->rlayer.handshake_fragment_len >= 4)
1516             && !ossl_statem_get_in_handshake(s)) {
1517         if (SSL_is_init_finished(s) &&
1518             !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
1519             ossl_statem_set_in_init(s, 1);
1520             s->renegotiate = 1;
1521             s->new_session = 1;
1522         }
1523         i = s->handshake_func(s);
1524         if (i < 0)
1525             return (i);
1526         if (i == 0) {
1527             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1528             return (-1);
1529         }
1530
1531         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1532             if (SSL3_BUFFER_get_left(rbuf) == 0) {
1533                 /* no read-ahead left? */
1534                 BIO *bio;
1535                 /*
1536                  * In the case where we try to read application data, but we
1537                  * trigger an SSL handshake, we return -1 with the retry
1538                  * option set.  Otherwise renegotiation may cause nasty
1539                  * problems in the blocking world
1540                  */
1541                 s->rwstate = SSL_READING;
1542                 bio = SSL_get_rbio(s);
1543                 BIO_clear_retry_flags(bio);
1544                 BIO_set_retry_read(bio);
1545                 return (-1);
1546             }
1547         }
1548         goto start;
1549     }
1550
1551     switch (SSL3_RECORD_get_type(rr)) {
1552     default:
1553         /*
1554          * TLS up to v1.1 just ignores unknown message types: TLS v1.2 give
1555          * an unexpected message alert.
1556          */
1557         if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION) {
1558             SSL3_RECORD_set_length(rr, 0);
1559             goto start;
1560         }
1561         al = SSL_AD_UNEXPECTED_MESSAGE;
1562         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1563         goto f_err;
1564     case SSL3_RT_CHANGE_CIPHER_SPEC:
1565     case SSL3_RT_ALERT:
1566     case SSL3_RT_HANDSHAKE:
1567         /*
1568          * we already handled all of these, with the possible exception of
1569          * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1570          * that should not happen when type != rr->type
1571          */
1572         al = SSL_AD_UNEXPECTED_MESSAGE;
1573         SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1574         goto f_err;
1575     case SSL3_RT_APPLICATION_DATA:
1576         /*
1577          * At this point, we were expecting handshake data, but have
1578          * application data.  If the library was running inside ssl3_read()
1579          * (i.e. in_read_app_data is set) and it makes sense to read
1580          * application data at this point (session renegotiation not yet
1581          * started), we will indulge it.
1582          */
1583         if (ossl_statem_app_data_allowed(s)) {
1584             s->s3->in_read_app_data = 2;
1585             return (-1);
1586         } else {
1587             al = SSL_AD_UNEXPECTED_MESSAGE;
1588             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1589             goto f_err;
1590         }
1591     }
1592     /* not reached */
1593
1594  f_err:
1595     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1596     return (-1);
1597 }
1598
1599 void ssl3_record_sequence_update(unsigned char *seq)
1600 {
1601     int i;
1602
1603     for (i = 7; i >= 0; i--) {
1604         ++seq[i];
1605         if (seq[i] != 0)
1606             break;
1607     }
1608 }
1609
1610 /*
1611  * Returns true if the current rrec was sent in SSLv2 backwards compatible
1612  * format and false otherwise.
1613  */
1614 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1615 {
1616     return SSL3_RECORD_is_sslv2_record(&rl->rrec[0]);
1617 }
1618
1619 /*
1620  * Returns the length in bytes of the current rrec
1621  */
1622 unsigned int RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
1623 {
1624     return SSL3_RECORD_get_length(&rl->rrec[0]);
1625 }