Home | History | Annotate | Line # | Download | only in statem
statem_dtls.c revision 1.1
      1 /*
      2  * Copyright 2005-2025 The OpenSSL Project Authors. All Rights Reserved.
      3  *
      4  * Licensed under the Apache License 2.0 (the "License").  You may not use
      5  * this file except in compliance with the License.  You can obtain a copy
      6  * in the file LICENSE in the source distribution or at
      7  * https://www.openssl.org/source/license.html
      8  */
      9 
     10 #include <assert.h>
     11 #include <limits.h>
     12 #include <string.h>
     13 #include <stdio.h>
     14 #include "../ssl_local.h"
     15 #include "statem_local.h"
     16 #include "internal/cryptlib.h"
     17 #include "internal/ssl_unwrap.h"
     18 #include <openssl/buffer.h>
     19 
     20 #define RSMBLY_BITMASK_SIZE(msg_len) (((msg_len) + 7) / 8)
     21 
     22 #define RSMBLY_BITMASK_MARK(bitmask, start, end) { \
     23                         if ((end) - (start) <= 8) { \
     24                                 long ii; \
     25                                 for (ii = (start); ii < (end); ii++) bitmask[((ii) >> 3)] |= (1 << ((ii) & 7)); \
     26                         } else { \
     27                                 long ii; \
     28                                 bitmask[((start) >> 3)] |= bitmask_start_values[((start) & 7)]; \
     29                                 for (ii = (((start) >> 3) + 1); ii < ((((end) - 1)) >> 3); ii++) bitmask[ii] = 0xff; \
     30                                 bitmask[(((end) - 1) >> 3)] |= bitmask_end_values[((end) & 7)]; \
     31                         } }
     32 
     33 #define RSMBLY_BITMASK_IS_COMPLETE(bitmask, msg_len, is_complete) { \
     34                         long ii; \
     35                         is_complete = 1; \
     36                         if (bitmask[(((msg_len) - 1) >> 3)] != bitmask_end_values[((msg_len) & 7)]) is_complete = 0; \
     37                         if (is_complete) for (ii = (((msg_len) - 1) >> 3) - 1; ii >= 0 ; ii--) \
     38                                 if (bitmask[ii] != 0xff) { is_complete = 0; break; } }
     39 
     40 static const unsigned char bitmask_start_values[] = {
     41     0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80
     42 };
     43 static const unsigned char bitmask_end_values[] = {
     44     0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f
     45 };
     46 
     47 static void dtls1_fix_message_header(SSL_CONNECTION *s, size_t frag_off,
     48                                      size_t frag_len);
     49 static unsigned char *dtls1_write_message_header(SSL_CONNECTION *s,
     50                                                  unsigned char *p);
     51 static void dtls1_set_message_header_int(SSL_CONNECTION *s, unsigned char mt,
     52                                          size_t len,
     53                                          unsigned short seq_num,
     54                                          size_t frag_off,
     55                                          size_t frag_len);
     56 static int dtls_get_reassembled_message(SSL_CONNECTION *s, int *errtype,
     57                                         size_t *len);
     58 
     59 static hm_fragment *dtls1_hm_fragment_new(size_t frag_len, int reassembly)
     60 {
     61     hm_fragment *frag = NULL;
     62     unsigned char *buf = NULL;
     63     unsigned char *bitmask = NULL;
     64 
     65     if ((frag = OPENSSL_zalloc(sizeof(*frag))) == NULL)
     66         return NULL;
     67 
     68     if (frag_len) {
     69         if ((buf = OPENSSL_malloc(frag_len)) == NULL) {
     70             OPENSSL_free(frag);
     71             return NULL;
     72         }
     73     }
     74 
     75     /* zero length fragment gets zero frag->fragment */
     76     frag->fragment = buf;
     77 
     78     /* Initialize reassembly bitmask if necessary */
     79     if (reassembly) {
     80         bitmask = OPENSSL_zalloc(RSMBLY_BITMASK_SIZE(frag_len));
     81         if (bitmask == NULL) {
     82             OPENSSL_free(buf);
     83             OPENSSL_free(frag);
     84             return NULL;
     85         }
     86     }
     87 
     88     frag->reassembly = bitmask;
     89 
     90     return frag;
     91 }
     92 
     93 void dtls1_hm_fragment_free(hm_fragment *frag)
     94 {
     95     if (!frag)
     96         return;
     97 
     98     OPENSSL_free(frag->fragment);
     99     OPENSSL_free(frag->reassembly);
    100     OPENSSL_free(frag);
    101 }
    102 
    103 /*
    104  * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
    105  * SSL3_RT_CHANGE_CIPHER_SPEC)
    106  */
    107 int dtls1_do_write(SSL_CONNECTION *s, uint8_t type)
    108 {
    109     int ret;
    110     size_t written;
    111     size_t curr_mtu;
    112     int retry = 1;
    113     size_t len, frag_off, overhead, used_len;
    114     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
    115     SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
    116     uint8_t saved_payload[DTLS1_HM_HEADER_LENGTH];
    117 
    118     if (!dtls1_query_mtu(s))
    119         return -1;
    120 
    121     if (s->d1->mtu < dtls1_min_mtu(s))
    122         /* should have something reasonable now */
    123         return -1;
    124 
    125     if (s->init_off == 0 && type == SSL3_RT_HANDSHAKE) {
    126         if (!ossl_assert(s->init_num ==
    127                          s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH))
    128             return -1;
    129     }
    130 
    131     overhead = s->rlayer.wrlmethod->get_max_record_overhead(s->rlayer.wrl);
    132 
    133     frag_off = 0;
    134     s->rwstate = SSL_NOTHING;
    135 
    136     /* s->init_num shouldn't ever be < 0...but just in case */
    137     while (s->init_num > 0) {
    138         if (type == SSL3_RT_HANDSHAKE && s->init_off != 0) {
    139             /* We must be writing a fragment other than the first one */
    140 
    141             if (frag_off > 0) {
    142                 /* This is the first attempt at writing out this fragment */
    143 
    144                 if (s->init_off <= DTLS1_HM_HEADER_LENGTH) {
    145                     /*
    146                      * Each fragment that was already sent must at least have
    147                      * contained the message header plus one other byte.
    148                      * Therefore |init_off| must have progressed by at least
    149                      * |DTLS1_HM_HEADER_LENGTH + 1| bytes. If not something went
    150                      * wrong.
    151                      */
    152                     return -1;
    153                 }
    154 
    155                 /*
    156                  * Adjust |init_off| and |init_num| to allow room for a new
    157                  * message header for this fragment.
    158                  */
    159                 s->init_off -= DTLS1_HM_HEADER_LENGTH;
    160                 s->init_num += DTLS1_HM_HEADER_LENGTH;
    161             } else {
    162                 /*
    163                  * We must have been called again after a retry so use the
    164                  * fragment offset from our last attempt. We do not need
    165                  * to adjust |init_off| and |init_num| as above, because
    166                  * that should already have been done before the retry.
    167                  */
    168                 frag_off = s->d1->w_msg_hdr.frag_off;
    169             }
    170         }
    171 
    172         used_len = BIO_wpending(s->wbio) + overhead;
    173         if (s->d1->mtu > used_len)
    174             curr_mtu = s->d1->mtu - used_len;
    175         else
    176             curr_mtu = 0;
    177 
    178         if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
    179             /*
    180              * grr.. we could get an error if MTU picked was wrong
    181              */
    182             ret = BIO_flush(s->wbio);
    183             if (ret <= 0) {
    184                 s->rwstate = SSL_WRITING;
    185                 return ret;
    186             }
    187             if (s->d1->mtu > overhead + DTLS1_HM_HEADER_LENGTH) {
    188                 curr_mtu = s->d1->mtu - overhead;
    189             } else {
    190                 /* Shouldn't happen */
    191                 return -1;
    192             }
    193         }
    194 
    195         /*
    196          * We just checked that s->init_num > 0 so this cast should be safe
    197          */
    198         if (((unsigned int)s->init_num) > curr_mtu)
    199             len = curr_mtu;
    200         else
    201             len = s->init_num;
    202 
    203         if (len > ssl_get_max_send_fragment(s))
    204             len = ssl_get_max_send_fragment(s);
    205 
    206         /*
    207          * XDTLS: this function is too long.  split out the CCS part
    208          */
    209         if (type == SSL3_RT_HANDSHAKE) {
    210             if (len < DTLS1_HM_HEADER_LENGTH) {
    211                 /*
    212                  * len is so small that we really can't do anything sensible
    213                  * so fail
    214                  */
    215                 return -1;
    216             }
    217             dtls1_fix_message_header(s, frag_off, len - DTLS1_HM_HEADER_LENGTH);
    218 
    219             /*
    220              * Save the data that will be overwritten by
    221              * dtls1_write_messsage_header so no corruption occurs when using
    222              * a msg callback.
    223              */
    224             if (s->msg_callback && s->init_off != 0)
    225                 memcpy(saved_payload, &s->init_buf->data[s->init_off],
    226                        sizeof(saved_payload));
    227 
    228             dtls1_write_message_header(s,
    229                                        (unsigned char *)&s->init_buf->
    230                                        data[s->init_off]);
    231         }
    232 
    233         ret = dtls1_write_bytes(s, type, &s->init_buf->data[s->init_off], len,
    234                                 &written);
    235 
    236         if (type == SSL3_RT_HANDSHAKE && s->msg_callback && s->init_off != 0)
    237             memcpy(&s->init_buf->data[s->init_off], saved_payload,
    238                    sizeof(saved_payload));
    239 
    240         if (ret <= 0) {
    241             /*
    242              * might need to update MTU here, but we don't know which
    243              * previous packet caused the failure -- so can't really
    244              * retransmit anything.  continue as if everything is fine and
    245              * wait for an alert to handle the retransmit
    246              */
    247             if (retry && BIO_ctrl(SSL_get_wbio(ssl),
    248                                   BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0) {
    249                 if (!(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
    250                     if (!dtls1_query_mtu(s))
    251                         return -1;
    252                     /* Have one more go */
    253                     retry = 0;
    254                 } else
    255                     return -1;
    256             } else {
    257                 return -1;
    258             }
    259         } else {
    260 
    261             /*
    262              * bad if this assert fails, only part of the handshake message
    263              * got sent.  but why would this happen?
    264              */
    265             if (!ossl_assert(len == written))
    266                 return -1;
    267 
    268             /*
    269              * We should not exceed the MTU size. If compression is in use
    270              * then the max record overhead calculation is unreliable so we do
    271              * not check in that case. We use assert rather than ossl_assert
    272              * because in a production build, if this assert were ever to fail,
    273              * then the best thing to do is probably carry on regardless.
    274              */
    275             assert(s->s3.tmp.new_compression != NULL
    276                    || BIO_wpending(s->wbio) <= (int)s->d1->mtu);
    277 
    278             if (type == SSL3_RT_HANDSHAKE && !s->d1->retransmitting) {
    279                 /*
    280                  * should not be done for 'Hello Request's, but in that case
    281                  * we'll ignore the result anyway
    282                  */
    283                 unsigned char *p =
    284                     (unsigned char *)&s->init_buf->data[s->init_off];
    285                 const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
    286                 size_t xlen;
    287 
    288                 if (frag_off == 0 && s->version != DTLS1_BAD_VER) {
    289                     /*
    290                      * reconstruct message header is if it is being sent in
    291                      * single fragment
    292                      */
    293                     *p++ = msg_hdr->type;
    294                     l2n3(msg_hdr->msg_len, p);
    295                     s2n(msg_hdr->seq, p);
    296                     l2n3(0, p);
    297                     l2n3(msg_hdr->msg_len, p);
    298                     p -= DTLS1_HM_HEADER_LENGTH;
    299                     xlen = written;
    300                 } else {
    301                     p += DTLS1_HM_HEADER_LENGTH;
    302                     xlen = written - DTLS1_HM_HEADER_LENGTH;
    303                 }
    304 
    305                 if (!ssl3_finish_mac(s, p, xlen))
    306                     return -1;
    307             }
    308 
    309             if (written == s->init_num) {
    310                 if (s->msg_callback)
    311                     s->msg_callback(1, s->version, type, s->init_buf->data,
    312                                     s->init_off + s->init_num, ussl,
    313                                     s->msg_callback_arg);
    314 
    315                 s->init_off = 0; /* done writing this message */
    316                 s->init_num = 0;
    317 
    318                 return 1;
    319             }
    320             s->init_off += written;
    321             s->init_num -= written;
    322             written -= DTLS1_HM_HEADER_LENGTH;
    323             frag_off += written;
    324 
    325             /*
    326              * We save the fragment offset for the next fragment so we have it
    327              * available in case of an IO retry. We don't know the length of the
    328              * next fragment yet so just set that to 0 for now. It will be
    329              * updated again later.
    330              */
    331             dtls1_fix_message_header(s, frag_off, 0);
    332         }
    333     }
    334     return 0;
    335 }
    336 
    337 int dtls_get_message(SSL_CONNECTION *s, int *mt)
    338 {
    339     struct hm_header_st *msg_hdr;
    340     unsigned char *p;
    341     size_t msg_len;
    342     size_t tmplen;
    343     int errtype;
    344 
    345     msg_hdr = &s->d1->r_msg_hdr;
    346     memset(msg_hdr, 0, sizeof(*msg_hdr));
    347 
    348  again:
    349     if (!dtls_get_reassembled_message(s, &errtype, &tmplen)) {
    350         if (errtype == DTLS1_HM_BAD_FRAGMENT
    351                 || errtype == DTLS1_HM_FRAGMENT_RETRY) {
    352             /* bad fragment received */
    353             goto again;
    354         }
    355         return 0;
    356     }
    357 
    358     *mt = s->s3.tmp.message_type;
    359 
    360     p = (unsigned char *)s->init_buf->data;
    361 
    362     if (*mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
    363         if (s->msg_callback) {
    364             s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
    365                             p, 1, SSL_CONNECTION_GET_USER_SSL(s),
    366                             s->msg_callback_arg);
    367         }
    368         /*
    369          * This isn't a real handshake message so skip the processing below.
    370          */
    371         return 1;
    372     }
    373 
    374     msg_len = msg_hdr->msg_len;
    375 
    376     /* reconstruct message header */
    377     *(p++) = msg_hdr->type;
    378     l2n3(msg_len, p);
    379     s2n(msg_hdr->seq, p);
    380     l2n3(0, p);
    381     l2n3(msg_len, p);
    382 
    383     memset(msg_hdr, 0, sizeof(*msg_hdr));
    384 
    385     s->d1->handshake_read_seq++;
    386 
    387     s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
    388 
    389     return 1;
    390 }
    391 
    392 /*
    393  * Actually we already have the message body - but this is an opportunity for
    394  * DTLS to do any further processing it wants at the same point that TLS would
    395  * be asked for the message body.
    396  */
    397 int dtls_get_message_body(SSL_CONNECTION *s, size_t *len)
    398 {
    399     unsigned char *msg = (unsigned char *)s->init_buf->data;
    400     size_t msg_len = s->init_num + DTLS1_HM_HEADER_LENGTH;
    401 
    402     if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
    403         /* Nothing to be done */
    404         goto end;
    405     }
    406     /*
    407      * If receiving Finished, record MAC of prior handshake messages for
    408      * Finished verification.
    409      */
    410     if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
    411         /* SSLfatal() already called */
    412         return 0;
    413     }
    414 
    415     if (s->version == DTLS1_BAD_VER) {
    416         msg += DTLS1_HM_HEADER_LENGTH;
    417         msg_len -= DTLS1_HM_HEADER_LENGTH;
    418     }
    419 
    420     if (!ssl3_finish_mac(s, msg, msg_len))
    421         return 0;
    422 
    423     if (s->msg_callback)
    424         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
    425                         s->init_buf->data, s->init_num + DTLS1_HM_HEADER_LENGTH,
    426                         SSL_CONNECTION_GET_USER_SSL(s), s->msg_callback_arg);
    427 
    428  end:
    429     *len = s->init_num;
    430     return 1;
    431 }
    432 
    433 /*
    434  * dtls1_max_handshake_message_len returns the maximum number of bytes
    435  * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but
    436  * may be greater if the maximum certificate list size requires it.
    437  */
    438 static size_t dtls1_max_handshake_message_len(const SSL_CONNECTION *s)
    439 {
    440     size_t max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
    441     if (max_len < s->max_cert_list)
    442         return s->max_cert_list;
    443     return max_len;
    444 }
    445 
    446 static int dtls1_preprocess_fragment(SSL_CONNECTION *s,
    447                                      struct hm_header_st *msg_hdr)
    448 {
    449     size_t frag_off, frag_len, msg_len;
    450 
    451     msg_len = msg_hdr->msg_len;
    452     frag_off = msg_hdr->frag_off;
    453     frag_len = msg_hdr->frag_len;
    454 
    455     /* sanity checking */
    456     if ((frag_off + frag_len) > msg_len
    457             || msg_len > dtls1_max_handshake_message_len(s)) {
    458         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
    459         return 0;
    460     }
    461 
    462     if (s->d1->r_msg_hdr.frag_off == 0) { /* first fragment */
    463         /*
    464          * msg_len is limited to 2^24, but is effectively checked against
    465          * dtls_max_handshake_message_len(s) above
    466          */
    467         if (!BUF_MEM_grow_clean(s->init_buf, msg_len + DTLS1_HM_HEADER_LENGTH)) {
    468             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
    469             return 0;
    470         }
    471 
    472         s->s3.tmp.message_size = msg_len;
    473         s->d1->r_msg_hdr.msg_len = msg_len;
    474         s->s3.tmp.message_type = msg_hdr->type;
    475         s->d1->r_msg_hdr.type = msg_hdr->type;
    476         s->d1->r_msg_hdr.seq = msg_hdr->seq;
    477     } else if (msg_len != s->d1->r_msg_hdr.msg_len) {
    478         /*
    479          * They must be playing with us! BTW, failure to enforce upper limit
    480          * would open possibility for buffer overrun.
    481          */
    482         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
    483         return 0;
    484     }
    485 
    486     return 1;
    487 }
    488 
    489 /*
    490  * Returns 1 if there is a buffered fragment available, 0 if not, or -1 on a
    491  * fatal error.
    492  */
    493 static int dtls1_retrieve_buffered_fragment(SSL_CONNECTION *s, size_t *len)
    494 {
    495     /*-
    496      * (0) check whether the desired fragment is available
    497      * if so:
    498      * (1) copy over the fragment to s->init_buf->data[]
    499      * (2) update s->init_num
    500      */
    501     pitem *item;
    502     piterator iter;
    503     hm_fragment *frag;
    504     int ret;
    505     int chretran = 0;
    506 
    507     iter = pqueue_iterator(s->d1->buffered_messages);
    508     do {
    509         item = pqueue_next(&iter);
    510         if (item == NULL)
    511             return 0;
    512 
    513         frag = (hm_fragment *)item->data;
    514 
    515         if (frag->msg_header.seq < s->d1->handshake_read_seq) {
    516             pitem *next;
    517             hm_fragment *nextfrag;
    518 
    519             if (!s->server
    520                     || frag->msg_header.seq != 0
    521                     || s->d1->handshake_read_seq != 1
    522                     || s->statem.hand_state != DTLS_ST_SW_HELLO_VERIFY_REQUEST) {
    523                 /*
    524                  * This is a stale message that has been buffered so clear it.
    525                  * It is safe to pop this message from the queue even though
    526                  * we have an active iterator
    527                  */
    528                 pqueue_pop(s->d1->buffered_messages);
    529                 dtls1_hm_fragment_free(frag);
    530                 pitem_free(item);
    531                 item = NULL;
    532                 frag = NULL;
    533             } else {
    534                 /*
    535                  * We have fragments for a ClientHello without a cookie,
    536                  * even though we have sent a HelloVerifyRequest. It is possible
    537                  * that the HelloVerifyRequest got lost and this is a
    538                  * retransmission of the original ClientHello
    539                  */
    540                 next = pqueue_next(&iter);
    541                 if (next != NULL) {
    542                     nextfrag = (hm_fragment *)next->data;
    543                     if (nextfrag->msg_header.seq == s->d1->handshake_read_seq) {
    544                         /*
    545                         * We have fragments for both a ClientHello without
    546                         * cookie and one with. Ditch the one without.
    547                         */
    548                         pqueue_pop(s->d1->buffered_messages);
    549                         dtls1_hm_fragment_free(frag);
    550                         pitem_free(item);
    551                         item = next;
    552                         frag = nextfrag;
    553                     } else {
    554                         chretran = 1;
    555                     }
    556                 } else {
    557                     chretran = 1;
    558                 }
    559             }
    560         }
    561     } while (item == NULL);
    562 
    563     /* Don't return if reassembly still in progress */
    564     if (frag->reassembly != NULL)
    565         return 0;
    566 
    567     if (s->d1->handshake_read_seq == frag->msg_header.seq || chretran) {
    568         size_t frag_len = frag->msg_header.frag_len;
    569         pqueue_pop(s->d1->buffered_messages);
    570 
    571         /* Calls SSLfatal() as required */
    572         ret = dtls1_preprocess_fragment(s, &frag->msg_header);
    573 
    574         if (ret && frag->msg_header.frag_len > 0) {
    575             unsigned char *p =
    576                 (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
    577             memcpy(&p[frag->msg_header.frag_off], frag->fragment,
    578                    frag->msg_header.frag_len);
    579         }
    580 
    581         dtls1_hm_fragment_free(frag);
    582         pitem_free(item);
    583 
    584         if (ret) {
    585             if (chretran) {
    586                 /*
    587                  * We got a new ClientHello with a message sequence of 0.
    588                  * Reset the read/write sequences back to the beginning.
    589                  * We process it like this is the first time we've seen a
    590                  * ClientHello from the client.
    591                  */
    592                 s->d1->handshake_read_seq = 0;
    593                 s->d1->next_handshake_write_seq = 0;
    594             }
    595             *len = frag_len;
    596             return 1;
    597         }
    598 
    599         /* Fatal error */
    600         s->init_num = 0;
    601         return -1;
    602     } else {
    603         return 0;
    604     }
    605 }
    606 
    607 static int dtls1_reassemble_fragment(SSL_CONNECTION *s,
    608                                      const struct hm_header_st *msg_hdr)
    609 {
    610     hm_fragment *frag = NULL;
    611     pitem *item = NULL;
    612     int i = -1, is_complete;
    613     unsigned char seq64be[8];
    614     size_t frag_len = msg_hdr->frag_len;
    615     size_t readbytes;
    616     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
    617 
    618     if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len ||
    619         msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
    620         goto err;
    621 
    622     if (frag_len == 0) {
    623         return DTLS1_HM_FRAGMENT_RETRY;
    624     }
    625 
    626     /* Try to find item in queue */
    627     memset(seq64be, 0, sizeof(seq64be));
    628     seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
    629     seq64be[7] = (unsigned char)msg_hdr->seq;
    630     item = pqueue_find(s->d1->buffered_messages, seq64be);
    631 
    632     if (item == NULL) {
    633         frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
    634         if (frag == NULL)
    635             goto err;
    636         memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
    637         frag->msg_header.frag_len = frag->msg_header.msg_len;
    638         frag->msg_header.frag_off = 0;
    639     } else {
    640         frag = (hm_fragment *)item->data;
    641         if (frag->msg_header.msg_len != msg_hdr->msg_len) {
    642             item = NULL;
    643             frag = NULL;
    644             goto err;
    645         }
    646     }
    647 
    648     /*
    649      * If message is already reassembled, this must be a retransmit and can
    650      * be dropped. In this case item != NULL and so frag does not need to be
    651      * freed.
    652      */
    653     if (frag->reassembly == NULL) {
    654         unsigned char devnull[256];
    655 
    656         while (frag_len) {
    657             i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
    658                                             devnull,
    659                                             frag_len >
    660                                             sizeof(devnull) ? sizeof(devnull) :
    661                                             frag_len, 0, &readbytes);
    662             if (i <= 0)
    663                 goto err;
    664             frag_len -= readbytes;
    665         }
    666         return DTLS1_HM_FRAGMENT_RETRY;
    667     }
    668 
    669     /* read the body of the fragment (header has already been read */
    670     i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
    671                                     frag->fragment + msg_hdr->frag_off,
    672                                     frag_len, 0, &readbytes);
    673     if (i <= 0 || readbytes != frag_len)
    674         i = -1;
    675     if (i <= 0)
    676         goto err;
    677 
    678     RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
    679                         (long)(msg_hdr->frag_off + frag_len));
    680 
    681     if (!ossl_assert(msg_hdr->msg_len > 0))
    682         goto err;
    683     RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
    684                                is_complete);
    685 
    686     if (is_complete) {
    687         OPENSSL_free(frag->reassembly);
    688         frag->reassembly = NULL;
    689     }
    690 
    691     if (item == NULL) {
    692         item = pitem_new(seq64be, frag);
    693         if (item == NULL) {
    694             i = -1;
    695             goto err;
    696         }
    697 
    698         item = pqueue_insert(s->d1->buffered_messages, item);
    699         /*
    700          * pqueue_insert fails iff a duplicate item is inserted. However,
    701          * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
    702          * would have returned it and control would never have reached this
    703          * branch.
    704          */
    705         if (!ossl_assert(item != NULL))
    706             goto err;
    707     }
    708 
    709     return DTLS1_HM_FRAGMENT_RETRY;
    710 
    711  err:
    712     if (item == NULL)
    713         dtls1_hm_fragment_free(frag);
    714     return -1;
    715 }
    716 
    717 static int dtls1_process_out_of_seq_message(SSL_CONNECTION *s,
    718                                             const struct hm_header_st *msg_hdr)
    719 {
    720     int i = -1;
    721     hm_fragment *frag = NULL;
    722     pitem *item = NULL;
    723     unsigned char seq64be[8];
    724     size_t frag_len = msg_hdr->frag_len;
    725     size_t readbytes;
    726     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
    727 
    728     if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
    729         goto err;
    730 
    731     /* Try to find item in queue, to prevent duplicate entries */
    732     memset(seq64be, 0, sizeof(seq64be));
    733     seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
    734     seq64be[7] = (unsigned char)msg_hdr->seq;
    735     item = pqueue_find(s->d1->buffered_messages, seq64be);
    736 
    737     /*
    738      * If we already have an entry and this one is a fragment, don't discard
    739      * it and rather try to reassemble it.
    740      */
    741     if (item != NULL && frag_len != msg_hdr->msg_len)
    742         item = NULL;
    743 
    744     /*
    745      * Discard the message if sequence number was already there, is too far
    746      * in the future, already in the queue or if we received a FINISHED
    747      * before the SERVER_HELLO, which then must be a stale retransmit.
    748      */
    749     if (msg_hdr->seq <= s->d1->handshake_read_seq ||
    750         msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL ||
    751         (s->d1->handshake_read_seq == 0 && msg_hdr->type == SSL3_MT_FINISHED)) {
    752         unsigned char devnull[256];
    753 
    754         while (frag_len) {
    755             i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
    756                                             devnull,
    757                                             frag_len >
    758                                             sizeof(devnull) ? sizeof(devnull) :
    759                                             frag_len, 0, &readbytes);
    760             if (i <= 0)
    761                 goto err;
    762             frag_len -= readbytes;
    763         }
    764     } else {
    765         if (frag_len != msg_hdr->msg_len) {
    766             return dtls1_reassemble_fragment(s, msg_hdr);
    767         }
    768 
    769         if (frag_len > dtls1_max_handshake_message_len(s))
    770             goto err;
    771 
    772         frag = dtls1_hm_fragment_new(frag_len, 0);
    773         if (frag == NULL)
    774             goto err;
    775 
    776         memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
    777 
    778         if (frag_len) {
    779             /*
    780              * read the body of the fragment (header has already been read
    781              */
    782             i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
    783                                             frag->fragment, frag_len, 0,
    784                                             &readbytes);
    785             if (i<=0 || readbytes != frag_len)
    786                 i = -1;
    787             if (i <= 0)
    788                 goto err;
    789         }
    790 
    791         item = pitem_new(seq64be, frag);
    792         if (item == NULL)
    793             goto err;
    794 
    795         item = pqueue_insert(s->d1->buffered_messages, item);
    796         /*
    797          * pqueue_insert fails iff a duplicate item is inserted. However,
    798          * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
    799          * would have returned it. Then, either |frag_len| !=
    800          * |msg_hdr->msg_len| in which case |item| is set to NULL and it will
    801          * have been processed with |dtls1_reassemble_fragment|, above, or
    802          * the record will have been discarded.
    803          */
    804         if (!ossl_assert(item != NULL))
    805             goto err;
    806     }
    807 
    808     return DTLS1_HM_FRAGMENT_RETRY;
    809 
    810  err:
    811     if (item == NULL)
    812         dtls1_hm_fragment_free(frag);
    813     return 0;
    814 }
    815 
    816 static int dtls_get_reassembled_message(SSL_CONNECTION *s, int *errtype,
    817                                         size_t *len)
    818 {
    819     size_t mlen, frag_off, frag_len;
    820     int i, ret;
    821     uint8_t recvd_type;
    822     struct hm_header_st msg_hdr;
    823     size_t readbytes;
    824     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
    825     SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
    826     int chretran = 0;
    827     unsigned char *p;
    828 
    829     *errtype = 0;
    830 
    831     p = (unsigned char *)s->init_buf->data;
    832 
    833  redo:
    834     /* see if we have the required fragment already */
    835     ret = dtls1_retrieve_buffered_fragment(s, &frag_len);
    836     if (ret < 0) {
    837         /* SSLfatal() already called */
    838         return 0;
    839     }
    840     if (ret > 0) {
    841         s->init_num = frag_len;
    842         *len = frag_len;
    843         return 1;
    844     }
    845 
    846     /* read handshake message header */
    847     i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type, p,
    848                                     DTLS1_HM_HEADER_LENGTH, 0, &readbytes);
    849     if (i <= 0) {               /* nbio, or an error */
    850         s->rwstate = SSL_READING;
    851         *len = 0;
    852         return 0;
    853     }
    854     if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
    855         if (p[0] != SSL3_MT_CCS) {
    856             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
    857                      SSL_R_BAD_CHANGE_CIPHER_SPEC);
    858             goto f_err;
    859         }
    860 
    861         s->init_num = readbytes - 1;
    862         s->init_msg = s->init_buf->data + 1;
    863         s->s3.tmp.message_type = SSL3_MT_CHANGE_CIPHER_SPEC;
    864         s->s3.tmp.message_size = readbytes - 1;
    865         *len = readbytes - 1;
    866         return 1;
    867     }
    868 
    869     /* Handshake fails if message header is incomplete */
    870     if (readbytes != DTLS1_HM_HEADER_LENGTH) {
    871         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
    872         goto f_err;
    873     }
    874 
    875     /* parse the message fragment header */
    876     dtls1_get_message_header(p, &msg_hdr);
    877 
    878     mlen = msg_hdr.msg_len;
    879     frag_off = msg_hdr.frag_off;
    880     frag_len = msg_hdr.frag_len;
    881 
    882     /*
    883      * We must have at least frag_len bytes left in the record to be read.
    884      * Fragments must not span records.
    885      */
    886     if (frag_len > s->rlayer.tlsrecs[s->rlayer.curr_rec].length) {
    887         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);
    888         goto f_err;
    889     }
    890 
    891     /*
    892      * if this is a future (or stale) message it gets buffered
    893      * (or dropped)--no further processing at this time
    894      * While listening, we accept seq 1 (ClientHello with cookie)
    895      * although we're still expecting seq 0 (ClientHello)
    896      */
    897     if (msg_hdr.seq != s->d1->handshake_read_seq) {
    898         if (!s->server
    899                 || msg_hdr.seq != 0
    900                 || s->d1->handshake_read_seq != 1
    901                 || p[0] != SSL3_MT_CLIENT_HELLO
    902                 || s->statem.hand_state != DTLS_ST_SW_HELLO_VERIFY_REQUEST) {
    903             *errtype = dtls1_process_out_of_seq_message(s, &msg_hdr);
    904             return 0;
    905         }
    906         /*
    907          * We received a ClientHello and sent back a HelloVerifyRequest. We
    908          * now seem to have received a retransmitted initial ClientHello. That
    909          * is allowed (possibly our HelloVerifyRequest got lost).
    910          */
    911         chretran = 1;
    912     }
    913 
    914     if (frag_len && frag_len < mlen) {
    915         *errtype = dtls1_reassemble_fragment(s, &msg_hdr);
    916         return 0;
    917     }
    918 
    919     if (!s->server
    920             && s->d1->r_msg_hdr.frag_off == 0
    921             && s->statem.hand_state != TLS_ST_OK
    922             && p[0] == SSL3_MT_HELLO_REQUEST) {
    923         /*
    924          * The server may always send 'Hello Request' messages -- we are
    925          * doing a handshake anyway now, so ignore them if their format is
    926          * correct. Does not count for 'Finished' MAC.
    927          */
    928         if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
    929             if (s->msg_callback)
    930                 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
    931                                 p, DTLS1_HM_HEADER_LENGTH, ussl,
    932                                 s->msg_callback_arg);
    933 
    934             s->init_num = 0;
    935             goto redo;
    936         } else {                /* Incorrectly formatted Hello request */
    937 
    938             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
    939             goto f_err;
    940         }
    941     }
    942 
    943     if (!dtls1_preprocess_fragment(s, &msg_hdr)) {
    944         /* SSLfatal() already called */
    945         goto f_err;
    946     }
    947 
    948     if (frag_len > 0) {
    949         p += DTLS1_HM_HEADER_LENGTH;
    950 
    951         i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
    952                                         &p[frag_off], frag_len, 0, &readbytes);
    953 
    954         /*
    955          * This shouldn't ever fail due to NBIO because we already checked
    956          * that we have enough data in the record
    957          */
    958         if (i <= 0) {
    959             s->rwstate = SSL_READING;
    960             *len = 0;
    961             return 0;
    962         }
    963     } else {
    964         readbytes = 0;
    965     }
    966 
    967     /*
    968      * XDTLS: an incorrectly formatted fragment should cause the handshake
    969      * to fail
    970      */
    971     if (readbytes != frag_len) {
    972         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);
    973         goto f_err;
    974     }
    975 
    976     if (chretran) {
    977         /*
    978          * We got a new ClientHello with a message sequence of 0.
    979          * Reset the read/write sequences back to the beginning.
    980          * We process it like this is the first time we've seen a ClientHello
    981          * from the client.
    982          */
    983         s->d1->handshake_read_seq = 0;
    984         s->d1->next_handshake_write_seq = 0;
    985     }
    986 
    987     /*
    988      * Note that s->init_num is *not* used as current offset in
    989      * s->init_buf->data, but as a counter summing up fragments' lengths: as
    990      * soon as they sum up to handshake packet length, we assume we have got
    991      * all the fragments.
    992      */
    993     *len = s->init_num = frag_len;
    994     return 1;
    995 
    996  f_err:
    997     s->init_num = 0;
    998     *len = 0;
    999     return 0;
   1000 }
   1001 
   1002 /*-
   1003  * for these 2 messages, we need to
   1004  * ssl->session->read_sym_enc           assign
   1005  * ssl->session->read_compression       assign
   1006  * ssl->session->read_hash              assign
   1007  */
   1008 CON_FUNC_RETURN dtls_construct_change_cipher_spec(SSL_CONNECTION *s,
   1009                                                   WPACKET *pkt)
   1010 {
   1011     if (s->version == DTLS1_BAD_VER) {
   1012         s->d1->next_handshake_write_seq++;
   1013 
   1014         if (!WPACKET_put_bytes_u16(pkt, s->d1->handshake_write_seq)) {
   1015             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
   1016             return CON_FUNC_ERROR;
   1017         }
   1018     }
   1019 
   1020     return CON_FUNC_SUCCESS;
   1021 }
   1022 
   1023 #ifndef OPENSSL_NO_SCTP
   1024 /*
   1025  * Wait for a dry event. Should only be called at a point in the handshake
   1026  * where we are not expecting any data from the peer except an alert.
   1027  */
   1028 WORK_STATE dtls_wait_for_dry(SSL_CONNECTION *s)
   1029 {
   1030     int ret, errtype;
   1031     size_t len;
   1032     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
   1033 
   1034     /* read app data until dry event */
   1035     ret = BIO_dgram_sctp_wait_for_dry(SSL_get_wbio(ssl));
   1036     if (ret < 0) {
   1037         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
   1038         return WORK_ERROR;
   1039     }
   1040 
   1041     if (ret == 0) {
   1042         /*
   1043          * We're not expecting any more messages from the peer at this point -
   1044          * but we could get an alert. If an alert is waiting then we will never
   1045          * return successfully. Therefore we attempt to read a message. This
   1046          * should never succeed but will process any waiting alerts.
   1047          */
   1048         if (dtls_get_reassembled_message(s, &errtype, &len)) {
   1049             /* The call succeeded! This should never happen */
   1050             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
   1051             return WORK_ERROR;
   1052         }
   1053 
   1054         s->s3.in_read_app_data = 2;
   1055         s->rwstate = SSL_READING;
   1056         BIO_clear_retry_flags(SSL_get_rbio(ssl));
   1057         BIO_set_retry_read(SSL_get_rbio(ssl));
   1058         return WORK_MORE_A;
   1059     }
   1060     return WORK_FINISHED_CONTINUE;
   1061 }
   1062 #endif
   1063 
   1064 int dtls1_read_failed(SSL_CONNECTION *s, int code)
   1065 {
   1066     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
   1067 
   1068     if (code > 0) {
   1069         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
   1070         return 0;
   1071     }
   1072 
   1073     if (!dtls1_is_timer_expired(s) || ossl_statem_in_error(s)) {
   1074         /*
   1075          * not a timeout, none of our business, let higher layers handle
   1076          * this.  in fact it's probably an error
   1077          */
   1078         return code;
   1079     }
   1080     /* done, no need to send a retransmit */
   1081     if (!SSL_in_init(ssl)) {
   1082         BIO_set_flags(SSL_get_rbio(ssl), BIO_FLAGS_READ);
   1083         return code;
   1084     }
   1085 
   1086     return dtls1_handle_timeout(s);
   1087 }
   1088 
   1089 int dtls1_get_queue_priority(unsigned short seq, int is_ccs)
   1090 {
   1091     /*
   1092      * The index of the retransmission queue actually is the message sequence
   1093      * number, since the queue only contains messages of a single handshake.
   1094      * However, the ChangeCipherSpec has no message sequence number and so
   1095      * using only the sequence will result in the CCS and Finished having the
   1096      * same index. To prevent this, the sequence number is multiplied by 2.
   1097      * In case of a CCS 1 is subtracted. This does not only differ CSS and
   1098      * Finished, it also maintains the order of the index (important for
   1099      * priority queues) and fits in the unsigned short variable.
   1100      */
   1101     return seq * 2 - is_ccs;
   1102 }
   1103 
   1104 int dtls1_retransmit_buffered_messages(SSL_CONNECTION *s)
   1105 {
   1106     pqueue *sent = s->d1->sent_messages;
   1107     piterator iter;
   1108     pitem *item;
   1109     hm_fragment *frag;
   1110     int found = 0;
   1111 
   1112     iter = pqueue_iterator(sent);
   1113 
   1114     for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
   1115         frag = (hm_fragment *)item->data;
   1116         if (dtls1_retransmit_message(s, (unsigned short)
   1117                                      dtls1_get_queue_priority
   1118                                      (frag->msg_header.seq,
   1119                                       frag->msg_header.is_ccs), &found) <= 0)
   1120             return -1;
   1121     }
   1122 
   1123     return 1;
   1124 }
   1125 
   1126 int dtls1_buffer_message(SSL_CONNECTION *s, int is_ccs)
   1127 {
   1128     pitem *item;
   1129     hm_fragment *frag;
   1130     unsigned char seq64be[8];
   1131 
   1132     /*
   1133      * this function is called immediately after a message has been
   1134      * serialized
   1135      */
   1136     if (!ossl_assert(s->init_off == 0))
   1137         return 0;
   1138 
   1139     frag = dtls1_hm_fragment_new(s->init_num, 0);
   1140     if (frag == NULL)
   1141         return 0;
   1142 
   1143     memcpy(frag->fragment, s->init_buf->data, s->init_num);
   1144 
   1145     if (is_ccs) {
   1146         /* For DTLS1_BAD_VER the header length is non-standard */
   1147         if (!ossl_assert(s->d1->w_msg_hdr.msg_len +
   1148                          ((s->version ==
   1149                            DTLS1_BAD_VER) ? 3 : DTLS1_CCS_HEADER_LENGTH)
   1150                          == (unsigned int)s->init_num)) {
   1151             dtls1_hm_fragment_free(frag);
   1152             return 0;
   1153         }
   1154     } else {
   1155         if (!ossl_assert(s->d1->w_msg_hdr.msg_len +
   1156                          DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num)) {
   1157             dtls1_hm_fragment_free(frag);
   1158             return 0;
   1159         }
   1160     }
   1161 
   1162     frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
   1163     frag->msg_header.seq = s->d1->w_msg_hdr.seq;
   1164     frag->msg_header.type = s->d1->w_msg_hdr.type;
   1165     frag->msg_header.frag_off = 0;
   1166     frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
   1167     frag->msg_header.is_ccs = is_ccs;
   1168 
   1169     /* save current state */
   1170     frag->msg_header.saved_retransmit_state.wrlmethod = s->rlayer.wrlmethod;
   1171     frag->msg_header.saved_retransmit_state.wrl = s->rlayer.wrl;
   1172 
   1173 
   1174     memset(seq64be, 0, sizeof(seq64be));
   1175     seq64be[6] =
   1176         (unsigned
   1177          char)(dtls1_get_queue_priority(frag->msg_header.seq,
   1178                                         frag->msg_header.is_ccs) >> 8);
   1179     seq64be[7] =
   1180         (unsigned
   1181          char)(dtls1_get_queue_priority(frag->msg_header.seq,
   1182                                         frag->msg_header.is_ccs));
   1183 
   1184     item = pitem_new(seq64be, frag);
   1185     if (item == NULL) {
   1186         dtls1_hm_fragment_free(frag);
   1187         return 0;
   1188     }
   1189 
   1190     pqueue_insert(s->d1->sent_messages, item);
   1191     return 1;
   1192 }
   1193 
   1194 int dtls1_retransmit_message(SSL_CONNECTION *s, unsigned short seq, int *found)
   1195 {
   1196     int ret;
   1197     /* XDTLS: for now assuming that read/writes are blocking */
   1198     pitem *item;
   1199     hm_fragment *frag;
   1200     unsigned long header_length;
   1201     unsigned char seq64be[8];
   1202     struct dtls1_retransmit_state saved_state;
   1203 
   1204     /* XDTLS:  the requested message ought to be found, otherwise error */
   1205     memset(seq64be, 0, sizeof(seq64be));
   1206     seq64be[6] = (unsigned char)(seq >> 8);
   1207     seq64be[7] = (unsigned char)seq;
   1208 
   1209     item = pqueue_find(s->d1->sent_messages, seq64be);
   1210     if (item == NULL) {
   1211         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
   1212         *found = 0;
   1213         return 0;
   1214     }
   1215 
   1216     *found = 1;
   1217     frag = (hm_fragment *)item->data;
   1218 
   1219     if (frag->msg_header.is_ccs)
   1220         header_length = DTLS1_CCS_HEADER_LENGTH;
   1221     else
   1222         header_length = DTLS1_HM_HEADER_LENGTH;
   1223 
   1224     memcpy(s->init_buf->data, frag->fragment,
   1225            frag->msg_header.msg_len + header_length);
   1226     s->init_num = frag->msg_header.msg_len + header_length;
   1227 
   1228     dtls1_set_message_header_int(s, frag->msg_header.type,
   1229                                  frag->msg_header.msg_len,
   1230                                  frag->msg_header.seq, 0,
   1231                                  frag->msg_header.frag_len);
   1232 
   1233     /* save current state */
   1234     saved_state.wrlmethod = s->rlayer.wrlmethod;
   1235     saved_state.wrl = s->rlayer.wrl;
   1236 
   1237     s->d1->retransmitting = 1;
   1238 
   1239     /* restore state in which the message was originally sent */
   1240     s->rlayer.wrlmethod = frag->msg_header.saved_retransmit_state.wrlmethod;
   1241     s->rlayer.wrl = frag->msg_header.saved_retransmit_state.wrl;
   1242 
   1243     /*
   1244      * The old wrl may be still pointing at an old BIO. Update it to what we're
   1245      * using now.
   1246      */
   1247     s->rlayer.wrlmethod->set1_bio(s->rlayer.wrl, s->wbio);
   1248 
   1249     ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
   1250                          SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
   1251 
   1252     /* restore current state */
   1253     s->rlayer.wrlmethod = saved_state.wrlmethod;
   1254     s->rlayer.wrl = saved_state.wrl;
   1255 
   1256     s->d1->retransmitting = 0;
   1257 
   1258     (void)BIO_flush(s->wbio);
   1259     return ret;
   1260 }
   1261 
   1262 void dtls1_set_message_header(SSL_CONNECTION *s,
   1263                               unsigned char mt, size_t len,
   1264                               size_t frag_off, size_t frag_len)
   1265 {
   1266     if (frag_off == 0) {
   1267         s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
   1268         s->d1->next_handshake_write_seq++;
   1269     }
   1270 
   1271     dtls1_set_message_header_int(s, mt, len, s->d1->handshake_write_seq,
   1272                                  frag_off, frag_len);
   1273 }
   1274 
   1275 /* don't actually do the writing, wait till the MTU has been retrieved */
   1276 static void
   1277 dtls1_set_message_header_int(SSL_CONNECTION *s, unsigned char mt,
   1278                              size_t len, unsigned short seq_num,
   1279                              size_t frag_off, size_t frag_len)
   1280 {
   1281     struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
   1282 
   1283     msg_hdr->type = mt;
   1284     msg_hdr->msg_len = len;
   1285     msg_hdr->seq = seq_num;
   1286     msg_hdr->frag_off = frag_off;
   1287     msg_hdr->frag_len = frag_len;
   1288 }
   1289 
   1290 static void
   1291 dtls1_fix_message_header(SSL_CONNECTION *s, size_t frag_off, size_t frag_len)
   1292 {
   1293     struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
   1294 
   1295     msg_hdr->frag_off = frag_off;
   1296     msg_hdr->frag_len = frag_len;
   1297 }
   1298 
   1299 static unsigned char *dtls1_write_message_header(SSL_CONNECTION *s,
   1300                                                  unsigned char *p)
   1301 {
   1302     struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
   1303 
   1304     *p++ = msg_hdr->type;
   1305     l2n3(msg_hdr->msg_len, p);
   1306 
   1307     s2n(msg_hdr->seq, p);
   1308     l2n3(msg_hdr->frag_off, p);
   1309     l2n3(msg_hdr->frag_len, p);
   1310 
   1311     return p;
   1312 }
   1313 
   1314 void dtls1_get_message_header(const unsigned char *data, struct
   1315                               hm_header_st *msg_hdr)
   1316 {
   1317     memset(msg_hdr, 0, sizeof(*msg_hdr));
   1318     msg_hdr->type = *(data++);
   1319     n2l3(data, msg_hdr->msg_len);
   1320 
   1321     n2s(data, msg_hdr->seq);
   1322     n2l3(data, msg_hdr->frag_off);
   1323     n2l3(data, msg_hdr->frag_len);
   1324 }
   1325 
   1326 int dtls1_set_handshake_header(SSL_CONNECTION *s, WPACKET *pkt, int htype)
   1327 {
   1328     unsigned char *header;
   1329 
   1330     if (htype == SSL3_MT_CHANGE_CIPHER_SPEC) {
   1331         s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
   1332         dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
   1333                                      s->d1->handshake_write_seq, 0, 0);
   1334         if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS))
   1335             return 0;
   1336     } else {
   1337         dtls1_set_message_header(s, htype, 0, 0, 0);
   1338         /*
   1339          * We allocate space at the start for the message header. This gets
   1340          * filled in later
   1341          */
   1342         if (!WPACKET_allocate_bytes(pkt, DTLS1_HM_HEADER_LENGTH, &header)
   1343                 || !WPACKET_start_sub_packet(pkt))
   1344             return 0;
   1345     }
   1346 
   1347     return 1;
   1348 }
   1349 
   1350 int dtls1_close_construct_packet(SSL_CONNECTION *s, WPACKET *pkt, int htype)
   1351 {
   1352     size_t msglen;
   1353 
   1354     if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
   1355             || !WPACKET_get_length(pkt, &msglen)
   1356             || msglen > INT_MAX)
   1357         return 0;
   1358 
   1359     if (htype != SSL3_MT_CHANGE_CIPHER_SPEC) {
   1360         s->d1->w_msg_hdr.msg_len = msglen - DTLS1_HM_HEADER_LENGTH;
   1361         s->d1->w_msg_hdr.frag_len = msglen - DTLS1_HM_HEADER_LENGTH;
   1362     }
   1363     s->init_num = (int)msglen;
   1364     s->init_off = 0;
   1365 
   1366     if (htype != DTLS1_MT_HELLO_VERIFY_REQUEST) {
   1367         /* Buffer the message to handle re-xmits */
   1368         if (!dtls1_buffer_message(s, htype == SSL3_MT_CHANGE_CIPHER_SPEC
   1369                                      ? 1 : 0))
   1370             return 0;
   1371     }
   1372 
   1373     return 1;
   1374 }
   1375