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