Remove some unneccessary macros
[openssl.git] / ssl / record / s3_pkt.c
1 /* ssl/s3_pkt.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 (RECORD_LAYER));
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 #endif
449     SSL3_BUFFER *wb = &s->rlayer.wbuf;
450     int i;
451     unsigned int u_len = (unsigned int)len;
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 (wb->left != 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 (wb->buf == NULL)
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)wb->buf + 2 * SSL3_RT_HEADER_LENGTH;
758         align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
759 #endif
760         p = wb->buf + align;
761         wb->offset = align;
762     } else if (prefix_len) {
763         p = wb->buf + wb->offset + prefix_len;
764     } else {
765 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
766         align = (long)wb->buf + SSL3_RT_HEADER_LENGTH;
767         align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
768 #endif
769         p = wb->buf + align;
770         wb->offset = align;
771     }
772
773     /* write the header */
774
775     *(p++) = type & 0xff;
776     wr->type = 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     wr->data = p + eivlen;
810     wr->length = (int)len;
811     wr->input = (unsigned char *)buf;
812
813     /*
814      * we now 'read' from wr->input, wr->length bytes into wr->data
815      */
816
817     /* first we compress */
818     if (s->compress != NULL) {
819         if (!ssl3_do_compress(s)) {
820             SSLerr(SSL_F_DO_SSL3_WRITE, SSL_R_COMPRESSION_FAILURE);
821             goto err;
822         }
823     } else {
824         memcpy(wr->data, wr->input, wr->length);
825         wr->input = wr->data;
826     }
827
828     /*
829      * we should still have the output to wr->data and the input from
830      * wr->input.  Length should be wr->length. wr->data still points in the
831      * wb->buf
832      */
833
834     if (!SSL_USE_ETM(s) && mac_size != 0) {
835         if (s->method->ssl3_enc->mac(s, &(p[wr->length + eivlen]), 1) < 0)
836             goto err;
837         wr->length += mac_size;
838     }
839
840     wr->input = p;
841     wr->data = p;
842
843     if (eivlen) {
844         /*
845          * if (RAND_pseudo_bytes(p, eivlen) <= 0) goto err;
846          */
847         wr->length += eivlen;
848     }
849
850     if (s->method->ssl3_enc->enc(s, 1) < 1)
851         goto err;
852
853     if (SSL_USE_ETM(s) && mac_size != 0) {
854         if (s->method->ssl3_enc->mac(s, p + wr->length, 1) < 0)
855             goto err;
856         wr->length += mac_size;
857     }
858
859     /* record length after mac and block padding */
860     s2n(wr->length, plen);
861
862     if (s->msg_callback)
863         s->msg_callback(1, 0, SSL3_RT_HEADER, plen - 5, 5, s,
864                         s->msg_callback_arg);
865
866     /*
867      * we should now have wr->data pointing to the encrypted data, which is
868      * wr->length long
869      */
870     wr->type = type;            /* not needed but helps for debugging */
871     wr->length += SSL3_RT_HEADER_LENGTH;
872
873     if (create_empty_fragment) {
874         /*
875          * we are in a recursive call; just return the length, don't write
876          * out anything here
877          */
878         return wr->length;
879     }
880
881     /* now let's set up wb */
882     wb->left = prefix_len + wr->length;
883
884     /*
885      * memorize arguments so that ssl3_write_pending can detect bad write
886      * retries later
887      */
888     s->rlayer.wpend_tot = len;
889     s->rlayer.wpend_buf = buf;
890     s->rlayer.wpend_type = type;
891     s->rlayer.wpend_ret = len;
892
893     /* we now just need to write the buffer */
894     return ssl3_write_pending(s, type, buf, len);
895  err:
896     return -1;
897 }
898
899 /* if s->s3->wbuf.left != 0, we need to call this */
900 int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
901                        unsigned int len)
902 {
903     int i;
904     SSL3_BUFFER *wb = &s->rlayer.wbuf;
905
906 /* XXXX */
907     if ((s->rlayer.wpend_tot > (int)len)
908         || ((s->rlayer.wpend_buf != buf) &&
909             !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
910         || (s->rlayer.wpend_type != type)) {
911         SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BAD_WRITE_RETRY);
912         return (-1);
913     }
914
915     for (;;) {
916         clear_sys_error();
917         if (s->wbio != NULL) {
918             s->rwstate = SSL_WRITING;
919             i = BIO_write(s->wbio,
920                           (char *)&(wb->buf[wb->offset]),
921                           (unsigned int)wb->left);
922         } else {
923             SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BIO_NOT_SET);
924             i = -1;
925         }
926         if (i == wb->left) {
927             wb->left = 0;
928             wb->offset += i;
929             s->rwstate = SSL_NOTHING;
930             return (s->rlayer.wpend_ret);
931         } else if (i <= 0) {
932             if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER) {
933                 /*
934                  * For DTLS, just drop it. That's kind of the whole point in
935                  * using a datagram service
936                  */
937                 wb->left = 0;
938             }
939             return (i);
940         }
941         wb->offset += i;
942         wb->left -= i;
943     }
944 }
945
946 /*-
947  * Return up to 'len' payload bytes received in 'type' records.
948  * 'type' is one of the following:
949  *
950  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
951  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
952  *   -  0 (during a shutdown, no data has to be returned)
953  *
954  * If we don't have stored data to work from, read a SSL/TLS record first
955  * (possibly multiple records if we still don't have anything to return).
956  *
957  * This function must handle any surprises the peer may have for us, such as
958  * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
959  * a surprise, but handled as if it were), or renegotiation requests.
960  * Also if record payloads contain fragments too small to process, we store
961  * them until there is enough for the respective protocol (the record protocol
962  * may use arbitrary fragmentation and even interleaving):
963  *     Change cipher spec protocol
964  *             just 1 byte needed, no need for keeping anything stored
965  *     Alert protocol
966  *             2 bytes needed (AlertLevel, AlertDescription)
967  *     Handshake protocol
968  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
969  *             to detect unexpected Client Hello and Hello Request messages
970  *             here, anything else is handled by higher layers
971  *     Application data protocol
972  *             none of our business
973  */
974 int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
975 {
976     int al, i, j, ret;
977     unsigned int n;
978     SSL3_RECORD *rr;
979     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
980
981     if (!SSL3_BUFFER_is_initialised(&s->rlayer.rbuf)) {
982         /* Not initialized yet */
983         if (!ssl3_setup_read_buffer(s))
984             return (-1);
985     }
986
987     if ((type && (type != SSL3_RT_APPLICATION_DATA)
988          && (type != SSL3_RT_HANDSHAKE)) || (peek
989                                              && (type !=
990                                                  SSL3_RT_APPLICATION_DATA))) {
991         SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
992         return -1;
993     }
994
995     if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
996         /* (partially) satisfy request from storage */
997     {
998         unsigned char *src = s->rlayer.handshake_fragment;
999         unsigned char *dst = buf;
1000         unsigned int k;
1001
1002         /* peek == 0 */
1003         n = 0;
1004         while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1005             *dst++ = *src++;
1006             len--;
1007             s->rlayer.handshake_fragment_len--;
1008             n++;
1009         }
1010         /* move any remaining fragment bytes: */
1011         for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1012             s->rlayer.handshake_fragment[k] = *src++;
1013         return n;
1014     }
1015
1016     /*
1017      * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1018      */
1019
1020     if (!s->in_handshake && SSL_in_init(s)) {
1021         /* type == SSL3_RT_APPLICATION_DATA */
1022         i = s->handshake_func(s);
1023         if (i < 0)
1024             return (i);
1025         if (i == 0) {
1026             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1027             return (-1);
1028         }
1029     }
1030  start:
1031     s->rwstate = SSL_NOTHING;
1032
1033     /*-
1034      * s->s3->rrec.type         - is the type of record
1035      * s->s3->rrec.data,    - data
1036      * s->s3->rrec.off,     - offset into 'data' for next read
1037      * s->s3->rrec.length,  - number of bytes.
1038      */
1039     rr = &s->rlayer.rrec;
1040
1041     /* get new packet if necessary */
1042     if ((rr->length == 0) || (s->rlayer.rstate == SSL_ST_READ_BODY)) {
1043         ret = ssl3_get_record(s);
1044         if (ret <= 0)
1045             return (ret);
1046     }
1047
1048     /* we now have a packet which can be read and processed */
1049
1050     if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
1051                                    * reset by ssl3_get_finished */
1052         && (rr->type != SSL3_RT_HANDSHAKE)) {
1053         al = SSL_AD_UNEXPECTED_MESSAGE;
1054         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1055         goto f_err;
1056     }
1057
1058     /*
1059      * If the other end has shut down, throw anything we read away (even in
1060      * 'peek' mode)
1061      */
1062     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1063         rr->length = 0;
1064         s->rwstate = SSL_NOTHING;
1065         return (0);
1066     }
1067
1068     if (type == rr->type) {     /* SSL3_RT_APPLICATION_DATA or
1069                                  * SSL3_RT_HANDSHAKE */
1070         /*
1071          * make sure that we are not getting application data when we are
1072          * doing a handshake for the first time
1073          */
1074         if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
1075             (s->enc_read_ctx == NULL)) {
1076             al = SSL_AD_UNEXPECTED_MESSAGE;
1077             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
1078             goto f_err;
1079         }
1080
1081         if (len <= 0)
1082             return (len);
1083
1084         if ((unsigned int)len > rr->length)
1085             n = rr->length;
1086         else
1087             n = (unsigned int)len;
1088
1089         memcpy(buf, &(rr->data[rr->off]), n);
1090         if (!peek) {
1091             rr->length -= n;
1092             rr->off += n;
1093             if (rr->length == 0) {
1094                 s->rlayer.rstate = SSL_ST_READ_HEADER;
1095                 rr->off = 0;
1096                 if (s->mode & SSL_MODE_RELEASE_BUFFERS
1097                     && SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0)
1098                     ssl3_release_read_buffer(s);
1099             }
1100         }
1101         return (n);
1102     }
1103
1104     /*
1105      * If we get here, then type != rr->type; if we have a handshake message,
1106      * then it was unexpected (Hello Request or Client Hello).
1107      */
1108
1109     /*
1110      * In case of record types for which we have 'fragment' storage, fill
1111      * that so that we can process the data at a fixed place.
1112      */
1113     {
1114         unsigned int dest_maxlen = 0;
1115         unsigned char *dest = NULL;
1116         unsigned int *dest_len = NULL;
1117
1118         if (rr->type == SSL3_RT_HANDSHAKE) {
1119             dest_maxlen = sizeof s->rlayer.handshake_fragment;
1120             dest = s->rlayer.handshake_fragment;
1121             dest_len = &s->rlayer.handshake_fragment_len;
1122         } else if (rr->type == SSL3_RT_ALERT) {
1123             dest_maxlen = sizeof s->rlayer.alert_fragment;
1124             dest = s->rlayer.alert_fragment;
1125             dest_len = &s->rlayer.alert_fragment_len;
1126         }
1127 #ifndef OPENSSL_NO_HEARTBEATS
1128         else if (rr->type == TLS1_RT_HEARTBEAT) {
1129             /* We can ignore 0 return values */
1130             if(tls1_process_heartbeat(s, SSL3_RECORD_get_data(&s->rlayer.rrec),
1131                     SSL3_RECORD_get_length(&s->rlayer.rrec)) < 0) {
1132                 return -1;
1133             }
1134
1135             /* Exit and notify application to read again */
1136             rr->length = 0;
1137             s->rwstate = SSL_READING;
1138             BIO_clear_retry_flags(SSL_get_rbio(s));
1139             BIO_set_retry_read(SSL_get_rbio(s));
1140             return (-1);
1141         }
1142 #endif
1143
1144         if (dest_maxlen > 0) {
1145             n = dest_maxlen - *dest_len; /* available space in 'dest' */
1146             if (rr->length < n)
1147                 n = rr->length; /* available bytes */
1148
1149             /* now move 'n' bytes: */
1150             while (n-- > 0) {
1151                 dest[(*dest_len)++] = rr->data[rr->off++];
1152                 rr->length--;
1153             }
1154
1155             if (*dest_len < dest_maxlen)
1156                 goto start;     /* fragment was too small */
1157         }
1158     }
1159
1160     /*-
1161      * s->rlayer.handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
1162      * s->rlayer.alert_fragment_len == 2      iff  rr->type == SSL3_RT_ALERT.
1163      * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1164      */
1165
1166     /* If we are a client, check for an incoming 'Hello Request': */
1167     if ((!s->server) &&
1168         (s->rlayer.handshake_fragment_len >= 4) &&
1169         (s->rlayer.handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
1170         (s->session != NULL) && (s->session->cipher != NULL)) {
1171         s->rlayer.handshake_fragment_len = 0;
1172
1173         if ((s->rlayer.handshake_fragment[1] != 0) ||
1174             (s->rlayer.handshake_fragment[2] != 0) ||
1175             (s->rlayer.handshake_fragment[3] != 0)) {
1176             al = SSL_AD_DECODE_ERROR;
1177             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
1178             goto f_err;
1179         }
1180
1181         if (s->msg_callback)
1182             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1183                             s->rlayer.handshake_fragment, 4, s,
1184                             s->msg_callback_arg);
1185
1186         if (SSL_is_init_finished(s) &&
1187             !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1188             !s->s3->renegotiate) {
1189             ssl3_renegotiate(s);
1190             if (ssl3_renegotiate_check(s)) {
1191                 i = s->handshake_func(s);
1192                 if (i < 0)
1193                     return (i);
1194                 if (i == 0) {
1195                     SSLerr(SSL_F_SSL3_READ_BYTES,
1196                            SSL_R_SSL_HANDSHAKE_FAILURE);
1197                     return (-1);
1198                 }
1199
1200                 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1201                     if (SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0) {
1202                         /* no read-ahead left? */
1203                         BIO *bio;
1204                         /*
1205                          * In the case where we try to read application data,
1206                          * but we trigger an SSL handshake, we return -1 with
1207                          * the retry option set.  Otherwise renegotiation may
1208                          * cause nasty problems in the blocking world
1209                          */
1210                         s->rwstate = SSL_READING;
1211                         bio = SSL_get_rbio(s);
1212                         BIO_clear_retry_flags(bio);
1213                         BIO_set_retry_read(bio);
1214                         return (-1);
1215                     }
1216                 }
1217             }
1218         }
1219         /*
1220          * we either finished a handshake or ignored the request, now try
1221          * again to obtain the (application) data we were asked for
1222          */
1223         goto start;
1224     }
1225     /*
1226      * If we are a server and get a client hello when renegotiation isn't
1227      * allowed send back a no renegotiation alert and carry on. WARNING:
1228      * experimental code, needs reviewing (steve)
1229      */
1230     if (s->server &&
1231         SSL_is_init_finished(s) &&
1232         !s->s3->send_connection_binding &&
1233         (s->version > SSL3_VERSION) &&
1234         (s->rlayer.handshake_fragment_len >= 4) &&
1235         (s->rlayer.handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
1236         (s->session != NULL) && (s->session->cipher != NULL) &&
1237         !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
1238         rr->length = 0;
1239         ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1240         goto start;
1241     }
1242     if (s->rlayer.alert_fragment_len >= 2) {
1243         int alert_level = s->rlayer.alert_fragment[0];
1244         int alert_descr = s->rlayer.alert_fragment[1];
1245
1246         s->rlayer.alert_fragment_len = 0;
1247
1248         if (s->msg_callback)
1249             s->msg_callback(0, s->version, SSL3_RT_ALERT,
1250                             s->rlayer.alert_fragment, 2, s,
1251                             s->msg_callback_arg);
1252
1253         if (s->info_callback != NULL)
1254             cb = s->info_callback;
1255         else if (s->ctx->info_callback != NULL)
1256             cb = s->ctx->info_callback;
1257
1258         if (cb != NULL) {
1259             j = (alert_level << 8) | alert_descr;
1260             cb(s, SSL_CB_READ_ALERT, j);
1261         }
1262
1263         if (alert_level == SSL3_AL_WARNING) {
1264             s->s3->warn_alert = alert_descr;
1265             if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
1266                 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1267                 return (0);
1268             }
1269             /*
1270              * This is a warning but we receive it if we requested
1271              * renegotiation and the peer denied it. Terminate with a fatal
1272              * alert because if application tried to renegotiatie it
1273              * presumably had a good reason and expects it to succeed. In
1274              * future we might have a renegotiation where we don't care if
1275              * the peer refused it where we carry on.
1276              */
1277             else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1278                 al = SSL_AD_HANDSHAKE_FAILURE;
1279                 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION);
1280                 goto f_err;
1281             }
1282 #ifdef SSL_AD_MISSING_SRP_USERNAME
1283             else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)
1284                 return (0);
1285 #endif
1286         } else if (alert_level == SSL3_AL_FATAL) {
1287             char tmp[16];
1288
1289             s->rwstate = SSL_NOTHING;
1290             s->s3->fatal_alert = alert_descr;
1291             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
1292             BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
1293             ERR_add_error_data(2, "SSL alert number ", tmp);
1294             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1295             SSL_CTX_remove_session(s->ctx, s->session);
1296             return (0);
1297         } else {
1298             al = SSL_AD_ILLEGAL_PARAMETER;
1299             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
1300             goto f_err;
1301         }
1302
1303         goto start;
1304     }
1305
1306     if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
1307                                             * shutdown */
1308         s->rwstate = SSL_NOTHING;
1309         rr->length = 0;
1310         return (0);
1311     }
1312
1313     if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1314         /*
1315          * 'Change Cipher Spec' is just a single byte, so we know exactly
1316          * what the record payload has to look like
1317          */
1318         if ((rr->length != 1) || (rr->off != 0) ||
1319             (rr->data[0] != SSL3_MT_CCS)) {
1320             al = SSL_AD_ILLEGAL_PARAMETER;
1321             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC);
1322             goto f_err;
1323         }
1324
1325         /* Check we have a cipher to change to */
1326         if (s->s3->tmp.new_cipher == NULL) {
1327             al = SSL_AD_UNEXPECTED_MESSAGE;
1328             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1329             goto f_err;
1330         }
1331
1332         if (!(s->s3->flags & SSL3_FLAGS_CCS_OK)) {
1333             al = SSL_AD_UNEXPECTED_MESSAGE;
1334             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1335             goto f_err;
1336         }
1337
1338         s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
1339
1340         rr->length = 0;
1341
1342         if (s->msg_callback)
1343             s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
1344                             rr->data, 1, s, s->msg_callback_arg);
1345
1346         s->s3->change_cipher_spec = 1;
1347         if (!ssl3_do_change_cipher_spec(s))
1348             goto err;
1349         else
1350             goto start;
1351     }
1352
1353     /*
1354      * Unexpected handshake message (Client Hello, or protocol violation)
1355      */
1356     if ((s->rlayer.handshake_fragment_len >= 4) && !s->in_handshake) {
1357         if (((s->state & SSL_ST_MASK) == SSL_ST_OK) &&
1358             !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
1359             s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
1360             s->renegotiate = 1;
1361             s->new_session = 1;
1362         }
1363         i = s->handshake_func(s);
1364         if (i < 0)
1365             return (i);
1366         if (i == 0) {
1367             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1368             return (-1);
1369         }
1370
1371         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1372             if (SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0) {
1373                 /* no read-ahead left? */
1374                 BIO *bio;
1375                 /*
1376                  * In the case where we try to read application data, but we
1377                  * trigger an SSL handshake, we return -1 with the retry
1378                  * option set.  Otherwise renegotiation may cause nasty
1379                  * problems in the blocking world
1380                  */
1381                 s->rwstate = SSL_READING;
1382                 bio = SSL_get_rbio(s);
1383                 BIO_clear_retry_flags(bio);
1384                 BIO_set_retry_read(bio);
1385                 return (-1);
1386             }
1387         }
1388         goto start;
1389     }
1390
1391     switch (rr->type) {
1392     default:
1393         /*
1394          * TLS up to v1.1 just ignores unknown message types: TLS v1.2 give
1395          * an unexpected message alert.
1396          */
1397         if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION) {
1398             rr->length = 0;
1399             goto start;
1400         }
1401         al = SSL_AD_UNEXPECTED_MESSAGE;
1402         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1403         goto f_err;
1404     case SSL3_RT_CHANGE_CIPHER_SPEC:
1405     case SSL3_RT_ALERT:
1406     case SSL3_RT_HANDSHAKE:
1407         /*
1408          * we already handled all of these, with the possible exception of
1409          * SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not
1410          * happen when type != rr->type
1411          */
1412         al = SSL_AD_UNEXPECTED_MESSAGE;
1413         SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1414         goto f_err;
1415     case SSL3_RT_APPLICATION_DATA:
1416         /*
1417          * At this point, we were expecting handshake data, but have
1418          * application data.  If the library was running inside ssl3_read()
1419          * (i.e. in_read_app_data is set) and it makes sense to read
1420          * application data at this point (session renegotiation not yet
1421          * started), we will indulge it.
1422          */
1423         if (s->s3->in_read_app_data &&
1424             (s->s3->total_renegotiations != 0) &&
1425             (((s->state & SSL_ST_CONNECT) &&
1426               (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1427               (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
1428              ) || ((s->state & SSL_ST_ACCEPT) &&
1429                    (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
1430                    (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
1431              )
1432             )) {
1433             s->s3->in_read_app_data = 2;
1434             return (-1);
1435         } else {
1436             al = SSL_AD_UNEXPECTED_MESSAGE;
1437             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1438             goto f_err;
1439         }
1440     }
1441     /* not reached */
1442
1443  f_err:
1444     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1445  err:
1446     return (-1);
1447 }
1448
1449 void ssl3_record_sequence_update(unsigned char *seq)
1450 {
1451     int i;
1452
1453     for (i = 7; i >= 0; i--) {
1454         ++seq[i];
1455         if (seq[i] != 0)
1456             break;
1457     }
1458 }
1459
1460