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