

#include <stdio.h>
#include <errno.h>
#include "../ssl_local.h"
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include "record_local.h"
#include "internal/packet.h"
#include "internal/cryptlib.h"

int DTLS_RECORD_LAYER_new(RECORD_LAYER *rl)
{
    DTLS_RECORD_LAYER *d;

    if ((d = OPENSSL_malloc(sizeof(*d))) == NULL)
        return 0;

    rl->d = d;

    d->buffered_app_data = pqueue_new();

    if (d->buffered_app_data == NULL) {
        OPENSSL_free(d);
        rl->d = NULL;
        return 0;
    }

    return 1;
}

void DTLS_RECORD_LAYER_free(RECORD_LAYER *rl)
{
    if (rl->d == NULL)
        return;

    DTLS_RECORD_LAYER_clear(rl);
    pqueue_free(rl->d->buffered_app_data);
    OPENSSL_free(rl->d);
    rl->d = NULL;
}

void DTLS_RECORD_LAYER_clear(RECORD_LAYER *rl)
{
    DTLS_RECORD_LAYER *d;
    pitem *item = NULL;
    TLS_RECORD *rec;
    pqueue *buffered_app_data;

    d = rl->d;

    while ((item = pqueue_pop(d->buffered_app_data)) != NULL) {
        rec = (TLS_RECORD *)item->data;

        if (rl->s->options & SSL_OP_CLEANSE_PLAINTEXT)
            OPENSSL_cleanse(rec->allocdata, rec->length);
        OPENSSL_free(rec->allocdata);
        OPENSSL_free(item->data);
        pitem_free(item);
    }

    buffered_app_data = d->buffered_app_data;
    memset(d, 0, sizeof(*d));
    d->buffered_app_data = buffered_app_data;
}

static int dtls_buffer_record(SSL_CONNECTION *s, TLS_RECORD *rec)
{
    TLS_RECORD *rdata;
    pitem *item;
    struct pqueue_st *queue = s->rlayer.d->buffered_app_data;

    
    if (pqueue_size(queue) >= 100)
        return 0;

    
    if (!ossl_assert(rec->off == 0))
        return -1;

    rdata = OPENSSL_malloc(sizeof(*rdata));
    item = pitem_new(rec->seq_num, rdata);
    if (rdata == NULL || item == NULL) {
        OPENSSL_free(rdata);
        pitem_free(item);
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
        return -1;
    }

    *rdata = *rec;
    
    rdata->data = rdata->allocdata = OPENSSL_memdup(rec->data, rec->length);
    if (rdata->data == NULL) {
        OPENSSL_free(rdata);
        pitem_free(item);
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
        return -1;
    }
    
    rdata->rechandle = NULL;

    item->data = rdata;

#ifndef OPENSSL_NO_SCTP
    
    if (BIO_dgram_is_sctp(s->rbio) &&
        (ossl_statem_get_state(s) == TLS_ST_SR_FINISHED
         || ossl_statem_get_state(s) == TLS_ST_CR_FINISHED)) {
        BIO_ctrl(s->rbio, BIO_CTRL_DGRAM_SCTP_GET_RCVINFO,
                 sizeof(rdata->recordinfo), &rdata->recordinfo);
    }
#endif

    if (pqueue_insert(queue, item) == NULL) {
        
        OPENSSL_free(rdata->allocdata);
        OPENSSL_free(rdata);
        pitem_free(item);
    }

    return 1;
}


static void dtls_unbuffer_record(SSL_CONNECTION *s)
{
    TLS_RECORD *rdata;
    pitem *item;

    
    if (s->rlayer.curr_rec < s->rlayer.num_recs)
        return;

    item = pqueue_pop(s->rlayer.d->buffered_app_data);
    if (item != NULL) {
        rdata = (TLS_RECORD *)item->data;

        s->rlayer.tlsrecs[0] = *rdata;
        s->rlayer.num_recs = 1;
        s->rlayer.curr_rec = 0;

#ifndef OPENSSL_NO_SCTP
        
        if (BIO_dgram_is_sctp(s->rbio)) {
            BIO_ctrl(s->rbio, BIO_CTRL_DGRAM_SCTP_SET_RCVINFO,
                     sizeof(rdata->recordinfo), &rdata->recordinfo);
        }
#endif

        OPENSSL_free(item->data);
        pitem_free(item);
    }
}


int dtls1_read_bytes(SSL *s, uint8_t type, uint8_t *recvd_type,
                     unsigned char *buf, size_t len,
                     int peek, size_t *readbytes)
{
    int i, j, ret;
    size_t n;
    TLS_RECORD *rr;
    void (*cb) (const SSL *ssl, int type2, int val) = NULL;
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);

    if (sc == NULL)
        return -1;

    if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
         (type != SSL3_RT_HANDSHAKE)) ||
        (peek && (type != SSL3_RT_APPLICATION_DATA))) {
        SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
        return -1;
    }

    if (!ossl_statem_get_in_handshake(sc) && SSL_in_init(s)) {
        
        i = sc->handshake_func(s);
        
        if (i < 0)
            return i;
        if (i == 0)
            return -1;
    }

 start:
    sc->rwstate = SSL_NOTHING;

    
    if (SSL_is_init_finished(s))
        dtls_unbuffer_record(sc);

    
    if (dtls1_handle_timeout(sc) > 0) {
        goto start;
    } else if (ossl_statem_in_error(sc)) {
        
        return -1;
    }

    
    if (sc->rlayer.curr_rec >= sc->rlayer.num_recs) {
        sc->rlayer.curr_rec = sc->rlayer.num_recs = 0;
        do {
            rr = &sc->rlayer.tlsrecs[sc->rlayer.num_recs];

            ret = HANDLE_RLAYER_READ_RETURN(sc,
                    sc->rlayer.rrlmethod->read_record(sc->rlayer.rrl,
                                                      &rr->rechandle,
                                                      &rr->version, &rr->type,
                                                      &rr->data, &rr->length,
                                                      &rr->epoch, rr->seq_num));
            if (ret <= 0) {
                ret = dtls1_read_failed(sc, ret);
                
                if (ret <= 0)
                    return ret;
                else
                    goto start;
            }
            rr->off = 0;
            sc->rlayer.num_recs++;
        } while (sc->rlayer.rrlmethod->processed_read_pending(sc->rlayer.rrl)
                 && sc->rlayer.num_recs < SSL_MAX_PIPELINES);
    }
    rr = &sc->rlayer.tlsrecs[sc->rlayer.curr_rec];

    
    if (rr->type != SSL3_RT_ALERT && rr->length != 0)
        sc->rlayer.alert_count = 0;

    

    if (sc->s3.change_cipher_spec 
        && (rr->type != SSL3_RT_HANDSHAKE)) {
        
        if (dtls_buffer_record(sc, rr) < 0) {
            
            return -1;
        }
        if (!ssl_release_record(sc, rr, 0))
            return -1;
        goto start;
    }

    
    if (sc->shutdown & SSL_RECEIVED_SHUTDOWN) {
        if (!ssl_release_record(sc, rr, 0))
            return -1;
        sc->rwstate = SSL_NOTHING;
        return 0;
    }

    if (type == rr->type
        || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
            && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {
        
        
        if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA)
                && (SSL_IS_FIRST_HANDSHAKE(sc))) {
            SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE,
                     SSL_R_APP_DATA_IN_HANDSHAKE);
            return -1;
        }

        if (recvd_type != NULL)
            *recvd_type = rr->type;

        if (len == 0) {
            
            if (rr->length == 0 && !ssl_release_record(sc, rr, 0))
                return -1;
            return 0;
        }

        if (len > rr->length)
            n = rr->length;
        else
            n = len;

        memcpy(buf, &(rr->data[rr->off]), n);
        if (peek) {
            if (rr->length == 0 && !ssl_release_record(sc, rr, 0))
                return -1;
        } else {
            if (!ssl_release_record(sc, rr, n))
                return -1;
        }
#ifndef OPENSSL_NO_SCTP
        
        if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
            sc->d1->shutdown_received
            && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s)) <= 0) {
            sc->shutdown |= SSL_RECEIVED_SHUTDOWN;
            return 0;
        }
#endif
        *readbytes = n;
        return 1;
    }

    

    if (rr->type == SSL3_RT_ALERT) {
        unsigned int alert_level, alert_descr;
        const unsigned char *alert_bytes = rr->data + rr->off;
        PACKET alert;

        if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
                || !PACKET_get_1(&alert, &alert_level)
                || !PACKET_get_1(&alert, &alert_descr)
                || PACKET_remaining(&alert) != 0) {
            SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
            return -1;
        }

        if (sc->msg_callback)
            sc->msg_callback(0, sc->version, SSL3_RT_ALERT, alert_bytes, 2, s,
                             sc->msg_callback_arg);

        if (sc->info_callback != NULL)
            cb = sc->info_callback;
        else if (s->ctx->info_callback != NULL)
            cb = s->ctx->info_callback;

        if (cb != NULL) {
            j = (alert_level << 8) | alert_descr;
            cb(s, SSL_CB_READ_ALERT, j);
        }

        if (alert_level == SSL3_AL_WARNING) {
            sc->s3.warn_alert = alert_descr;
            if (!ssl_release_record(sc, rr, 0))
                return -1;

            sc->rlayer.alert_count++;
            if (sc->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
                SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE,
                         SSL_R_TOO_MANY_WARN_ALERTS);
                return -1;
            }

            if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
#ifndef OPENSSL_NO_SCTP
                
                if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
                    BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s)) > 0) {
                    sc->d1->shutdown_received = 1;
                    sc->rwstate = SSL_READING;
                    BIO_clear_retry_flags(SSL_get_rbio(s));
                    BIO_set_retry_read(SSL_get_rbio(s));
                    return -1;
                }
#endif
                sc->shutdown |= SSL_RECEIVED_SHUTDOWN;
                return 0;
            }
        } else if (alert_level == SSL3_AL_FATAL) {
            sc->rwstate = SSL_NOTHING;
            sc->s3.fatal_alert = alert_descr;
            SSLfatal_data(sc, SSL_AD_NO_ALERT,
                          SSL_AD_REASON_OFFSET + alert_descr,
                          "SSL alert number %d", alert_descr);
            sc->shutdown |= SSL_RECEIVED_SHUTDOWN;
            if (!ssl_release_record(sc, rr, 0))
                return -1;
            SSL_CTX_remove_session(sc->session_ctx, sc->session);
            return 0;
        } else {
            SSLfatal(sc, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
            return -1;
        }

        goto start;
    }

    if (sc->shutdown & SSL_SENT_SHUTDOWN) { 
        sc->rwstate = SSL_NOTHING;
        if (!ssl_release_record(sc, rr, 0))
            return -1;
        return 0;
    }

    if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
        
        if (!ssl_release_record(sc, rr, 0))
            return -1;
        goto start;
    }

    
    if (rr->type == SSL3_RT_HANDSHAKE && !ossl_statem_get_in_handshake(sc)) {
        struct hm_header_st msg_hdr;

        
        if (rr->epoch != sc->rlayer.d->r_epoch
                || rr->length < DTLS1_HM_HEADER_LENGTH) {
            if (!ssl_release_record(sc, rr, 0))
                return -1;
            goto start;
        }

        dtls1_get_message_header(rr->data, &msg_hdr);

        
        if (msg_hdr.type == SSL3_MT_FINISHED) {
            if (dtls1_check_timeout_num(sc) < 0) {
                
                return -1;
            }

            if (dtls1_retransmit_buffered_messages(sc) <= 0) {
                
                if (ossl_statem_in_error(sc))
                    return -1;
            }
            if (!ssl_release_record(sc, rr, 0))
                return -1;
            if (!(sc->mode & SSL_MODE_AUTO_RETRY)) {
                if (!sc->rlayer.rrlmethod->unprocessed_read_pending(sc->rlayer.rrl)) {
                    
                    BIO *bio;

                    sc->rwstate = SSL_READING;
                    bio = SSL_get_rbio(s);
                    BIO_clear_retry_flags(bio);
                    BIO_set_retry_read(bio);
                    return -1;
                }
            }
            goto start;
        }

        
        if (!ossl_assert(SSL_is_init_finished(s))) {
            SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
            return -1;
        }

        
        ossl_statem_set_in_init(sc, 1);

        i = sc->handshake_func(s);
        
        if (i < 0)
            return i;
        if (i == 0)
            return -1;

        if (!(sc->mode & SSL_MODE_AUTO_RETRY)) {
            if (!sc->rlayer.rrlmethod->unprocessed_read_pending(sc->rlayer.rrl)) {
                
                BIO *bio;
                
                sc->rwstate = SSL_READING;
                bio = SSL_get_rbio(s);
                BIO_clear_retry_flags(bio);
                BIO_set_retry_read(bio);
                return -1;
            }
        }
        goto start;
    }

    switch (rr->type) {
    default:
        SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
        return -1;
    case SSL3_RT_CHANGE_CIPHER_SPEC:
    case SSL3_RT_ALERT:
    case SSL3_RT_HANDSHAKE:
        
        SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
        return -1;
    case SSL3_RT_APPLICATION_DATA:
        
        if (sc->s3.in_read_app_data &&
            (sc->s3.total_renegotiations != 0) &&
            ossl_statem_app_data_allowed(sc)) {
            sc->s3.in_read_app_data = 2;
            return -1;
        } else {
            SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
            return -1;
        }
    }
    
}


int dtls1_write_bytes(SSL_CONNECTION *s, uint8_t type, const void *buf,
                      size_t len, size_t *written)
{
    int i;

    if (!ossl_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH)) {
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
        return -1;
    }
    s->rwstate = SSL_NOTHING;
    i = do_dtls1_write(s, type, buf, len, written);
    return i;
}

int do_dtls1_write(SSL_CONNECTION *sc, uint8_t type, const unsigned char *buf,
                   size_t len, size_t *written)
{
    int i;
    OSSL_RECORD_TEMPLATE tmpl;
    SSL *s = SSL_CONNECTION_GET_SSL(sc);
    int ret;

    
    if (sc->s3.alert_dispatch > 0) {
        i = s->method->ssl_dispatch_alert(s);
        if (i <= 0)
            return i;
        
    }

    if (len == 0)
        return 0;

    if (len > ssl_get_max_send_fragment(sc)) {
        SSLfatal(sc, SSL_AD_INTERNAL_ERROR, SSL_R_EXCEEDS_MAX_FRAGMENT_SIZE);
        return 0;
    }

    tmpl.type = type;
    
    if (s->method->version == DTLS_ANY_VERSION
            && sc->max_proto_version != DTLS1_BAD_VER)
        tmpl.version = DTLS1_VERSION;
    else
        tmpl.version = sc->version;
    tmpl.buf = buf;
    tmpl.buflen = len;

    ret = HANDLE_RLAYER_WRITE_RETURN(sc,
              sc->rlayer.wrlmethod->write_records(sc->rlayer.wrl, &tmpl, 1));

    if (ret > 0)
        *written = (int)len;

    return ret;
}

void dtls1_increment_epoch(SSL_CONNECTION *s, int rw)
{
    if (rw & SSL3_CC_READ) {
        s->rlayer.d->r_epoch++;

        
        dtls1_clear_received_buffer(s);
    } else {
        s->rlayer.d->w_epoch++;
    }
}

uint16_t dtls1_get_epoch(SSL_CONNECTION *s, int rw) {
    uint16_t epoch;

    if (rw & SSL3_CC_READ)
        epoch = s->rlayer.d->r_epoch;
    else
        epoch = s->rlayer.d->w_epoch;

    return epoch;
}
