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