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