/* Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#endif

#include <stdio.h>
#include <string.h>
#include <apr_pools.h>
#include <apr_time.h>

#include <openssl/err.h>
#include <openssl/ssl.h>

#include "h3_check.h"
#include "quic/detail/h3q_ossl_addr.h"
#include "quic/h3q_conn.h"

/* Stream modes, incoming-stream policy and idle timeout, applied to a freshly accepted connection. */
int h3q_conn_prepare(h3q_conn* conn, uint32_t idle_timeout_secs)
{
    SSL* ssl_conn = (SSL*)conn;
    if (!ssl_conn || !SSL_set_blocking_mode(ssl_conn, 0))
    {
        return 0;
    }
    SSL_set_default_stream_mode(ssl_conn, SSL_DEFAULT_STREAM_MODE_NONE);
    SSL_set_incoming_stream_policy(ssl_conn, SSL_INCOMING_STREAM_POLICY_ACCEPT, 0);
    SSL_set_generic_value_uint(ssl_conn, SSL_VALUE_QUIC_IDLE_TIMEOUT, (uint64_t)idle_timeout_secs * 1000);
    return 1;
}

/* OpenSSL copies written bytes and reports no per-stream acknowledgements. */
void h3q_conn_set_user(h3q_conn* conn, void* user)
{
    (void)conn;
    (void)user;
}

/* OpenSSL's QUIC server drops 0-RTT packets. */
int h3q_conn_has_early_data(h3q_conn* conn)
{
    (void)conn;
    return 0;
}

/* OpenSSL manages the peer's stream credit itself and does not report it. */
uint64_t h3q_conn_max_remote_streams_bidi(h3q_conn* conn)
{
    (void)conn;
    return 0;
}

/* OpenSSL reports no per-connection activity: always treat the connection as touched. */
int h3q_conn_take_activity(h3q_conn* conn)
{
    (void)conn;
    return 1;
}

h3q_stream* h3q_conn_open_uni_stream(h3q_conn* conn, int64_t* out_id)
{
    SSL* ssl_conn = (SSL*)conn;
    CHECK(ssl_conn);
    CHECK(out_id);
    SSL* stream = SSL_new_stream(ssl_conn, SSL_STREAM_FLAG_UNI);
    if (!stream)
    {
        return NULL;
    }
    *out_id = (int64_t)SSL_get_stream_id(stream);
    return (h3q_stream*)stream;
}

h3q_stream* h3q_conn_accept_stream(h3q_conn* conn)
{
    SSL* ssl_conn = (SSL*)conn;
    if (!ssl_conn)
    {
        return NULL;
    }
    return (h3q_stream*)SSL_accept_stream(ssl_conn, SSL_ACCEPT_STREAM_NO_BLOCK);
}

int h3q_conn_is_handshake_done(h3q_conn* conn)
{
    SSL* ssl_conn = (SSL*)conn;
    return ssl_conn ? SSL_is_init_finished(ssl_conn) : 0;
}

int h3q_conn_tls_info(h3q_conn* conn, h3q_tls_info* out)
{
    SSL* ssl_conn = (SSL*)conn;
    if (!ssl_conn || !out)
    {
        return 0;
    }
    const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_conn);
    if (!cipher)
    {
        return 0;
    }
    int alg_bits = 0;
    out->cipher_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
    out->cipher_alg_bits = alg_bits;
    out->cipher = SSL_CIPHER_get_name(cipher);
    const char* version = SSL_get_version(ssl_conn);
    out->protocol = (version && strncmp(version, "TLS", 3) == 0) ? version : "TLSv1.3";
    out->resumed = SSL_session_reused(ssl_conn) ? 1u : 0u;
    return 1;
}

int h3q_conn_is_closed(h3q_conn* conn)
{
    SSL* ssl_conn = (SSL*)conn;
    return ssl_conn ? (SSL_get_shutdown(ssl_conn) != 0) : 1;
}

int h3q_conn_shutdown(h3q_conn* conn, int is_rapid, uint64_t app_error, const char* reason)
{
    SSL* ssl_conn = (SSL*)conn;
    if (!ssl_conn)
    {
        return 1;
    }
    uint64_t flags = is_rapid ? (uint64_t)SSL_SHUTDOWN_FLAG_RAPID : 0;
    int ret = 0;
    if (reason)
    {
        SSL_SHUTDOWN_EX_ARGS args = {.quic_error_code = app_error, .quic_reason = reason};
        ret = SSL_shutdown_ex(ssl_conn, flags, &args, sizeof(args));
    }
    else if (flags != 0)
    {
        SSL_SHUTDOWN_EX_ARGS args = {0};
        ret = SSL_shutdown_ex(ssl_conn, flags, &args, sizeof(args));
    }
    else
    {
        ret = SSL_shutdown(ssl_conn);
    }

    if (ret == 1)
    {
        return 1;
    }
    if (ret < 0)
    {
        int err = SSL_get_error(ssl_conn, ret);
        if (err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE)
        {
            return 1;
        }
    }
    return 0;
}

/* How long a refused connection waits for its handshake to finish before it is closed anyway. */
#define H3Q_REFUSE_HANDSHAKE_WAIT_SECS 5

/* OpenSSL cannot send the CONNECTION_REFUSED transport error, and its CONNECTION_CLOSE is sent in the packet type of
 * the lowest encryption level it still holds: a client which got the server's handshake flight has discarded the keys
 * for that already. So the close is held back until the handshake is done and goes out as an application error in a
 * 1-RTT packet, which every client can read. The engine keeps the connection until then and through the closing
 * period. */
void h3q_conn_refuse(h3q_engine* engine, h3q_conn* conn)
{
    SSL* ssl_conn = (SSL*)conn;
    h3q_refused* refused;
    if (!ssl_conn)
    {
        return;
    }
    refused = engine->refused_free;
    if (refused)
    {
        engine->refused_free = refused->next;
        memset(refused, 0, sizeof(*refused));
    }
    else
    {
        refused = apr_pcalloc(engine->pool, sizeof(*refused));
    }
    refused->ssl_conn = ssl_conn;
    refused->refused_at = apr_time_now();
    refused->next = engine->refused_head;
    engine->refused_head = refused;
}

void h3q_engine_reap_refused(h3q_engine* engine, int all)
{
    h3q_refused** slot = &engine->refused_head;
    apr_time_t now = apr_time_now();
    while (*slot)
    {
        h3q_refused* refused = *slot;
        SSL_SHUTDOWN_EX_ARGS args = {.quic_error_code = 0x107 /* H3_EXCESSIVE_LOAD */, .quic_reason = "refused"};
        int done = all;
        if (!done && !refused->closing && (SSL_is_init_finished(refused->ssl_conn) || now - refused->refused_at >= apr_time_from_sec(H3Q_REFUSE_HANDSHAKE_WAIT_SECS)))
        {
            refused->closing = 1;
        }
        if (!done && refused->closing)
        {
            done = (SSL_shutdown_ex(refused->ssl_conn, SSL_SHUTDOWN_FLAG_RAPID, &args, sizeof(args)) == 1);
        }
        if (done)
        {
            *slot = refused->next;
            SSL_free(refused->ssl_conn);
            refused->next = engine->refused_free;
            engine->refused_free = refused;
        }
        else
        {
            slot = &refused->next;
        }
    }
}

void h3q_conn_free(h3q_conn* conn)
{
    if (conn)
    {
        SSL_free((SSL*)conn);
    }
}

void h3q_conn_close_reason(h3q_conn* conn, char* buf, size_t buflen)
{
    if (!buf || buflen == 0)
    {
        return;
    }
    buf[0] = '\0';

    char errbuf[H3Q_ERRLEN] = {0};
    ERR_error_string_n(ERR_peek_last_error(), errbuf, sizeof(errbuf));

    SSL_CONN_CLOSE_INFO cci = {0};
    if (conn && SSL_get_conn_close_info((SSL*)conn, &cci, sizeof(cci)))
    {
        const char* origin = (cci.flags & SSL_CONN_CLOSE_FLAG_LOCAL) ? "local" : "remote";
        const char* layer = (cci.flags & SSL_CONN_CLOSE_FLAG_TRANSPORT) ? "transport" : "app";
        const char* reason = cci.reason ? cci.reason : "";
        snprintf(buf, buflen, "%s %s err=0x%llx frame=0x%llx reason=\"%.*s\" (%s)", origin, layer, (unsigned long long)cci.error_code, (unsigned long long)cci.frame_type, (int)cci.reason_len, reason, errbuf);
        return;
    }
    snprintf(buf, buflen, "%s", errbuf);
}
