SSL object refactoring using SSL_CONNECTION object
[openssl.git] / ssl / record / rec_layer_s3.c
1 /*
2  * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include <limits.h>
12 #include <errno.h>
13 #include "../ssl_local.h"
14 #include <openssl/evp.h>
15 #include <openssl/buffer.h>
16 #include <openssl/rand.h>
17 #include "record_local.h"
18 #include "internal/packet.h"
19
20 #if     defined(OPENSSL_SMALL_FOOTPRINT) || \
21         !(      defined(AES_ASM) &&     ( \
22                 defined(__x86_64)       || defined(__x86_64__)  || \
23                 defined(_M_AMD64)       || defined(_M_X64)      ) \
24         )
25 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
26 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
27 #endif
28
29 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
30 {
31     rl->s = s;
32     RECORD_LAYER_set_first_record(&s->rlayer);
33     SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
34 }
35
36 void RECORD_LAYER_clear(RECORD_LAYER *rl)
37 {
38     rl->rstate = SSL_ST_READ_HEADER;
39
40     /*
41      * Do I need to clear read_ahead? As far as I can tell read_ahead did not
42      * previously get reset by SSL_clear...so I'll keep it that way..but is
43      * that right?
44      */
45
46     rl->packet = NULL;
47     rl->packet_length = 0;
48     rl->wnum = 0;
49     memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
50     rl->handshake_fragment_len = 0;
51     rl->wpend_tot = 0;
52     rl->wpend_type = 0;
53     rl->wpend_ret = 0;
54     rl->wpend_buf = NULL;
55
56     SSL3_BUFFER_clear(&rl->rbuf);
57     ssl3_release_write_buffer(rl->s);
58     rl->numrpipes = 0;
59     SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
60
61     RECORD_LAYER_reset_read_sequence(rl);
62     RECORD_LAYER_reset_write_sequence(rl);
63
64     if (rl->d)
65         DTLS_RECORD_LAYER_clear(rl);
66 }
67
68 void RECORD_LAYER_release(RECORD_LAYER *rl)
69 {
70     if (SSL3_BUFFER_is_initialised(&rl->rbuf))
71         ssl3_release_read_buffer(rl->s);
72     if (rl->numwpipes > 0)
73         ssl3_release_write_buffer(rl->s);
74     SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
75 }
76
77 /* Checks if we have unprocessed read ahead data pending */
78 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
79 {
80     return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
81 }
82
83 /* Checks if we have decrypted unread record data pending */
84 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
85 {
86     size_t curr_rec = 0, num_recs = RECORD_LAYER_get_numrpipes(rl);
87     const SSL3_RECORD *rr = rl->rrec;
88
89     while (curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]))
90         curr_rec++;
91
92     return curr_rec < num_recs;
93 }
94
95 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
96 {
97     return (rl->numwpipes > 0)
98         && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
99 }
100
101 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
102 {
103     memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
104 }
105
106 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
107 {
108     memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
109 }
110
111 size_t ssl3_pending(const SSL *s)
112 {
113     size_t i, num = 0;
114     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
115
116     if (sc == NULL)
117         return 0;
118
119     if (sc->rlayer.rstate == SSL_ST_READ_BODY)
120         return 0;
121
122     for (i = 0; i < RECORD_LAYER_get_numrpipes(&sc->rlayer); i++) {
123         if (SSL3_RECORD_get_type(&sc->rlayer.rrec[i])
124             != SSL3_RT_APPLICATION_DATA)
125             return 0;
126         num += SSL3_RECORD_get_length(&sc->rlayer.rrec[i]);
127     }
128
129     return num;
130 }
131
132 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
133 {
134     ctx->default_read_buf_len = len;
135 }
136
137 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
138 {
139     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
140
141     if (sc == NULL)
142         return;
143
144     SSL3_BUFFER_set_default_len(RECORD_LAYER_get_rbuf(&sc->rlayer), len);
145 }
146
147 const char *SSL_rstate_string_long(const SSL *s)
148 {
149     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
150
151     if (sc == NULL)
152         return NULL;
153
154     switch (sc->rlayer.rstate) {
155     case SSL_ST_READ_HEADER:
156         return "read header";
157     case SSL_ST_READ_BODY:
158         return "read body";
159     case SSL_ST_READ_DONE:
160         return "read done";
161     default:
162         return "unknown";
163     }
164 }
165
166 const char *SSL_rstate_string(const SSL *s)
167 {
168     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
169
170     if (sc == NULL)
171         return NULL;
172
173     switch (sc->rlayer.rstate) {
174     case SSL_ST_READ_HEADER:
175         return "RH";
176     case SSL_ST_READ_BODY:
177         return "RB";
178     case SSL_ST_READ_DONE:
179         return "RD";
180     default:
181         return "unknown";
182     }
183 }
184
185 /*
186  * Return values are as per SSL_read()
187  */
188 int ssl3_read_n(SSL_CONNECTION *s, size_t n, size_t max, int extend,
189                 int clearold, size_t *readbytes)
190 {
191     /*
192      * If extend == 0, obtain new n-byte packet; if extend == 1, increase
193      * packet by another n bytes. The packet will be in the sub-array of
194      * s->rlayer.rbuf.buf specified by s->rlayer.packet and
195      * s->rlayer.packet_length. (If s->rlayer.read_ahead is set, 'max' bytes may
196      * be stored in rbuf [plus s->rlayer.packet_length bytes if extend == 1].)
197      * if clearold == 1, move the packet to the start of the buffer; if
198      * clearold == 0 then leave any old packets where they were
199      */
200     size_t len, left, align = 0;
201     unsigned char *pkt;
202     SSL3_BUFFER *rb;
203
204     if (n == 0)
205         return 0;
206
207     rb = &s->rlayer.rbuf;
208     if (rb->buf == NULL)
209         if (!ssl3_setup_read_buffer(s)) {
210             /* SSLfatal() already called */
211             return -1;
212         }
213
214     left = rb->left;
215 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
216     align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
217     align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
218 #endif
219
220     if (!extend) {
221         /* start with empty packet ... */
222         if (left == 0)
223             rb->offset = align;
224         else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
225             /*
226              * check if next packet length is large enough to justify payload
227              * alignment...
228              */
229             pkt = rb->buf + rb->offset;
230             if (pkt[0] == SSL3_RT_APPLICATION_DATA
231                 && (pkt[3] << 8 | pkt[4]) >= 128) {
232                 /*
233                  * Note that even if packet is corrupted and its length field
234                  * is insane, we can only be led to wrong decision about
235                  * whether memmove will occur or not. Header values has no
236                  * effect on memmove arguments and therefore no buffer
237                  * overrun can be triggered.
238                  */
239                 memmove(rb->buf + align, pkt, left);
240                 rb->offset = align;
241             }
242         }
243         s->rlayer.packet = rb->buf + rb->offset;
244         s->rlayer.packet_length = 0;
245         /* ... now we can act as if 'extend' was set */
246     }
247
248     len = s->rlayer.packet_length;
249     pkt = rb->buf + align;
250     /*
251      * Move any available bytes to front of buffer: 'len' bytes already
252      * pointed to by 'packet', 'left' extra ones at the end
253      */
254     if (s->rlayer.packet != pkt && clearold == 1) {
255         memmove(pkt, s->rlayer.packet, len + left);
256         s->rlayer.packet = pkt;
257         rb->offset = len + align;
258     }
259
260     /*
261      * For DTLS/UDP reads should not span multiple packets because the read
262      * operation returns the whole packet at once (as long as it fits into
263      * the buffer).
264      */
265     if (SSL_CONNECTION_IS_DTLS(s)) {
266         if (left == 0 && extend)
267             return 0;
268         if (left > 0 && n > left)
269             n = left;
270     }
271
272     /* if there is enough in the buffer from a previous read, take some */
273     if (left >= n) {
274         s->rlayer.packet_length += n;
275         rb->left = left - n;
276         rb->offset += n;
277         *readbytes = n;
278         return 1;
279     }
280
281     /* else we need to read more data */
282
283     if (n > rb->len - rb->offset) {
284         /* does not happen */
285         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
286         return -1;
287     }
288
289     /*
290      * Ktls always reads full records.
291      * Also, we always act like read_ahead is set for DTLS.
292      */
293     if (!BIO_get_ktls_recv(s->rbio) && !s->rlayer.read_ahead
294         && !SSL_CONNECTION_IS_DTLS(s)) {
295         /* ignore max parameter */
296         max = n;
297     } else {
298         if (max < n)
299             max = n;
300         if (max > rb->len - rb->offset)
301             max = rb->len - rb->offset;
302     }
303
304     while (left < n) {
305         size_t bioread = 0;
306         int ret;
307
308         /*
309          * Now we have len+left bytes at the front of s->s3.rbuf.buf and
310          * need to read in more until we have len+n (up to len+max if
311          * possible)
312          */
313
314         clear_sys_error();
315         if (s->rbio != NULL) {
316             s->rwstate = SSL_READING;
317             ret = BIO_read(s->rbio, pkt + len + left, max - left);
318             if (ret >= 0)
319                 bioread = ret;
320             if (ret <= 0
321                     && !BIO_should_retry(s->rbio)
322                     && BIO_eof(s->rbio)) {
323                 if (s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) {
324                     SSL_set_shutdown(SSL_CONNECTION_GET_SSL(s),
325                                      SSL_RECEIVED_SHUTDOWN);
326                     s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
327                 } else {
328                     SSLfatal(s, SSL_AD_DECODE_ERROR,
329                              SSL_R_UNEXPECTED_EOF_WHILE_READING);
330                 }
331             }
332         } else {
333             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
334             ret = -1;
335         }
336
337         if (ret <= 0) {
338             rb->left = left;
339             if ((s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
340                 && !SSL_CONNECTION_IS_DTLS(s))
341                 if (len + left == 0)
342                     ssl3_release_read_buffer(s);
343             return ret;
344         }
345         left += bioread;
346         /*
347          * reads should *never* span multiple packets for DTLS because the
348          * underlying transport protocol is message oriented as opposed to
349          * byte oriented as in the TLS case.
350          */
351         if (SSL_CONNECTION_IS_DTLS(s)) {
352             if (n > left)
353                 n = left;       /* makes the while condition false */
354         }
355     }
356
357     /* done reading, now the book-keeping */
358     rb->offset += n;
359     rb->left = left - n;
360     s->rlayer.packet_length += n;
361     s->rwstate = SSL_NOTHING;
362     *readbytes = n;
363     return 1;
364 }
365
366 /*
367  * Call this to write data in records of type 'type' It will return <= 0 if
368  * not all data has been sent or non-blocking IO.
369  */
370 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
371                      size_t *written)
372 {
373     const unsigned char *buf = buf_;
374     size_t tot;
375     size_t n, max_send_fragment, split_send_fragment, maxpipes;
376 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
377     size_t nw;
378 #endif
379     SSL3_BUFFER *wb;
380     int i;
381     size_t tmpwrit;
382     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
383
384     if (s == NULL)
385         return -1;
386
387     wb = &s->rlayer.wbuf[0];
388     s->rwstate = SSL_NOTHING;
389     tot = s->rlayer.wnum;
390     /*
391      * ensure that if we end up with a smaller value of data to write out
392      * than the original len from a write which didn't complete for
393      * non-blocking I/O and also somehow ended up avoiding the check for
394      * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
395      * possible to end up with (len-tot) as a large number that will then
396      * promptly send beyond the end of the users buffer ... so we trap and
397      * report the error in a way the user will notice
398      */
399     if ((len < s->rlayer.wnum)
400         || ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
401         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
402         return -1;
403     }
404
405     if (s->early_data_state == SSL_EARLY_DATA_WRITING
406             && !ossl_early_data_count_ok(s, len, 0, 1)) {
407         /* SSLfatal() already called */
408         return -1;
409     }
410
411     s->rlayer.wnum = 0;
412
413     /*
414      * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
415      * into init unless we have writes pending - in which case we should finish
416      * doing that first.
417      */
418     if (wb->left == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
419                           || s->ext.extra_tickets_expected > 0))
420         ossl_statem_set_in_init(s, 1);
421
422     /*
423      * When writing early data on the server side we could be "in_init" in
424      * between receiving the EoED and the CF - but we don't want to handle those
425      * messages yet.
426      */
427     if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
428             && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
429         i = s->handshake_func(ssl);
430         /* SSLfatal() already called */
431         if (i < 0)
432             return i;
433         if (i == 0) {
434             return -1;
435         }
436     }
437
438     /*
439      * first check if there is a SSL3_BUFFER still being written out.  This
440      * will happen with non blocking IO
441      */
442     if (wb->left != 0) {
443         /* SSLfatal() already called if appropriate */
444         i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot,
445                                &tmpwrit);
446         if (i <= 0) {
447             /* XXX should we ssl3_release_write_buffer if i<0? */
448             s->rlayer.wnum = tot;
449             return i;
450         }
451         tot += tmpwrit;               /* this might be last fragment */
452     }
453 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
454     /*
455      * Depending on platform multi-block can deliver several *times*
456      * better performance. Downside is that it has to allocate
457      * jumbo buffer to accommodate up to 8 records, but the
458      * compromise is considered worthy.
459      */
460     if (type == SSL3_RT_APPLICATION_DATA
461             && len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s))
462             && s->compress == NULL
463             && s->msg_callback == NULL
464             && !SSL_WRITE_ETM(s)
465             && SSL_USE_EXPLICIT_IV(s)
466             && !BIO_get_ktls_send(s->wbio)
467             && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
468                 & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0) {
469         unsigned char aad[13];
470         EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
471         size_t packlen;
472         int packleni;
473
474         /* minimize address aliasing conflicts */
475         if ((max_send_fragment & 0xfff) == 0)
476             max_send_fragment -= 512;
477
478         if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
479             ssl3_release_write_buffer(s);
480
481             packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
482                                           EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
483                                           (int)max_send_fragment, NULL);
484
485             if (len >= 8 * max_send_fragment)
486                 packlen *= 8;
487             else
488                 packlen *= 4;
489
490             if (!ssl3_setup_write_buffer(s, 1, packlen)) {
491                 /* SSLfatal() already called */
492                 return -1;
493             }
494         } else if (tot == len) { /* done? */
495             /* free jumbo buffer */
496             ssl3_release_write_buffer(s);
497             *written = tot;
498             return 1;
499         }
500
501         n = (len - tot);
502         for (;;) {
503             if (n < 4 * max_send_fragment) {
504                 /* free jumbo buffer */
505                 ssl3_release_write_buffer(s);
506                 break;
507             }
508
509             if (s->s3.alert_dispatch) {
510                 i = ssl->method->ssl_dispatch_alert(ssl);
511                 if (i <= 0) {
512                     /* SSLfatal() already called if appropriate */
513                     s->rlayer.wnum = tot;
514                     return i;
515                 }
516             }
517
518             if (n >= 8 * max_send_fragment)
519                 nw = max_send_fragment * (mb_param.interleave = 8);
520             else
521                 nw = max_send_fragment * (mb_param.interleave = 4);
522
523             memcpy(aad, s->rlayer.write_sequence, 8);
524             aad[8] = type;
525             aad[9] = (unsigned char)(s->version >> 8);
526             aad[10] = (unsigned char)(s->version);
527             aad[11] = 0;
528             aad[12] = 0;
529             mb_param.out = NULL;
530             mb_param.inp = aad;
531             mb_param.len = nw;
532
533             packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
534                                           EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
535                                           sizeof(mb_param), &mb_param);
536             packlen = (size_t)packleni;
537             if (packleni <= 0 || packlen > wb->len) { /* never happens */
538                 /* free jumbo buffer */
539                 ssl3_release_write_buffer(s);
540                 break;
541             }
542
543             mb_param.out = wb->buf;
544             mb_param.inp = &buf[tot];
545             mb_param.len = nw;
546
547             if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
548                                     EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
549                                     sizeof(mb_param), &mb_param) <= 0)
550                 return -1;
551
552             s->rlayer.write_sequence[7] += mb_param.interleave;
553             if (s->rlayer.write_sequence[7] < mb_param.interleave) {
554                 int j = 6;
555                 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
556             }
557
558             wb->offset = 0;
559             wb->left = packlen;
560
561             s->rlayer.wpend_tot = nw;
562             s->rlayer.wpend_buf = &buf[tot];
563             s->rlayer.wpend_type = type;
564             s->rlayer.wpend_ret = nw;
565
566             i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
567             if (i <= 0) {
568                 /* SSLfatal() already called if appropriate */
569                 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
570                     /* free jumbo buffer */
571                     ssl3_release_write_buffer(s);
572                 }
573                 s->rlayer.wnum = tot;
574                 return i;
575             }
576             if (tmpwrit == n) {
577                 /* free jumbo buffer */
578                 ssl3_release_write_buffer(s);
579                 *written = tot + tmpwrit;
580                 return 1;
581             }
582             n -= tmpwrit;
583             tot += tmpwrit;
584         }
585     } else
586 #endif  /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
587     if (tot == len) {           /* done? */
588         if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_CONNECTION_IS_DTLS(s))
589             ssl3_release_write_buffer(s);
590
591         *written = tot;
592         return 1;
593     }
594
595     n = (len - tot);
596
597     max_send_fragment = ssl_get_max_send_fragment(s);
598     split_send_fragment = ssl_get_split_send_fragment(s);
599     /*
600      * If max_pipelines is 0 then this means "undefined" and we default to
601      * 1 pipeline. Similarly if the cipher does not support pipelined
602      * processing then we also only use 1 pipeline, or if we're not using
603      * explicit IVs
604      */
605     maxpipes = s->max_pipelines;
606     if (maxpipes > SSL_MAX_PIPELINES) {
607         /*
608          * We should have prevented this when we set max_pipelines so we
609          * shouldn't get here
610          */
611         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
612         return -1;
613     }
614     if (maxpipes == 0
615         || s->enc_write_ctx == NULL
616         || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
617             & EVP_CIPH_FLAG_PIPELINE) == 0
618         || !SSL_USE_EXPLICIT_IV(s))
619         maxpipes = 1;
620     if (max_send_fragment == 0
621             || split_send_fragment == 0
622             || split_send_fragment > max_send_fragment) {
623         /*
624          * We should have prevented this when we set/get the split and max send
625          * fragments so we shouldn't get here
626          */
627         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
628         return -1;
629     }
630
631     for (;;) {
632         size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
633         size_t numpipes, j;
634
635         if (n == 0)
636             numpipes = 1;
637         else
638             numpipes = ((n - 1) / split_send_fragment) + 1;
639         if (numpipes > maxpipes)
640             numpipes = maxpipes;
641
642         if (n / numpipes >= max_send_fragment) {
643             /*
644              * We have enough data to completely fill all available
645              * pipelines
646              */
647             for (j = 0; j < numpipes; j++) {
648                 pipelens[j] = max_send_fragment;
649             }
650         } else {
651             /* We can partially fill all available pipelines */
652             tmppipelen = n / numpipes;
653             remain = n % numpipes;
654             for (j = 0; j < numpipes; j++) {
655                 pipelens[j] = tmppipelen;
656                 if (j < remain)
657                     pipelens[j]++;
658             }
659         }
660
661         i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0,
662                           &tmpwrit);
663         if (i <= 0) {
664             /* SSLfatal() already called if appropriate */
665             /* XXX should we ssl3_release_write_buffer if i<0? */
666             s->rlayer.wnum = tot;
667             return i;
668         }
669
670         if (tmpwrit == n ||
671             (type == SSL3_RT_APPLICATION_DATA &&
672              (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
673             /*
674              * next chunk of data should get another prepended empty fragment
675              * in ciphersuites with known-IV weakness:
676              */
677             s->s3.empty_fragment_done = 0;
678
679             if (tmpwrit == n
680                     && (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
681                     && !SSL_CONNECTION_IS_DTLS(s))
682                 ssl3_release_write_buffer(s);
683
684             *written = tot + tmpwrit;
685             return 1;
686         }
687
688         n -= tmpwrit;
689         tot += tmpwrit;
690     }
691 }
692
693 int do_ssl3_write(SSL_CONNECTION *s, int type, const unsigned char *buf,
694                   size_t *pipelens, size_t numpipes,
695                   int create_empty_fragment, size_t *written)
696 {
697     WPACKET pkt[SSL_MAX_PIPELINES];
698     SSL3_RECORD wr[SSL_MAX_PIPELINES];
699     WPACKET *thispkt;
700     SSL3_RECORD *thiswr;
701     unsigned char *recordstart;
702     int i, mac_size, clear = 0;
703     size_t prefix_len = 0;
704     int eivlen = 0;
705     size_t align = 0;
706     SSL3_BUFFER *wb;
707     SSL_SESSION *sess;
708     size_t totlen = 0, len, wpinited = 0;
709     size_t j;
710     int using_ktls;
711     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
712
713     for (j = 0; j < numpipes; j++)
714         totlen += pipelens[j];
715     /*
716      * first check if there is a SSL3_BUFFER still being written out.  This
717      * will happen with non blocking IO
718      */
719     if (RECORD_LAYER_write_pending(&s->rlayer)) {
720         /* Calls SSLfatal() as required */
721         return ssl3_write_pending(s, type, buf, totlen, written);
722     }
723
724     /* If we have an alert to send, lets send it */
725     if (s->s3.alert_dispatch) {
726         i = ssl->method->ssl_dispatch_alert(ssl);
727         if (i <= 0) {
728             /* SSLfatal() already called if appropriate */
729             return i;
730         }
731         /* if it went, fall through and send more stuff */
732     }
733
734     if (s->rlayer.numwpipes < numpipes) {
735         if (!ssl3_setup_write_buffer(s, numpipes, 0)) {
736             /* SSLfatal() already called */
737             return -1;
738         }
739     }
740
741     if (totlen == 0 && !create_empty_fragment)
742         return 0;
743
744     sess = s->session;
745
746     if ((sess == NULL)
747             || (s->enc_write_ctx == NULL)
748             || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
749         clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
750         mac_size = 0;
751     } else {
752         mac_size = EVP_MD_CTX_get_size(s->write_hash);
753         if (mac_size < 0) {
754             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
755             goto err;
756         }
757     }
758
759     /*
760      * 'create_empty_fragment' is true only when this function calls itself
761      */
762     if (!clear && !create_empty_fragment && !s->s3.empty_fragment_done) {
763         /*
764          * countermeasure against known-IV weakness in CBC ciphersuites (see
765          * http://www.openssl.org/~bodo/tls-cbc.txt)
766          */
767
768         if (s->s3.need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
769             /*
770              * recursive function call with 'create_empty_fragment' set; this
771              * prepares and buffers the data for an empty fragment (these
772              * 'prefix_len' bytes are sent out later together with the actual
773              * payload)
774              */
775             size_t tmppipelen = 0;
776             int ret;
777
778             ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len);
779             if (ret <= 0) {
780                 /* SSLfatal() already called if appropriate */
781                 goto err;
782             }
783
784             if (prefix_len >
785                 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
786                 /* insufficient space */
787                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
788                 goto err;
789             }
790         }
791
792         s->s3.empty_fragment_done = 1;
793     }
794
795     using_ktls = BIO_get_ktls_send(s->wbio);
796     if (using_ktls) {
797         /*
798          * ktls doesn't modify the buffer, but to avoid a warning we need to
799          * discard the const qualifier.
800          * This doesn't leak memory because the buffers have been released when
801          * switching to ktls.
802          */
803         SSL3_BUFFER_set_buf(&s->rlayer.wbuf[0], (unsigned char *)buf);
804         SSL3_BUFFER_set_offset(&s->rlayer.wbuf[0], 0);
805         SSL3_BUFFER_set_app_buffer(&s->rlayer.wbuf[0], 1);
806         goto wpacket_init_complete;
807     }
808
809     if (create_empty_fragment) {
810         wb = &s->rlayer.wbuf[0];
811 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
812         /*
813          * extra fragment would be couple of cipher blocks, which would be
814          * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
815          * payload, then we can just pretend we simply have two headers.
816          */
817         align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
818         align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
819 #endif
820         SSL3_BUFFER_set_offset(wb, align);
821         if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
822                                      SSL3_BUFFER_get_len(wb), 0)
823                 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
824             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
825             goto err;
826         }
827         wpinited = 1;
828     } else if (prefix_len) {
829         wb = &s->rlayer.wbuf[0];
830         if (!WPACKET_init_static_len(&pkt[0],
831                                      SSL3_BUFFER_get_buf(wb),
832                                      SSL3_BUFFER_get_len(wb), 0)
833                 || !WPACKET_allocate_bytes(&pkt[0], SSL3_BUFFER_get_offset(wb)
834                                                     + prefix_len, NULL)) {
835             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
836             goto err;
837         }
838         wpinited = 1;
839     } else {
840         for (j = 0; j < numpipes; j++) {
841             thispkt = &pkt[j];
842
843             wb = &s->rlayer.wbuf[j];
844 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
845             align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
846             align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
847 #endif
848             SSL3_BUFFER_set_offset(wb, align);
849             if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
850                                          SSL3_BUFFER_get_len(wb), 0)
851                     || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
852                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
853                 goto err;
854             }
855             wpinited++;
856         }
857     }
858
859     /* Explicit IV length, block ciphers appropriate version flag */
860     if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)
861         && !SSL_CONNECTION_TREAT_AS_TLS13(s)) {
862         int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
863         if (mode == EVP_CIPH_CBC_MODE) {
864             eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
865             if (eivlen <= 1)
866                 eivlen = 0;
867         } else if (mode == EVP_CIPH_GCM_MODE) {
868             /* Need explicit part of IV for GCM mode */
869             eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
870         } else if (mode == EVP_CIPH_CCM_MODE) {
871             eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
872         }
873     }
874
875  wpacket_init_complete:
876
877     totlen = 0;
878     /* Clear our SSL3_RECORD structures */
879     memset(wr, 0, sizeof(wr));
880     for (j = 0; j < numpipes; j++) {
881         unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
882                                                               : s->version;
883         unsigned char *compressdata = NULL;
884         size_t maxcomplen;
885         unsigned int rectype;
886
887         thispkt = &pkt[j];
888         thiswr = &wr[j];
889
890         /*
891          * In TLSv1.3, once encrypting, we always use application data for the
892          * record type
893          */
894         if (SSL_CONNECTION_TREAT_AS_TLS13(s)
895                 && s->enc_write_ctx != NULL
896                 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
897                     || type != SSL3_RT_ALERT))
898             rectype = SSL3_RT_APPLICATION_DATA;
899         else
900             rectype = type;
901         SSL3_RECORD_set_type(thiswr, rectype);
902
903         /*
904          * Some servers hang if initial client hello is larger than 256 bytes
905          * and record version number > TLS 1.0
906          */
907         if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
908                 && !s->renegotiate
909                 && TLS1_get_version(ssl) > TLS1_VERSION
910                 && s->hello_retry_request == SSL_HRR_NONE)
911             version = TLS1_VERSION;
912         SSL3_RECORD_set_rec_version(thiswr, version);
913
914         maxcomplen = pipelens[j];
915         if (s->compress != NULL)
916             maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
917
918         /*
919          * When using offload kernel will write the header.
920          * Otherwise write the header now
921          */
922         if (!using_ktls
923                 && (!WPACKET_put_bytes_u8(thispkt, rectype)
924                 || !WPACKET_put_bytes_u16(thispkt, version)
925                 || !WPACKET_start_sub_packet_u16(thispkt)
926                 || (eivlen > 0
927                     && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
928                 || (maxcomplen > 0
929                     && !WPACKET_reserve_bytes(thispkt, maxcomplen,
930                                               &compressdata)))) {
931             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
932             goto err;
933         }
934
935         /* lets setup the record stuff. */
936         SSL3_RECORD_set_data(thiswr, compressdata);
937         SSL3_RECORD_set_length(thiswr, pipelens[j]);
938         SSL3_RECORD_set_input(thiswr, (unsigned char *)&buf[totlen]);
939         totlen += pipelens[j];
940
941         /*
942          * we now 'read' from thiswr->input, thiswr->length bytes into
943          * thiswr->data
944          */
945
946         /* first we compress */
947         if (s->compress != NULL) {
948             if (!ssl3_do_compress(s, thiswr)
949                     || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
950                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
951                 goto err;
952             }
953         } else {
954             if (using_ktls) {
955                 SSL3_RECORD_reset_data(&wr[j]);
956             } else {
957                 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
958                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
959                     goto err;
960                 }
961                 SSL3_RECORD_reset_input(&wr[j]);
962             }
963         }
964
965         if (SSL_CONNECTION_TREAT_AS_TLS13(s)
966                 && !using_ktls
967                 && s->enc_write_ctx != NULL
968                 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
969                     || type != SSL3_RT_ALERT)) {
970             size_t rlen, max_send_fragment;
971
972             if (!WPACKET_put_bytes_u8(thispkt, type)) {
973                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
974                 goto err;
975             }
976             SSL3_RECORD_add_length(thiswr, 1);
977
978             /* Add TLS1.3 padding */
979             max_send_fragment = ssl_get_max_send_fragment(s);
980             rlen = SSL3_RECORD_get_length(thiswr);
981             if (rlen < max_send_fragment) {
982                 size_t padding = 0;
983                 size_t max_padding = max_send_fragment - rlen;
984                 if (s->record_padding_cb != NULL) {
985                     padding = s->record_padding_cb(ssl, type, rlen, s->record_padding_arg);
986                 } else if (s->block_padding > 0) {
987                     size_t mask = s->block_padding - 1;
988                     size_t remainder;
989
990                     /* optimize for power of 2 */
991                     if ((s->block_padding & mask) == 0)
992                         remainder = rlen & mask;
993                     else
994                         remainder = rlen % s->block_padding;
995                     /* don't want to add a block of padding if we don't have to */
996                     if (remainder == 0)
997                         padding = 0;
998                     else
999                         padding = s->block_padding - remainder;
1000                 }
1001                 if (padding > 0) {
1002                     /* do not allow the record to exceed max plaintext length */
1003                     if (padding > max_padding)
1004                         padding = max_padding;
1005                     if (!WPACKET_memset(thispkt, 0, padding)) {
1006                         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1007                                  ERR_R_INTERNAL_ERROR);
1008                         goto err;
1009                     }
1010                     SSL3_RECORD_add_length(thiswr, padding);
1011                 }
1012             }
1013         }
1014
1015         /*
1016          * we should still have the output to thiswr->data and the input from
1017          * wr->input. Length should be thiswr->length. thiswr->data still points
1018          * in the wb->buf
1019          */
1020
1021         if (!using_ktls && !SSL_WRITE_ETM(s) && mac_size != 0) {
1022             unsigned char *mac;
1023
1024             if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1025                     || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
1026                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1027                 goto err;
1028             }
1029         }
1030
1031         /*
1032          * Reserve some bytes for any growth that may occur during encryption.
1033          * This will be at most one cipher block or the tag length if using
1034          * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
1035          */
1036         if (!using_ktls) {
1037             if (!WPACKET_reserve_bytes(thispkt,
1038                                         SSL_RT_MAX_CIPHER_BLOCK_SIZE,
1039                                         NULL)
1040                 /*
1041                  * We also need next the amount of bytes written to this
1042                  * sub-packet
1043                  */
1044                 || !WPACKET_get_length(thispkt, &len)) {
1045             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1046             goto err;
1047             }
1048
1049             /* Get a pointer to the start of this record excluding header */
1050             recordstart = WPACKET_get_curr(thispkt) - len;
1051             SSL3_RECORD_set_data(thiswr, recordstart);
1052             SSL3_RECORD_reset_input(thiswr);
1053             SSL3_RECORD_set_length(thiswr, len);
1054         }
1055     }
1056
1057     if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
1058         /*
1059          * We haven't actually negotiated the version yet, but we're trying to
1060          * send early data - so we need to use the tls13enc function.
1061          */
1062         if (tls13_enc(s, wr, numpipes, 1, NULL, mac_size) < 1) {
1063             if (!ossl_statem_in_error(s)) {
1064                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1065             }
1066             goto err;
1067         }
1068     } else {
1069         if (!using_ktls) {
1070             if (ssl->method->ssl3_enc->enc(s, wr, numpipes, 1, NULL,
1071                                          mac_size) < 1) {
1072                 if (!ossl_statem_in_error(s)) {
1073                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1074                 }
1075                 goto err;
1076             }
1077         }
1078     }
1079
1080     for (j = 0; j < numpipes; j++) {
1081         size_t origlen;
1082
1083         thispkt = &pkt[j];
1084         thiswr = &wr[j];
1085
1086         if (using_ktls)
1087             goto mac_done;
1088
1089         /* Allocate bytes for the encryption overhead */
1090         if (!WPACKET_get_length(thispkt, &origlen)
1091                    /* Encryption should never shrink the data! */
1092                 || origlen > thiswr->length
1093                 || (thiswr->length > origlen
1094                     && !WPACKET_allocate_bytes(thispkt,
1095                                                thiswr->length - origlen,
1096                                                NULL))) {
1097             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1098             goto err;
1099         }
1100         if (SSL_WRITE_ETM(s) && mac_size != 0) {
1101             unsigned char *mac;
1102
1103             if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1104                     || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
1105                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1106                 goto err;
1107             }
1108             SSL3_RECORD_add_length(thiswr, mac_size);
1109         }
1110
1111         if (!WPACKET_get_length(thispkt, &len)
1112                 || !WPACKET_close(thispkt)) {
1113             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1114             goto err;
1115         }
1116
1117         if (s->msg_callback) {
1118             recordstart = WPACKET_get_curr(thispkt) - len
1119                           - SSL3_RT_HEADER_LENGTH;
1120             s->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
1121                             SSL3_RT_HEADER_LENGTH, ssl,
1122                             s->msg_callback_arg);
1123
1124             if (SSL_CONNECTION_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
1125                 unsigned char ctype = type;
1126
1127                 s->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
1128                                 &ctype, 1, ssl, s->msg_callback_arg);
1129             }
1130         }
1131
1132         if (!WPACKET_finish(thispkt)) {
1133             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1134             goto err;
1135         }
1136
1137         /* header is added by the kernel when using offload */
1138         SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
1139
1140         if (create_empty_fragment) {
1141             /*
1142              * we are in a recursive call; just return the length, don't write
1143              * out anything here
1144              */
1145             if (j > 0) {
1146                 /* We should never be pipelining an empty fragment!! */
1147                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1148                 goto err;
1149             }
1150             *written = SSL3_RECORD_get_length(thiswr);
1151             return 1;
1152         }
1153
1154  mac_done:
1155         /*
1156          * we should now have thiswr->data pointing to the encrypted data, which
1157          * is thiswr->length long
1158          */
1159         SSL3_RECORD_set_type(thiswr, type); /* not needed but helps for
1160                                              * debugging */
1161
1162         /* now let's set up wb */
1163         SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
1164                              prefix_len + SSL3_RECORD_get_length(thiswr));
1165     }
1166
1167     /*
1168      * memorize arguments so that ssl3_write_pending can detect bad write
1169      * retries later
1170      */
1171     s->rlayer.wpend_tot = totlen;
1172     s->rlayer.wpend_buf = buf;
1173     s->rlayer.wpend_type = type;
1174     s->rlayer.wpend_ret = totlen;
1175
1176     /* we now just need to write the buffer */
1177     return ssl3_write_pending(s, type, buf, totlen, written);
1178  err:
1179     for (j = 0; j < wpinited; j++)
1180         WPACKET_cleanup(&pkt[j]);
1181     return -1;
1182 }
1183
1184 /* if SSL3_BUFFER_get_left() != 0, we need to call this
1185  *
1186  * Return values are as per SSL_write()
1187  */
1188 int ssl3_write_pending(SSL_CONNECTION *s, int type, const unsigned char *buf,
1189                        size_t len, size_t *written)
1190 {
1191     int i;
1192     SSL3_BUFFER *wb = s->rlayer.wbuf;
1193     size_t currbuf = 0;
1194     size_t tmpwrit = 0;
1195
1196     if ((s->rlayer.wpend_tot > len)
1197         || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
1198             && (s->rlayer.wpend_buf != buf))
1199         || (s->rlayer.wpend_type != type)) {
1200         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
1201         return -1;
1202     }
1203
1204     for (;;) {
1205         /* Loop until we find a buffer we haven't written out yet */
1206         if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
1207             && currbuf < s->rlayer.numwpipes - 1) {
1208             currbuf++;
1209             continue;
1210         }
1211         clear_sys_error();
1212         if (s->wbio != NULL) {
1213             s->rwstate = SSL_WRITING;
1214
1215             /*
1216              * To prevent coalescing of control and data messages,
1217              * such as in buffer_write, we flush the BIO
1218              */
1219             if (BIO_get_ktls_send(s->wbio) && type != SSL3_RT_APPLICATION_DATA) {
1220                 i = BIO_flush(s->wbio);
1221                 if (i <= 0)
1222                     return i;
1223                 BIO_set_ktls_ctrl_msg(s->wbio, type);
1224             }
1225             i = BIO_write(s->wbio, (char *)
1226                           &(SSL3_BUFFER_get_buf(&wb[currbuf])
1227                             [SSL3_BUFFER_get_offset(&wb[currbuf])]),
1228                           (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
1229             if (i >= 0)
1230                 tmpwrit = i;
1231         } else {
1232             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1233             i = -1;
1234         }
1235
1236         /*
1237          * When an empty fragment is sent on a connection using KTLS,
1238          * it is sent as a write of zero bytes.  If this zero byte
1239          * write succeeds, i will be 0 rather than a non-zero value.
1240          * Treat i == 0 as success rather than an error for zero byte
1241          * writes to permit this case.
1242          */
1243         if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(&wb[currbuf])) {
1244             SSL3_BUFFER_set_left(&wb[currbuf], 0);
1245             SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1246             if (currbuf + 1 < s->rlayer.numwpipes)
1247                 continue;
1248             s->rwstate = SSL_NOTHING;
1249             *written = s->rlayer.wpend_ret;
1250             return 1;
1251         } else if (i <= 0) {
1252             if (SSL_CONNECTION_IS_DTLS(s)) {
1253                 /*
1254                  * For DTLS, just drop it. That's kind of the whole point in
1255                  * using a datagram service
1256                  */
1257                 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1258             }
1259             return i;
1260         }
1261         SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1262         SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit);
1263     }
1264 }
1265
1266 /*-
1267  * Return up to 'len' payload bytes received in 'type' records.
1268  * 'type' is one of the following:
1269  *
1270  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1271  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1272  *   -  0 (during a shutdown, no data has to be returned)
1273  *
1274  * If we don't have stored data to work from, read a SSL/TLS record first
1275  * (possibly multiple records if we still don't have anything to return).
1276  *
1277  * This function must handle any surprises the peer may have for us, such as
1278  * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1279  * messages are treated as if they were handshake messages *if* the |recvd_type|
1280  * argument is non NULL.
1281  * Also if record payloads contain fragments too small to process, we store
1282  * them until there is enough for the respective protocol (the record protocol
1283  * may use arbitrary fragmentation and even interleaving):
1284  *     Change cipher spec protocol
1285  *             just 1 byte needed, no need for keeping anything stored
1286  *     Alert protocol
1287  *             2 bytes needed (AlertLevel, AlertDescription)
1288  *     Handshake protocol
1289  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
1290  *             to detect unexpected Client Hello and Hello Request messages
1291  *             here, anything else is handled by higher layers
1292  *     Application data protocol
1293  *             none of our business
1294  */
1295 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
1296                     size_t len, int peek, size_t *readbytes)
1297 {
1298     int i, j, ret;
1299     size_t n, curr_rec, num_recs, totalbytes;
1300     SSL3_RECORD *rr;
1301     SSL3_BUFFER *rbuf;
1302     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
1303     int is_tls13;
1304     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1305
1306     is_tls13 = SSL_CONNECTION_IS_TLS13(s);
1307
1308     rbuf = &s->rlayer.rbuf;
1309
1310     if (!SSL3_BUFFER_is_initialised(rbuf)) {
1311         /* Not initialized yet */
1312         if (!ssl3_setup_read_buffer(s)) {
1313             /* SSLfatal() already called */
1314             return -1;
1315         }
1316     }
1317
1318     if ((type && (type != SSL3_RT_APPLICATION_DATA)
1319          && (type != SSL3_RT_HANDSHAKE)) || (peek
1320                                              && (type !=
1321                                                  SSL3_RT_APPLICATION_DATA))) {
1322         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1323         return -1;
1324     }
1325
1326     if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
1327         /* (partially) satisfy request from storage */
1328     {
1329         unsigned char *src = s->rlayer.handshake_fragment;
1330         unsigned char *dst = buf;
1331         unsigned int k;
1332
1333         /* peek == 0 */
1334         n = 0;
1335         while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1336             *dst++ = *src++;
1337             len--;
1338             s->rlayer.handshake_fragment_len--;
1339             n++;
1340         }
1341         /* move any remaining fragment bytes: */
1342         for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1343             s->rlayer.handshake_fragment[k] = *src++;
1344
1345         if (recvd_type != NULL)
1346             *recvd_type = SSL3_RT_HANDSHAKE;
1347
1348         *readbytes = n;
1349         return 1;
1350     }
1351
1352     /*
1353      * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1354      */
1355
1356     if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
1357         /* type == SSL3_RT_APPLICATION_DATA */
1358         i = s->handshake_func(ssl);
1359         /* SSLfatal() already called */
1360         if (i < 0)
1361             return i;
1362         if (i == 0)
1363             return -1;
1364     }
1365  start:
1366     s->rwstate = SSL_NOTHING;
1367
1368     /*-
1369      * For each record 'i' up to |num_recs]
1370      * rr[i].type     - is the type of record
1371      * rr[i].data,    - data
1372      * rr[i].off,     - offset into 'data' for next read
1373      * rr[i].length,  - number of bytes.
1374      */
1375     rr = s->rlayer.rrec;
1376     num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1377
1378     do {
1379         /* get new records if necessary */
1380         if (num_recs == 0) {
1381             ret = ssl3_get_record(s);
1382             if (ret <= 0) {
1383                 /* SSLfatal() already called if appropriate */
1384                 return ret;
1385             }
1386             num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1387             if (num_recs == 0) {
1388                 /* Shouldn't happen */
1389                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1390                 return -1;
1391             }
1392         }
1393         /* Skip over any records we have already read */
1394         for (curr_rec = 0;
1395              curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]);
1396              curr_rec++) ;
1397         if (curr_rec == num_recs) {
1398             RECORD_LAYER_set_numrpipes(&s->rlayer, 0);
1399             num_recs = 0;
1400             curr_rec = 0;
1401         }
1402     } while (num_recs == 0);
1403     rr = &rr[curr_rec];
1404
1405     if (s->rlayer.handshake_fragment_len > 0
1406             && SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE
1407             && SSL_CONNECTION_IS_TLS13(s)) {
1408         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1409                  SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
1410         return -1;
1411     }
1412
1413     /*
1414      * Reset the count of consecutive warning alerts if we've got a non-empty
1415      * record that isn't an alert.
1416      */
1417     if (SSL3_RECORD_get_type(rr) != SSL3_RT_ALERT
1418             && SSL3_RECORD_get_length(rr) != 0)
1419         s->rlayer.alert_count = 0;
1420
1421     /* we now have a packet which can be read and processed */
1422
1423     if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
1424                                   * reset by ssl3_get_finished */
1425         && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {
1426         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1427                  SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1428         return -1;
1429     }
1430
1431     /*
1432      * If the other end has shut down, throw anything we read away (even in
1433      * 'peek' mode)
1434      */
1435     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1436         SSL3_RECORD_set_length(rr, 0);
1437         s->rwstate = SSL_NOTHING;
1438         return 0;
1439     }
1440
1441     if (type == SSL3_RECORD_get_type(rr)
1442         || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1443             && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
1444             && !is_tls13)) {
1445         /*
1446          * SSL3_RT_APPLICATION_DATA or
1447          * SSL3_RT_HANDSHAKE or
1448          * SSL3_RT_CHANGE_CIPHER_SPEC
1449          */
1450         /*
1451          * make sure that we are not getting application data when we are
1452          * doing a handshake for the first time
1453          */
1454         if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
1455             && s->enc_read_ctx == NULL) {
1456             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
1457             return -1;
1458         }
1459
1460         if (type == SSL3_RT_HANDSHAKE
1461             && SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1462             && s->rlayer.handshake_fragment_len > 0) {
1463             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1464             return -1;
1465         }
1466
1467         if (recvd_type != NULL)
1468             *recvd_type = SSL3_RECORD_get_type(rr);
1469
1470         if (len == 0) {
1471             /*
1472              * Mark a zero length record as read. This ensures multiple calls to
1473              * SSL_read() with a zero length buffer will eventually cause
1474              * SSL_pending() to report data as being available.
1475              */
1476             if (SSL3_RECORD_get_length(rr) == 0)
1477                 SSL3_RECORD_set_read(rr);
1478             return 0;
1479         }
1480
1481         totalbytes = 0;
1482         do {
1483             if (len - totalbytes > SSL3_RECORD_get_length(rr))
1484                 n = SSL3_RECORD_get_length(rr);
1485             else
1486                 n = len - totalbytes;
1487
1488             memcpy(buf, &(rr->data[rr->off]), n);
1489             buf += n;
1490             if (peek) {
1491                 /* Mark any zero length record as consumed CVE-2016-6305 */
1492                 if (SSL3_RECORD_get_length(rr) == 0)
1493                     SSL3_RECORD_set_read(rr);
1494             } else {
1495                 if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
1496                     OPENSSL_cleanse(&(rr->data[rr->off]), n);
1497                 SSL3_RECORD_sub_length(rr, n);
1498                 SSL3_RECORD_add_off(rr, n);
1499                 if (SSL3_RECORD_get_length(rr) == 0) {
1500                     s->rlayer.rstate = SSL_ST_READ_HEADER;
1501                     SSL3_RECORD_set_off(rr, 0);
1502                     SSL3_RECORD_set_read(rr);
1503                 }
1504             }
1505             if (SSL3_RECORD_get_length(rr) == 0
1506                 || (peek && n == SSL3_RECORD_get_length(rr))) {
1507                 curr_rec++;
1508                 rr++;
1509             }
1510             totalbytes += n;
1511         } while (type == SSL3_RT_APPLICATION_DATA && curr_rec < num_recs
1512                  && totalbytes < len);
1513         if (totalbytes == 0) {
1514             /* We must have read empty records. Get more data */
1515             goto start;
1516         }
1517         if (!peek && curr_rec == num_recs
1518             && (s->mode & SSL_MODE_RELEASE_BUFFERS)
1519             && SSL3_BUFFER_get_left(rbuf) == 0)
1520             ssl3_release_read_buffer(s);
1521         *readbytes = totalbytes;
1522         return 1;
1523     }
1524
1525     /*
1526      * If we get here, then type != rr->type; if we have a handshake message,
1527      * then it was unexpected (Hello Request or Client Hello) or invalid (we
1528      * were actually expecting a CCS).
1529      */
1530
1531     /*
1532      * Lets just double check that we've not got an SSLv2 record
1533      */
1534     if (rr->rec_version == SSL2_VERSION) {
1535         /*
1536          * Should never happen. ssl3_get_record() should only give us an SSLv2
1537          * record back if this is the first packet and we are looking for an
1538          * initial ClientHello. Therefore |type| should always be equal to
1539          * |rr->type|. If not then something has gone horribly wrong
1540          */
1541         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1542         return -1;
1543     }
1544
1545     if (ssl->method->version == TLS_ANY_VERSION
1546         && (s->server || rr->type != SSL3_RT_ALERT)) {
1547         /*
1548          * If we've got this far and still haven't decided on what version
1549          * we're using then this must be a client side alert we're dealing
1550          * with. We shouldn't be receiving anything other than a ClientHello
1551          * if we are a server.
1552          */
1553         s->version = rr->rec_version;
1554         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1555         return -1;
1556     }
1557
1558     /*-
1559      * s->rlayer.handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
1560      * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1561      */
1562
1563     if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {
1564         unsigned int alert_level, alert_descr;
1565         unsigned char *alert_bytes = SSL3_RECORD_get_data(rr)
1566                                      + SSL3_RECORD_get_off(rr);
1567         PACKET alert;
1568
1569         if (!PACKET_buf_init(&alert, alert_bytes, SSL3_RECORD_get_length(rr))
1570                 || !PACKET_get_1(&alert, &alert_level)
1571                 || !PACKET_get_1(&alert, &alert_descr)
1572                 || PACKET_remaining(&alert) != 0) {
1573             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
1574             return -1;
1575         }
1576
1577         if (s->msg_callback)
1578             s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
1579                             s->msg_callback_arg);
1580
1581         if (s->info_callback != NULL)
1582             cb = s->info_callback;
1583         else if (ssl->ctx->info_callback != NULL)
1584             cb = ssl->ctx->info_callback;
1585
1586         if (cb != NULL) {
1587             j = (alert_level << 8) | alert_descr;
1588             cb(ssl, SSL_CB_READ_ALERT, j);
1589         }
1590
1591         if (alert_level == SSL3_AL_WARNING
1592                 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
1593             s->s3.warn_alert = alert_descr;
1594             SSL3_RECORD_set_read(rr);
1595
1596             s->rlayer.alert_count++;
1597             if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
1598                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1599                          SSL_R_TOO_MANY_WARN_ALERTS);
1600                 return -1;
1601             }
1602         }
1603
1604         /*
1605          * Apart from close_notify the only other warning alert in TLSv1.3
1606          * is user_cancelled - which we just ignore.
1607          */
1608         if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
1609             goto start;
1610         } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
1611                 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
1612             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1613             return 0;
1614         } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
1615             s->rwstate = SSL_NOTHING;
1616             s->s3.fatal_alert = alert_descr;
1617             SSLfatal_data(s, SSL_AD_NO_ALERT,
1618                           SSL_AD_REASON_OFFSET + alert_descr,
1619                           "SSL alert number %d", alert_descr);
1620             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1621             SSL3_RECORD_set_read(rr);
1622             SSL_CTX_remove_session(s->session_ctx, s->session);
1623             return 0;
1624         } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1625             /*
1626              * This is a warning but we receive it if we requested
1627              * renegotiation and the peer denied it. Terminate with a fatal
1628              * alert because if application tried to renegotiate it
1629              * presumably had a good reason and expects it to succeed. In
1630              * future we might have a renegotiation where we don't care if
1631              * the peer refused it where we carry on.
1632              */
1633             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
1634             return -1;
1635         } else if (alert_level == SSL3_AL_WARNING) {
1636             /* We ignore any other warning alert in TLSv1.2 and below */
1637             goto start;
1638         }
1639
1640         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
1641         return -1;
1642     }
1643
1644     if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
1645         if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
1646             BIO *rbio;
1647
1648             /*
1649              * We ignore any handshake messages sent to us unless they are
1650              * TLSv1.3 in which case we want to process them. For all other
1651              * handshake messages we can't do anything reasonable with them
1652              * because we are unable to write any response due to having already
1653              * sent close_notify.
1654              */
1655             if (!SSL_CONNECTION_IS_TLS13(s)) {
1656                 SSL3_RECORD_set_length(rr, 0);
1657                 SSL3_RECORD_set_read(rr);
1658
1659                 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
1660                     goto start;
1661
1662                 s->rwstate = SSL_READING;
1663                 rbio = SSL_get_rbio(ssl);
1664                 BIO_clear_retry_flags(rbio);
1665                 BIO_set_retry_read(rbio);
1666                 return -1;
1667             }
1668         } else {
1669             /*
1670              * The peer is continuing to send application data, but we have
1671              * already sent close_notify. If this was expected we should have
1672              * been called via SSL_read() and this would have been handled
1673              * above.
1674              * No alert sent because we already sent close_notify
1675              */
1676             SSL3_RECORD_set_length(rr, 0);
1677             SSL3_RECORD_set_read(rr);
1678             SSLfatal(s, SSL_AD_NO_ALERT,
1679                      SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
1680             return -1;
1681         }
1682     }
1683
1684     /*
1685      * For handshake data we have 'fragment' storage, so fill that so that we
1686      * can process the header at a fixed place. This is done after the
1687      * "SHUTDOWN" code above to avoid filling the fragment storage with data
1688      * that we're just going to discard.
1689      */
1690     if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
1691         size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
1692         unsigned char *dest = s->rlayer.handshake_fragment;
1693         size_t *dest_len = &s->rlayer.handshake_fragment_len;
1694
1695         n = dest_maxlen - *dest_len; /* available space in 'dest' */
1696         if (SSL3_RECORD_get_length(rr) < n)
1697             n = SSL3_RECORD_get_length(rr); /* available bytes */
1698
1699         /* now move 'n' bytes: */
1700         memcpy(dest + *dest_len,
1701                SSL3_RECORD_get_data(rr) + SSL3_RECORD_get_off(rr), n);
1702         SSL3_RECORD_add_off(rr, n);
1703         SSL3_RECORD_sub_length(rr, n);
1704         *dest_len += n;
1705         if (SSL3_RECORD_get_length(rr) == 0)
1706             SSL3_RECORD_set_read(rr);
1707
1708         if (*dest_len < dest_maxlen)
1709             goto start;     /* fragment was too small */
1710     }
1711
1712     if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
1713         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1714         return -1;
1715     }
1716
1717     /*
1718      * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1719      * protocol violation)
1720      */
1721     if ((s->rlayer.handshake_fragment_len >= 4)
1722             && !ossl_statem_get_in_handshake(s)) {
1723         int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
1724
1725         /* We found handshake data, so we're going back into init */
1726         ossl_statem_set_in_init(s, 1);
1727
1728         i = s->handshake_func(ssl);
1729         /* SSLfatal() already called if appropriate */
1730         if (i < 0)
1731             return i;
1732         if (i == 0) {
1733             return -1;
1734         }
1735
1736         /*
1737          * If we were actually trying to read early data and we found a
1738          * handshake message, then we don't want to continue to try and read
1739          * the application data any more. It won't be "early" now.
1740          */
1741         if (ined)
1742             return -1;
1743
1744         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1745             if (SSL3_BUFFER_get_left(rbuf) == 0) {
1746                 /* no read-ahead left? */
1747                 BIO *bio;
1748                 /*
1749                  * In the case where we try to read application data, but we
1750                  * trigger an SSL handshake, we return -1 with the retry
1751                  * option set.  Otherwise renegotiation may cause nasty
1752                  * problems in the blocking world
1753                  */
1754                 s->rwstate = SSL_READING;
1755                 bio = SSL_get_rbio(ssl);
1756                 BIO_clear_retry_flags(bio);
1757                 BIO_set_retry_read(bio);
1758                 return -1;
1759             }
1760         }
1761         goto start;
1762     }
1763
1764     switch (SSL3_RECORD_get_type(rr)) {
1765     default:
1766         /*
1767          * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1768          * TLS 1.2 says you MUST send an unexpected message alert. We use the
1769          * TLS 1.2 behaviour for all protocol versions to prevent issues where
1770          * no progress is being made and the peer continually sends unrecognised
1771          * record types, using up resources processing them.
1772          */
1773         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1774         return -1;
1775     case SSL3_RT_CHANGE_CIPHER_SPEC:
1776     case SSL3_RT_ALERT:
1777     case SSL3_RT_HANDSHAKE:
1778         /*
1779          * we already handled all of these, with the possible exception of
1780          * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1781          * that should not happen when type != rr->type
1782          */
1783         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1784         return -1;
1785     case SSL3_RT_APPLICATION_DATA:
1786         /*
1787          * At this point, we were expecting handshake data, but have
1788          * application data.  If the library was running inside ssl3_read()
1789          * (i.e. in_read_app_data is set) and it makes sense to read
1790          * application data at this point (session renegotiation not yet
1791          * started), we will indulge it.
1792          */
1793         if (ossl_statem_app_data_allowed(s)) {
1794             s->s3.in_read_app_data = 2;
1795             return -1;
1796         } else if (ossl_statem_skip_early_data(s)) {
1797             /*
1798              * This can happen after a client sends a CH followed by early_data,
1799              * but the server responds with a HelloRetryRequest. The server
1800              * reads the next record from the client expecting to find a
1801              * plaintext ClientHello but gets a record which appears to be
1802              * application data. The trial decrypt "works" because null
1803              * decryption was applied. We just skip it and move on to the next
1804              * record.
1805              */
1806             if (!ossl_early_data_count_ok(s, rr->length,
1807                                           EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1808                 /* SSLfatal() already called */
1809                 return -1;
1810             }
1811             SSL3_RECORD_set_read(rr);
1812             goto start;
1813         } else {
1814             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1815             return -1;
1816         }
1817     }
1818 }
1819
1820 void ssl3_record_sequence_update(unsigned char *seq)
1821 {
1822     int i;
1823
1824     for (i = 7; i >= 0; i--) {
1825         ++seq[i];
1826         if (seq[i] != 0)
1827             break;
1828     }
1829 }
1830
1831 /*
1832  * Returns true if the current rrec was sent in SSLv2 backwards compatible
1833  * format and false otherwise.
1834  */
1835 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1836 {
1837     return SSL3_RECORD_is_sslv2_record(&rl->rrec[0]);
1838 }
1839
1840 /*
1841  * Returns the length in bytes of the current rrec
1842  */
1843 size_t RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
1844 {
1845     return SSL3_RECORD_get_length(&rl->rrec[0]);
1846 }