/***************************************************************************
 *                                  _   _ ____  _
 *  Project                     ___| | | |  _ \| |
 *                             / __| | | | |_) | |
 *                            | (__| |_| |  _ <| |___
 *                             \___|\___/|_| \_\_____|
 *
 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution. The terms
 * are also available at https://curl.se/docs/copyright.html.
 *
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
 * copies of the Software, and permit persons to whom the Software is
 * furnished to do so, under the terms of the COPYING file.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 * SPDX-License-Identifier: curl
 *
 ***************************************************************************/

/*
 * Source file for all wolfSSL specific code for the TLS/SSL layer. No code
 * but vtls.c should ever call or use these functions.
 *
 */

#include "curl_setup.h"

#ifdef USE_WOLFSSL

#define WOLFSSL_OPTIONS_IGNORE_SYS
#include <wolfssl/version.h>
#include <wolfssl/options.h>

/* To determine what functions are available we rely on one or both of:
   - the user's options.h generated by wolfSSL
   - the symbols detected by curl's configure
   Since they are markedly different from one another, and one or the other may
   not be available, we do some checking below to bring things in sync. */

/* HAVE_ALPN is wolfSSL's build time symbol for enabling ALPN in options.h. */
#ifndef HAVE_ALPN
#ifdef HAVE_WOLFSSL_USEALPN
#define HAVE_ALPN
#endif
#endif

#include <limits.h>

#include "urldata.h"
#include "sendf.h"
#include "inet_pton.h"
#include "vtls.h"
#include "vtls_int.h"
#include "keylog.h"
#include "parsedate.h"
#include "connect.h" /* for the connect timeout */
#include "select.h"
#include "strcase.h"
#include "x509asn1.h"
#include "curl_printf.h"
#include "multiif.h"

#include <wolfssl/openssl/ssl.h>
#include <wolfssl/ssl.h>
#include <wolfssl/error-ssl.h>
#include "wolfssl.h"

/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"

#ifdef USE_ECH
# include "curl_base64.h"
# define ECH_ENABLED(__data__) \
    (__data__->set.tls_ech && \
     !(__data__->set.tls_ech & CURLECH_DISABLE)\
    )
#endif /* USE_ECH */

/* KEEP_PEER_CERT is a product of the presence of build time symbol
   OPENSSL_EXTRA without NO_CERTS, depending on the version. KEEP_PEER_CERT is
   in wolfSSL's settings.h, and the latter two are build time symbols in
   options.h. */
#ifndef KEEP_PEER_CERT
#if defined(HAVE_WOLFSSL_GET_PEER_CERTIFICATE) || \
    (defined(OPENSSL_EXTRA) && !defined(NO_CERTS))
#define KEEP_PEER_CERT
#endif
#endif

#if defined(HAVE_WOLFSSL_FULL_BIO) && HAVE_WOLFSSL_FULL_BIO
#define USE_BIO_CHAIN
#else
#undef USE_BIO_CHAIN
#endif

#ifdef OPENSSL_EXTRA
/*
 * Availability note:
 * The TLS 1.3 secret callback (wolfSSL_set_tls13_secret_cb) was added in
 * wolfSSL 4.4.0, but requires the -DHAVE_SECRET_CALLBACK build option. If that
 * option is not set, then TLS 1.3 will not be logged.
 * For TLS 1.2 and before, we use wolfSSL_get_keys().
 * SSL_get_client_random and wolfSSL_get_keys require OPENSSL_EXTRA
 * (--enable-opensslextra or --enable-all).
 */
#if defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13)
static int
wolfssl_tls13_secret_callback(SSL *ssl, int id, const unsigned char *secret,
                              int secretSz, void *ctx)
{
  const char *label;
  unsigned char client_random[SSL3_RANDOM_SIZE];
  (void)ctx;

  if(!ssl || !Curl_tls_keylog_enabled()) {
    return 0;
  }

  switch(id) {
  case CLIENT_EARLY_TRAFFIC_SECRET:
    label = "CLIENT_EARLY_TRAFFIC_SECRET";
    break;
  case CLIENT_HANDSHAKE_TRAFFIC_SECRET:
    label = "CLIENT_HANDSHAKE_TRAFFIC_SECRET";
    break;
  case SERVER_HANDSHAKE_TRAFFIC_SECRET:
    label = "SERVER_HANDSHAKE_TRAFFIC_SECRET";
    break;
  case CLIENT_TRAFFIC_SECRET:
    label = "CLIENT_TRAFFIC_SECRET_0";
    break;
  case SERVER_TRAFFIC_SECRET:
    label = "SERVER_TRAFFIC_SECRET_0";
    break;
  case EARLY_EXPORTER_SECRET:
    label = "EARLY_EXPORTER_SECRET";
    break;
  case EXPORTER_SECRET:
    label = "EXPORTER_SECRET";
    break;
  default:
    return 0;
  }

  if(SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE) == 0) {
    /* Should never happen as wolfSSL_KeepArrays() was called before. */
    return 0;
  }

  Curl_tls_keylog_write(label, client_random, secret, secretSz);
  return 0;
}
#endif /* defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13) */

static void
wolfssl_log_tls12_secret(SSL *ssl)
{
  unsigned char *ms, *sr, *cr;
  unsigned int msLen, srLen, crLen, i, x = 0;

#if LIBWOLFSSL_VERSION_HEX >= 0x0300d000 /* >= 3.13.0 */
  /* wolfSSL_GetVersion is available since 3.13, we use it instead of
   * SSL_version since the latter relies on OPENSSL_ALL (--enable-opensslall or
   * --enable-all). Failing to perform this check could result in an unusable
   * key log line when TLS 1.3 is actually negotiated. */
  switch(wolfSSL_GetVersion(ssl)) {
  case WOLFSSL_SSLV3:
  case WOLFSSL_TLSV1:
  case WOLFSSL_TLSV1_1:
  case WOLFSSL_TLSV1_2:
    break;
  default:
    /* TLS 1.3 does not use this mechanism, the "master secret" returned below
     * is not directly usable. */
    return;
  }
#endif

  if(wolfSSL_get_keys(ssl, &ms, &msLen, &sr, &srLen, &cr, &crLen) !=
     SSL_SUCCESS) {
    return;
  }

  /* Check for a missing master secret and skip logging. That can happen if
   * curl rejects the server certificate and aborts the handshake.
   */
  for(i = 0; i < msLen; i++) {
    x |= ms[i];
  }
  if(x == 0) {
    return;
  }

  Curl_tls_keylog_write("CLIENT_RANDOM", cr, ms, msLen);
}
#endif /* OPENSSL_EXTRA */

static int do_file_type(const char *type)
{
  if(!type || !type[0])
    return SSL_FILETYPE_PEM;
  if(strcasecompare(type, "PEM"))
    return SSL_FILETYPE_PEM;
  if(strcasecompare(type, "DER"))
    return SSL_FILETYPE_ASN1;
  return -1;
}

#ifdef HAVE_LIBOQS
struct group_name_map {
  const word16 group;
  const char   *name;
};

static const struct group_name_map gnm[] = {
  { WOLFSSL_KYBER_LEVEL1, "KYBER_LEVEL1" },
  { WOLFSSL_KYBER_LEVEL3, "KYBER_LEVEL3" },
  { WOLFSSL_KYBER_LEVEL5, "KYBER_LEVEL5" },
  { WOLFSSL_P256_KYBER_LEVEL1, "P256_KYBER_LEVEL1" },
  { WOLFSSL_P384_KYBER_LEVEL3, "P384_KYBER_LEVEL3" },
  { WOLFSSL_P521_KYBER_LEVEL5, "P521_KYBER_LEVEL5" },
  { 0, NULL }
};
#endif

#ifdef USE_BIO_CHAIN

static int wolfssl_bio_cf_create(WOLFSSL_BIO *bio)
{
  wolfSSL_BIO_set_shutdown(bio, 1);
  wolfSSL_BIO_set_data(bio, NULL);
  return 1;
}

static int wolfssl_bio_cf_destroy(WOLFSSL_BIO *bio)
{
  if(!bio)
    return 0;
  return 1;
}

static long wolfssl_bio_cf_ctrl(WOLFSSL_BIO *bio, int cmd, long num, void *ptr)
{
  struct Curl_cfilter *cf = BIO_get_data(bio);
  long ret = 1;

  (void)cf;
  (void)ptr;
  switch(cmd) {
  case BIO_CTRL_GET_CLOSE:
    ret = (long)wolfSSL_BIO_get_shutdown(bio);
    break;
  case BIO_CTRL_SET_CLOSE:
    wolfSSL_BIO_set_shutdown(bio, (int)num);
    break;
  case BIO_CTRL_FLUSH:
    /* we do no delayed writes, but if we ever would, this
     * needs to trigger it. */
    ret = 1;
    break;
  case BIO_CTRL_DUP:
    ret = 1;
    break;
#ifdef BIO_CTRL_EOF
  case BIO_CTRL_EOF:
    /* EOF has been reached on input? */
    return (!cf->next || !cf->next->connected);
#endif
  default:
    ret = 0;
    break;
  }
  return ret;
}

static int wolfssl_bio_cf_out_write(WOLFSSL_BIO *bio,
                                    const char *buf, int blen)
{
  struct Curl_cfilter *cf = wolfSSL_BIO_get_data(bio);
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;
  struct Curl_easy *data = CF_DATA_CURRENT(cf);
  ssize_t nwritten;
  CURLcode result = CURLE_OK;

  DEBUGASSERT(data);
  nwritten = Curl_conn_cf_send(cf->next, data, buf, blen, &result);
  backend->io_result = result;
  CURL_TRC_CF(data, cf, "bio_write(len=%d) -> %zd, %d",
              blen, nwritten, result);
  wolfSSL_BIO_clear_retry_flags(bio);
  if(nwritten < 0 && CURLE_AGAIN == result)
    BIO_set_retry_write(bio);
  return (int)nwritten;
}

static int wolfssl_bio_cf_in_read(WOLFSSL_BIO *bio, char *buf, int blen)
{
  struct Curl_cfilter *cf = wolfSSL_BIO_get_data(bio);
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;
  struct Curl_easy *data = CF_DATA_CURRENT(cf);
  ssize_t nread;
  CURLcode result = CURLE_OK;

  DEBUGASSERT(data);
  /* OpenSSL catches this case, so should we. */
  if(!buf)
    return 0;

  nread = Curl_conn_cf_recv(cf->next, data, buf, blen, &result);
  backend->io_result = result;
  CURL_TRC_CF(data, cf, "bio_read(len=%d) -> %zd, %d", blen, nread, result);
  wolfSSL_BIO_clear_retry_flags(bio);
  if(nread < 0 && CURLE_AGAIN == result)
    BIO_set_retry_read(bio);
  else if(nread == 0)
    connssl->peer_closed = TRUE;
  return (int)nread;
}

static WOLFSSL_BIO_METHOD *wolfssl_bio_cf_method = NULL;

static void wolfssl_bio_cf_init_methods(void)
{
  wolfssl_bio_cf_method = wolfSSL_BIO_meth_new(BIO_TYPE_MEM, "wolfSSL CF BIO");
  wolfSSL_BIO_meth_set_write(wolfssl_bio_cf_method, &wolfssl_bio_cf_out_write);
  wolfSSL_BIO_meth_set_read(wolfssl_bio_cf_method, &wolfssl_bio_cf_in_read);
  wolfSSL_BIO_meth_set_ctrl(wolfssl_bio_cf_method, &wolfssl_bio_cf_ctrl);
  wolfSSL_BIO_meth_set_create(wolfssl_bio_cf_method, &wolfssl_bio_cf_create);
  wolfSSL_BIO_meth_set_destroy(wolfssl_bio_cf_method, &wolfssl_bio_cf_destroy);
}

static void wolfssl_bio_cf_free_methods(void)
{
  wolfSSL_BIO_meth_free(wolfssl_bio_cf_method);
}

#else /* USE_BIO_CHAIN */

#define wolfssl_bio_cf_init_methods() Curl_nop_stmt
#define wolfssl_bio_cf_free_methods() Curl_nop_stmt

#endif /* !USE_BIO_CHAIN */

static CURLcode populate_x509_store(struct Curl_cfilter *cf,
                                    struct Curl_easy *data,
                                    X509_STORE *store,
                                    struct wolfssl_ctx *wssl)
{
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  const struct curl_blob *ca_info_blob = conn_config->ca_info_blob;
  const char * const ssl_cafile =
    /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */
    (ca_info_blob ? NULL : conn_config->CAfile);
  const char * const ssl_capath = conn_config->CApath;
  struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  bool imported_native_ca = false;

#if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SYS_CA_CERTS)
  /* load native CA certificates */
  if(ssl_config->native_ca_store) {
    if(wolfSSL_CTX_load_system_CA_certs(wssl->ctx) != WOLFSSL_SUCCESS) {
      infof(data, "error importing native CA store, continuing anyway");
    }
    else {
      imported_native_ca = true;
      infof(data, "successfully imported native CA store");
      wssl->x509_store_setup = TRUE;
    }
  }
#endif /* !NO_FILESYSTEM */

  /* load certificate blob */
  if(ca_info_blob) {
    if(wolfSSL_CTX_load_verify_buffer(wssl->ctx, ca_info_blob->data,
                                      (long)ca_info_blob->len,
                                      SSL_FILETYPE_PEM) != SSL_SUCCESS) {
      if(imported_native_ca) {
        infof(data, "error importing CA certificate blob, continuing anyway");
      }
      else {
        failf(data, "error importing CA certificate blob");
        return CURLE_SSL_CACERT_BADFILE;
      }
    }
    else {
      infof(data, "successfully imported CA certificate blob");
      wssl->x509_store_setup = TRUE;
    }
  }

#ifndef NO_FILESYSTEM
  /* load trusted cacert from file if not blob */

  CURL_TRC_CF(data, cf, "populate_x509_store, path=%s, blob=%d",
              ssl_cafile? ssl_cafile : "none", !!ca_info_blob);
  if(!store)
    return CURLE_OUT_OF_MEMORY;

  if((ssl_cafile || ssl_capath) && (!wssl->x509_store_setup)) {
    int rc =
      wolfSSL_CTX_load_verify_locations_ex(wssl->ctx,
                                           ssl_cafile,
                                           ssl_capath,
                                           WOLFSSL_LOAD_FLAG_IGNORE_ERR);
    if(SSL_SUCCESS != rc) {
      if(conn_config->verifypeer) {
        /* Fail if we insist on successfully verifying the server. */
        failf(data, "error setting certificate verify locations:"
              " CAfile: %s CApath: %s",
              ssl_cafile ? ssl_cafile : "none",
              ssl_capath ? ssl_capath : "none");
        return CURLE_SSL_CACERT_BADFILE;
      }
      else {
        /* Just continue with a warning if no strict certificate
           verification is required. */
        infof(data, "error setting certificate verify locations,"
              " continuing anyway:");
      }
    }
    else {
      /* Everything is fine. */
      infof(data, "successfully set certificate verify locations:");
    }
    infof(data, " CAfile: %s", ssl_cafile ? ssl_cafile : "none");
    infof(data, " CApath: %s", ssl_capath ? ssl_capath : "none");
    wssl->x509_store_setup = TRUE;
  }
#endif
  (void)store;
  return CURLE_OK;
}

/* key to use at `multi->proto_hash` */
#define MPROTO_WSSL_X509_KEY   "tls:wssl:x509:share"

struct wssl_x509_share {
  char *CAfile;         /* CAfile path used to generate X509 store */
  WOLFSSL_X509_STORE *store; /* cached X509 store or NULL if none */
  struct curltime time; /* when the cached store was created */
};

static void wssl_x509_share_free(void *key, size_t key_len, void *p)
{
  struct wssl_x509_share *share = p;
  DEBUGASSERT(key_len == (sizeof(MPROTO_WSSL_X509_KEY)-1));
  DEBUGASSERT(!memcmp(MPROTO_WSSL_X509_KEY, key, key_len));
  (void)key;
  (void)key_len;
  if(share->store) {
    wolfSSL_X509_STORE_free(share->store);
  }
  free(share->CAfile);
  free(share);
}

static bool
cached_x509_store_expired(const struct Curl_easy *data,
                          const struct wssl_x509_share *mb)
{
  const struct ssl_general_config *cfg = &data->set.general_ssl;
  struct curltime now = Curl_now();
  timediff_t elapsed_ms = Curl_timediff(now, mb->time);
  timediff_t timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000;

  if(timeout_ms < 0)
    return false;

  return elapsed_ms >= timeout_ms;
}

static bool
cached_x509_store_different(struct Curl_cfilter *cf,
                            const struct wssl_x509_share *mb)
{
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  if(!mb->CAfile || !conn_config->CAfile)
    return mb->CAfile != conn_config->CAfile;

  return strcmp(mb->CAfile, conn_config->CAfile);
}

static X509_STORE *get_cached_x509_store(struct Curl_cfilter *cf,
                                         const struct Curl_easy *data)
{
  struct Curl_multi *multi = data->multi;
  struct wssl_x509_share *share;
  WOLFSSL_X509_STORE *store = NULL;

  DEBUGASSERT(multi);
  share = multi? Curl_hash_pick(&multi->proto_hash,
                                (void *)MPROTO_WSSL_X509_KEY,
                                sizeof(MPROTO_WSSL_X509_KEY)-1) : NULL;
  if(share && share->store &&
     !cached_x509_store_expired(data, share) &&
     !cached_x509_store_different(cf, share)) {
    store = share->store;
  }

  return store;
}

static void set_cached_x509_store(struct Curl_cfilter *cf,
                                  const struct Curl_easy *data,
                                  X509_STORE *store)
{
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  struct Curl_multi *multi = data->multi;
  struct wssl_x509_share *share;

  DEBUGASSERT(multi);
  if(!multi)
    return;
  share = Curl_hash_pick(&multi->proto_hash,
                         (void *)MPROTO_WSSL_X509_KEY,
                         sizeof(MPROTO_WSSL_X509_KEY)-1);

  if(!share) {
    share = calloc(1, sizeof(*share));
    if(!share)
      return;
    if(!Curl_hash_add2(&multi->proto_hash,
                       (void *)MPROTO_WSSL_X509_KEY,
                       sizeof(MPROTO_WSSL_X509_KEY)-1,
                       share, wssl_x509_share_free)) {
      free(share);
      return;
    }
  }

  if(wolfSSL_X509_STORE_up_ref(store)) {
    char *CAfile = NULL;

    if(conn_config->CAfile) {
      CAfile = strdup(conn_config->CAfile);
      if(!CAfile) {
        X509_STORE_free(store);
        return;
      }
    }

    if(share->store) {
      X509_STORE_free(share->store);
      free(share->CAfile);
    }

    share->time = Curl_now();
    share->store = store;
    share->CAfile = CAfile;
  }
}

CURLcode Curl_wssl_setup_x509_store(struct Curl_cfilter *cf,
                                    struct Curl_easy *data,
                                    struct wolfssl_ctx *wssl)
{
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  CURLcode result = CURLE_OK;
  WOLFSSL_X509_STORE *cached_store;
  bool cache_criteria_met;

  /* Consider the X509 store cacheable if it comes exclusively from a CAfile,
     or no source is provided and we are falling back to OpenSSL's built-in
     default. */
  cache_criteria_met = (data->set.general_ssl.ca_cache_timeout != 0) &&
    conn_config->verifypeer &&
    !conn_config->CApath &&
    !conn_config->ca_info_blob &&
    !ssl_config->primary.CRLfile &&
    !ssl_config->native_ca_store;

  cached_store = get_cached_x509_store(cf, data);
  if(cached_store && cache_criteria_met
     && wolfSSL_X509_STORE_up_ref(cached_store)) {
    wolfSSL_CTX_set_cert_store(wssl->ctx, cached_store);
  }
  else {
    X509_STORE *store = wolfSSL_CTX_get_cert_store(wssl->ctx);

    result = populate_x509_store(cf, data, store, wssl);
    if(result == CURLE_OK && cache_criteria_met) {
      set_cached_x509_store(cf, data, store);
    }
  }

  return result;
}

/*
 * This function loads all the client/CA certificates and CRLs. Setup the TLS
 * layer and do all necessary magic.
 */
static CURLcode
wolfssl_connect_step1(struct Curl_cfilter *cf, struct Curl_easy *data)
{
  char *ciphers, *curves;
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  const struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  WOLFSSL_METHOD* req_method = NULL;
#ifdef HAVE_LIBOQS
  word16 oqsAlg = 0;
  size_t idx = 0;
#endif
#ifdef HAVE_SNI
  bool sni = FALSE;
#define use_sni(x)  sni = (x)
#else
#define use_sni(x)  Curl_nop_stmt
#endif

  DEBUGASSERT(backend);

  if(connssl->state == ssl_connection_complete)
    return CURLE_OK;

  if(conn_config->version_max != CURL_SSLVERSION_MAX_NONE) {
    failf(data, "wolfSSL does not support to set maximum SSL/TLS version");
    return CURLE_SSL_CONNECT_ERROR;
  }

  /* check to see if we have been told to use an explicit SSL/TLS version */
  switch(conn_config->version) {
  case CURL_SSLVERSION_DEFAULT:
  case CURL_SSLVERSION_TLSv1:
#if LIBWOLFSSL_VERSION_HEX >= 0x03003000 /* >= 3.3.0 */
    /* minimum protocol version is set later after the CTX object is created */
    req_method = SSLv23_client_method();
#else
    infof(data, "wolfSSL <3.3.0 cannot be configured to use TLS 1.0-1.2, "
          "TLS 1.0 is used exclusively");
    req_method = TLSv1_client_method();
#endif
    use_sni(TRUE);
    break;
  case CURL_SSLVERSION_TLSv1_0:
#if defined(WOLFSSL_ALLOW_TLSV10) && !defined(NO_OLD_TLS)
    req_method = TLSv1_client_method();
    use_sni(TRUE);
    break;
#else
    failf(data, "wolfSSL does not support TLS 1.0");
    return CURLE_NOT_BUILT_IN;
#endif
  case CURL_SSLVERSION_TLSv1_1:
#ifndef NO_OLD_TLS
    req_method = TLSv1_1_client_method();
    use_sni(TRUE);
    break;
#else
    failf(data, "wolfSSL does not support TLS 1.1");
    return CURLE_NOT_BUILT_IN;
#endif
  case CURL_SSLVERSION_TLSv1_2:
#ifndef WOLFSSL_NO_TLS12
    req_method = TLSv1_2_client_method();
    use_sni(TRUE);
#else
    failf(data, "wolfSSL does not support TLS 1.2");
    return CURLE_NOT_BUILT_IN;
#endif
    break;
  case CURL_SSLVERSION_TLSv1_3:
#ifdef WOLFSSL_TLS13
    req_method = wolfTLSv1_3_client_method();
    use_sni(TRUE);
    break;
#else
    failf(data, "wolfSSL: TLS 1.3 is not yet supported");
    return CURLE_SSL_CONNECT_ERROR;
#endif
  default:
    failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
    return CURLE_SSL_CONNECT_ERROR;
  }

  if(!req_method) {
    failf(data, "SSL: could not create a method");
    return CURLE_OUT_OF_MEMORY;
  }

  if(backend->ctx)
    wolfSSL_CTX_free(backend->ctx);
  backend->ctx = wolfSSL_CTX_new(req_method);

  if(!backend->ctx) {
    failf(data, "SSL: could not create a context");
    return CURLE_OUT_OF_MEMORY;
  }

  switch(conn_config->version) {
  case CURL_SSLVERSION_DEFAULT:
  case CURL_SSLVERSION_TLSv1:
#if LIBWOLFSSL_VERSION_HEX > 0x03004006 /* > 3.4.6 */
    /* Versions 3.3.0 to 3.4.6 we know the minimum protocol version is
     * whatever minimum version of TLS was built in and at least TLS 1.0. For
     * later library versions that could change (eg TLS 1.0 built in but
     * defaults to TLS 1.1) so we have this short circuit evaluation to find
     * the minimum supported TLS version.
    */
    if((wolfSSL_CTX_SetMinVersion(backend->ctx, WOLFSSL_TLSV1) != 1) &&
       (wolfSSL_CTX_SetMinVersion(backend->ctx, WOLFSSL_TLSV1_1) != 1) &&
       (wolfSSL_CTX_SetMinVersion(backend->ctx, WOLFSSL_TLSV1_2) != 1)
#ifdef WOLFSSL_TLS13
       && (wolfSSL_CTX_SetMinVersion(backend->ctx, WOLFSSL_TLSV1_3) != 1)
#endif
      ) {
      failf(data, "SSL: could not set the minimum protocol version");
      return CURLE_SSL_CONNECT_ERROR;
    }
#endif
    FALLTHROUGH();
  default:
    break;
  }

  ciphers = conn_config->cipher_list;
  if(ciphers) {
    if(!SSL_CTX_set_cipher_list(backend->ctx, ciphers)) {
      failf(data, "failed setting cipher list: %s", ciphers);
      return CURLE_SSL_CIPHER;
    }
    infof(data, "Cipher selection: %s", ciphers);
  }

  curves = conn_config->curves;
  if(curves) {

#ifdef HAVE_LIBOQS
    for(idx = 0; gnm[idx].name != NULL; idx++) {
      if(strncmp(curves, gnm[idx].name, strlen(gnm[idx].name)) == 0) {
        oqsAlg = gnm[idx].group;
        break;
      }
    }

    if(oqsAlg == 0)
#endif
    {
      if(!SSL_CTX_set1_curves_list(backend->ctx, curves)) {
        failf(data, "failed setting curves list: '%s'", curves);
        return CURLE_SSL_CIPHER;
      }
    }
  }

#ifndef NO_FILESYSTEM
  /* Load the client certificate, and private key */
  if(ssl_config->primary.clientcert) {
    char *key_file = ssl_config->key;
    int file_type = do_file_type(ssl_config->cert_type);

    if(file_type == WOLFSSL_FILETYPE_PEM) {
      if(wolfSSL_CTX_use_certificate_chain_file(backend->ctx,
                                                ssl_config->primary.clientcert)
         != 1) {
        failf(data, "unable to use client certificate");
        return CURLE_SSL_CONNECT_ERROR;
      }
    }
    else if(file_type == WOLFSSL_FILETYPE_ASN1) {
      if(wolfSSL_CTX_use_certificate_file(backend->ctx,
                                          ssl_config->primary.clientcert,
                                          file_type) != 1) {
        failf(data, "unable to use client certificate");
        return CURLE_SSL_CONNECT_ERROR;
      }
    }
    else {
      failf(data, "unknown cert type");
      return CURLE_BAD_FUNCTION_ARGUMENT;
    }

    if(!key_file)
      key_file = ssl_config->primary.clientcert;
    else
      file_type = do_file_type(ssl_config->key_type);

    if(wolfSSL_CTX_use_PrivateKey_file(backend->ctx, key_file,
                                       file_type) != 1) {
      failf(data, "unable to set private key");
      return CURLE_SSL_CONNECT_ERROR;
    }
  }
#endif /* !NO_FILESYSTEM */

  /* SSL always tries to verify the peer, this only says whether it should
   * fail to connect if the verification fails, or if it should continue
   * anyway. In the latter case the result of the verification is checked with
   * SSL_get_verify_result() below. */
  wolfSSL_CTX_set_verify(backend->ctx,
                         conn_config->verifypeer?SSL_VERIFY_PEER:
                         SSL_VERIFY_NONE, NULL);

#ifdef HAVE_SNI
  if(sni && connssl->peer.sni) {
    size_t sni_len = strlen(connssl->peer.sni);
    if((sni_len < USHRT_MAX)) {
      if(wolfSSL_CTX_UseSNI(backend->ctx, WOLFSSL_SNI_HOST_NAME,
                            connssl->peer.sni,
                            (unsigned short)sni_len) != 1) {
        failf(data, "Failed to set SNI");
        return CURLE_SSL_CONNECT_ERROR;
      }
    }
  }
#endif

  /* give application a chance to interfere with SSL set up. */
  if(data->set.ssl.fsslctx) {
    CURLcode result = (*data->set.ssl.fsslctx)(data, backend->ctx,
                                               data->set.ssl.fsslctxp);
    if(result) {
      failf(data, "error signaled by ssl ctx callback");
      return result;
    }
  }
#ifdef NO_FILESYSTEM
  else if(conn_config->verifypeer) {
    failf(data, "SSL: Certificates cannot be loaded because wolfSSL was built"
          " with \"no filesystem\". Either disable peer verification"
          " (insecure) or if you are building an application with libcurl you"
          " can load certificates via CURLOPT_SSL_CTX_FUNCTION.");
    return CURLE_SSL_CONNECT_ERROR;
  }
#endif

  /* Let's make an SSL structure */
  if(backend->handle)
    wolfSSL_free(backend->handle);
  backend->handle = wolfSSL_new(backend->ctx);
  if(!backend->handle) {
    failf(data, "SSL: could not create a handle");
    return CURLE_OUT_OF_MEMORY;
  }

#ifdef HAVE_LIBOQS
  if(oqsAlg) {
    if(wolfSSL_UseKeyShare(backend->handle, oqsAlg) != WOLFSSL_SUCCESS) {
      failf(data, "unable to use oqs KEM");
    }
  }
#endif

#ifdef HAVE_ALPN
  if(connssl->alpn) {
    struct alpn_proto_buf proto;
    CURLcode result;

    result = Curl_alpn_to_proto_str(&proto, connssl->alpn);
    if(result ||
       wolfSSL_UseALPN(backend->handle,
                       (char *)proto.data, (unsigned int)proto.len,
                       WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) != SSL_SUCCESS) {
      failf(data, "SSL: failed setting ALPN protocols");
      return CURLE_SSL_CONNECT_ERROR;
    }
    infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
  }
#endif /* HAVE_ALPN */

#ifdef OPENSSL_EXTRA
  if(Curl_tls_keylog_enabled()) {
    /* Ensure the Client Random is preserved. */
    wolfSSL_KeepArrays(backend->handle);
#if defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13)
    wolfSSL_set_tls13_secret_cb(backend->handle,
                                wolfssl_tls13_secret_callback, NULL);
#endif
  }
#endif /* OPENSSL_EXTRA */

#ifdef HAVE_SECURE_RENEGOTIATION
  if(wolfSSL_UseSecureRenegotiation(backend->handle) != SSL_SUCCESS) {
    failf(data, "SSL: failed setting secure renegotiation");
    return CURLE_SSL_CONNECT_ERROR;
  }
#endif /* HAVE_SECURE_RENEGOTIATION */

  /* Check if there is a cached ID we can/should use here! */
  if(ssl_config->primary.cache_session) {
    void *ssl_sessionid = NULL;

    Curl_ssl_sessionid_lock(data);
    if(!Curl_ssl_getsessionid(cf, data, &connssl->peer,
                              &ssl_sessionid, NULL)) {
      /* we got a session id, use it! */
      if(!SSL_set_session(backend->handle, ssl_sessionid)) {
        Curl_ssl_delsessionid(data, ssl_sessionid);
        infof(data, "cannot use session ID, going on without");
      }
      else
        infof(data, "SSL reusing session ID");
    }
    Curl_ssl_sessionid_unlock(data);
  }

#ifdef USE_ECH
  if(ECH_ENABLED(data)) {
    int trying_ech_now = 0;

    if(data->set.str[STRING_ECH_PUBLIC]) {
      infof(data, "ECH: outername not (yet) supported with wolfSSL");
      return CURLE_SSL_CONNECT_ERROR;
    }
    if(data->set.tls_ech == CURLECH_GREASE) {
      infof(data, "ECH: GREASE'd ECH not yet supported for wolfSSL");
      return CURLE_SSL_CONNECT_ERROR;
    }
    if(data->set.tls_ech & CURLECH_CLA_CFG
       && data->set.str[STRING_ECH_CONFIG]) {
      char *b64val = data->set.str[STRING_ECH_CONFIG];
      word32 b64len = 0;

      b64len = (word32) strlen(b64val);
      if(b64len
         && wolfSSL_SetEchConfigsBase64(backend->handle, b64val, b64len)
              != WOLFSSL_SUCCESS) {
        if(data->set.tls_ech & CURLECH_HARD)
          return CURLE_SSL_CONNECT_ERROR;
      }
      else {
       trying_ech_now = 1;
       infof(data, "ECH: ECHConfig from command line");
      }
    }
    else {
      struct Curl_dns_entry *dns = NULL;

      dns = Curl_fetch_addr(data, connssl->peer.hostname, connssl->peer.port);
      if(!dns) {
        infof(data, "ECH: requested but no DNS info available");
        if(data->set.tls_ech & CURLECH_HARD)
          return CURLE_SSL_CONNECT_ERROR;
      }
      else {
        struct Curl_https_rrinfo *rinfo = NULL;

        rinfo = dns->hinfo;
        if(rinfo && rinfo->echconfiglist) {
          unsigned char *ecl = rinfo->echconfiglist;
          size_t elen = rinfo->echconfiglist_len;

          infof(data, "ECH: ECHConfig from DoH HTTPS RR");
          if(wolfSSL_SetEchConfigs(backend->handle, ecl, (word32) elen) !=
                WOLFSSL_SUCCESS) {
            infof(data, "ECH: wolfSSL_SetEchConfigs failed");
            if(data->set.tls_ech & CURLECH_HARD)
              return CURLE_SSL_CONNECT_ERROR;
          }
          else {
            trying_ech_now = 1;
            infof(data, "ECH: imported ECHConfigList of length %ld", elen);
          }
        }
        else {
          infof(data, "ECH: requested but no ECHConfig available");
          if(data->set.tls_ech & CURLECH_HARD)
            return CURLE_SSL_CONNECT_ERROR;
        }
        Curl_resolv_unlock(data, dns);
      }
    }

    if(trying_ech_now
       && SSL_set_min_proto_version(backend->handle, TLS1_3_VERSION) != 1) {
      infof(data, "ECH: cannot force TLSv1.3 [ERROR]");
      return CURLE_SSL_CONNECT_ERROR;
    }

  }
#endif  /* USE_ECH */

#ifdef USE_BIO_CHAIN
  {
    WOLFSSL_BIO *bio;

    bio = BIO_new(wolfssl_bio_cf_method);
    if(!bio)
      return CURLE_OUT_OF_MEMORY;

    wolfSSL_BIO_set_data(bio, cf);
    wolfSSL_set_bio(backend->handle, bio, bio);
  }
#else /* USE_BIO_CHAIN */
  /* pass the raw socket into the SSL layer */
  if(!wolfSSL_set_fd(backend->handle,
                     (int)Curl_conn_cf_get_socket(cf, data))) {
    failf(data, "SSL: SSL_set_fd failed");
    return CURLE_SSL_CONNECT_ERROR;
  }
#endif /* !USE_BIO_CHAIN */

  connssl->connecting_state = ssl_connect_2;
  return CURLE_OK;
}


static char *wolfssl_strerror(unsigned long error, char *buf,
                              unsigned long size)
{
  DEBUGASSERT(size);
  *buf = '\0';

  wolfSSL_ERR_error_string_n(error, buf, size);

  if(!*buf) {
    const char *msg = error ? "Unknown error" : "No error";
    strncpy(buf, msg, size - 1);
    buf[size - 1] = '\0';
  }

  return buf;
}


static CURLcode
wolfssl_connect_step2(struct Curl_cfilter *cf, struct Curl_easy *data)
{
  int ret = -1;
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
#ifndef CURL_DISABLE_PROXY
  const char * const pinnedpubkey = Curl_ssl_cf_is_proxy(cf)?
    data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY]:
    data->set.str[STRING_SSL_PINNEDPUBLICKEY];
#else
  const char * const pinnedpubkey = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
#endif

  DEBUGASSERT(backend);

  wolfSSL_ERR_clear_error();

  /* Enable RFC2818 checks */
  if(conn_config->verifyhost) {
    char *snihost = connssl->peer.sni?
                    connssl->peer.sni : connssl->peer.hostname;
    if(wolfSSL_check_domain_name(backend->handle, snihost) == SSL_FAILURE)
      return CURLE_SSL_CONNECT_ERROR;
  }

  if(!backend->x509_store_setup) {
    /* After having send off the ClientHello, we prepare the x509
     * store to verify the coming certificate from the server */
    CURLcode result;
    struct wolfssl_ctx wssl;
    wssl.ctx = backend->ctx;
    wssl.handle = backend->handle;
    wssl.io_result = CURLE_OK;
    wssl.x509_store_setup = FALSE;
    result = Curl_wssl_setup_x509_store(cf, data, &wssl);
    if(result)
      return result;
    backend->x509_store_setup = wssl.x509_store_setup;
  }

  connssl->io_need = CURL_SSL_IO_NEED_NONE;
  ret = wolfSSL_connect(backend->handle);

#ifdef OPENSSL_EXTRA
  if(Curl_tls_keylog_enabled()) {
    /* If key logging is enabled, wait for the handshake to complete and then
     * proceed with logging secrets (for TLS 1.2 or older).
     *
     * During the handshake (ret==-1), wolfSSL_want_read() is true as it waits
     * for the server response. At that point the master secret is not yet
     * available, so we must not try to read it.
     * To log the secret on completion with a handshake failure, detect
     * completion via the observation that there is nothing to read or write.
     * Note that OpenSSL SSL_want_read() is always true here. If wolfSSL ever
     * changes, the worst case is that no key is logged on error.
     */
    if(ret == SSL_SUCCESS ||
       (!wolfSSL_want_read(backend->handle) &&
        !wolfSSL_want_write(backend->handle))) {
      wolfssl_log_tls12_secret(backend->handle);
      /* Client Random and master secrets are no longer needed, erase these.
       * Ignored while the handshake is still in progress. */
      wolfSSL_FreeArrays(backend->handle);
    }
  }
#endif  /* OPENSSL_EXTRA */

  if(ret != 1) {
    int detail = wolfSSL_get_error(backend->handle, ret);

    if(SSL_ERROR_WANT_READ == detail) {
      connssl->io_need = CURL_SSL_IO_NEED_RECV;
      return CURLE_OK;
    }
    else if(SSL_ERROR_WANT_WRITE == detail) {
      connssl->io_need = CURL_SSL_IO_NEED_SEND;
      return CURLE_OK;
    }
    /* There is no easy way to override only the CN matching.
     * This will enable the override of both mismatching SubjectAltNames
     * as also mismatching CN fields */
    else if(DOMAIN_NAME_MISMATCH == detail) {
#if 1
      failf(data, " subject alt name(s) or common name do not match \"%s\"",
            connssl->peer.dispname);
      return CURLE_PEER_FAILED_VERIFICATION;
#else
      /* When the wolfssl_check_domain_name() is used and you desire to
       * continue on a DOMAIN_NAME_MISMATCH, i.e. 'ssl_config.verifyhost
       * == 0', CyaSSL version 2.4.0 will fail with an INCOMPLETE_DATA
       * error. The only way to do this is currently to switch the
       * Wolfssl_check_domain_name() in and out based on the
       * 'ssl_config.verifyhost' value. */
      if(conn_config->verifyhost) {
        failf(data,
              " subject alt name(s) or common name do not match \"%s\"\n",
              connssl->dispname);
        return CURLE_PEER_FAILED_VERIFICATION;
      }
      else {
        infof(data,
              " subject alt name(s) and/or common name do not match \"%s\"",
              connssl->dispname);
        return CURLE_OK;
      }
#endif
    }
#if LIBWOLFSSL_VERSION_HEX >= 0x02007000 /* 2.7.0 */
    else if(ASN_NO_SIGNER_E == detail) {
      if(conn_config->verifypeer) {
        failf(data, " CA signer not available for verification");
        return CURLE_SSL_CACERT_BADFILE;
      }
      else {
        /* Just continue with a warning if no strict certificate
           verification is required. */
        infof(data, "CA signer not available for verification, "
                    "continuing anyway");
      }
    }
#endif
#ifdef USE_ECH
    else if(-1 == detail) {
      /* try access a retry_config ECHConfigList for tracing */
      byte echConfigs[1000];
      word32 echConfigsLen = 1000;
      int rv = 0;

      /* this currently does not produce the retry_configs */
      rv = wolfSSL_GetEchConfigs(backend->handle, echConfigs,
                                 &echConfigsLen);
      if(rv != WOLFSSL_SUCCESS) {
        infof(data, "Failed to get ECHConfigs");
      }
      else {
        char *b64str = NULL;
        size_t blen = 0;

        rv = Curl_base64_encode((const char *)echConfigs, echConfigsLen,
                                &b64str, &blen);
        if(!rv && b64str)
          infof(data, "ECH: (not yet) retry_configs %s", b64str);
        free(b64str);
      }
    }
#endif
    else if(backend->io_result == CURLE_AGAIN) {
      return CURLE_OK;
    }
    else {
      char error_buffer[256];
      failf(data, "SSL_connect failed with error %d: %s", detail,
            wolfssl_strerror((unsigned long)detail, error_buffer,
                             sizeof(error_buffer)));
      return CURLE_SSL_CONNECT_ERROR;
    }
  }

  if(pinnedpubkey) {
#ifdef KEEP_PEER_CERT
    X509 *x509;
    const char *x509_der;
    int x509_der_len;
    struct Curl_X509certificate x509_parsed;
    struct Curl_asn1Element *pubkey;
    CURLcode result;

    x509 = wolfSSL_get_peer_certificate(backend->handle);
    if(!x509) {
      failf(data, "SSL: failed retrieving server certificate");
      return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
    }

    x509_der = (const char *)wolfSSL_X509_get_der(x509, &x509_der_len);
    if(!x509_der) {
      failf(data, "SSL: failed retrieving ASN.1 server certificate");
      return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
    }

    memset(&x509_parsed, 0, sizeof(x509_parsed));
    if(Curl_parseX509(&x509_parsed, x509_der, x509_der + x509_der_len))
      return CURLE_SSL_PINNEDPUBKEYNOTMATCH;

    pubkey = &x509_parsed.subjectPublicKeyInfo;
    if(!pubkey->header || pubkey->end <= pubkey->header) {
      failf(data, "SSL: failed retrieving public key from server certificate");
      return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
    }

    result = Curl_pin_peer_pubkey(data,
                                  pinnedpubkey,
                                  (const unsigned char *)pubkey->header,
                                  (size_t)(pubkey->end - pubkey->header));
    wolfSSL_FreeX509(x509);
    if(result) {
      failf(data, "SSL: public key does not match pinned public key");
      return result;
    }
#else
    failf(data, "Library lacks pinning support built-in");
    return CURLE_NOT_BUILT_IN;
#endif
  }

#ifdef HAVE_ALPN
  if(connssl->alpn) {
    int rc;
    char *protocol = NULL;
    unsigned short protocol_len = 0;

    rc = wolfSSL_ALPN_GetProtocol(backend->handle, &protocol, &protocol_len);

    if(rc == SSL_SUCCESS) {
      Curl_alpn_set_negotiated(cf, data, (const unsigned char *)protocol,
                               protocol_len);
    }
    else if(rc == SSL_ALPN_NOT_FOUND)
      Curl_alpn_set_negotiated(cf, data, NULL, 0);
    else {
      failf(data, "ALPN, failure getting protocol, error %d", rc);
      return CURLE_SSL_CONNECT_ERROR;
    }
  }
#endif /* HAVE_ALPN */

  connssl->connecting_state = ssl_connect_3;
#if (LIBWOLFSSL_VERSION_HEX >= 0x03009010)
  infof(data, "SSL connection using %s / %s",
        wolfSSL_get_version(backend->handle),
        wolfSSL_get_cipher_name(backend->handle));
#else
  infof(data, "SSL connected");
#endif

  return CURLE_OK;
}


static void wolfssl_session_free(void *sessionid, size_t idsize)
{
  (void)idsize;
  wolfSSL_SESSION_free(sessionid);
}


static CURLcode
wolfssl_connect_step3(struct Curl_cfilter *cf, struct Curl_easy *data)
{
  CURLcode result = CURLE_OK;
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;
  const struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);

  DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
  DEBUGASSERT(backend);

  if(ssl_config->primary.cache_session) {
    /* wolfSSL_get1_session allocates memory that has to be freed. */
    WOLFSSL_SESSION *our_ssl_sessionid = wolfSSL_get1_session(backend->handle);

    if(our_ssl_sessionid) {
      Curl_ssl_sessionid_lock(data);
      /* call takes ownership of `our_ssl_sessionid` */
      result = Curl_ssl_set_sessionid(cf, data, &connssl->peer,
                                      our_ssl_sessionid, 0,
                                      wolfssl_session_free);
      Curl_ssl_sessionid_unlock(data);
      if(result) {
        failf(data, "failed to store ssl session");
        return result;
      }
    }
  }

  connssl->connecting_state = ssl_connect_done;

  return result;
}


static ssize_t wolfssl_send(struct Curl_cfilter *cf,
                            struct Curl_easy *data,
                            const void *mem,
                            size_t len,
                            CURLcode *curlcode)
{
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;
  int memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
  int rc;

  DEBUGASSERT(backend);

  wolfSSL_ERR_clear_error();

  rc = wolfSSL_write(backend->handle, mem, memlen);
  if(rc <= 0) {
    int err = wolfSSL_get_error(backend->handle, rc);

    switch(err) {
    case SSL_ERROR_WANT_READ:
    case SSL_ERROR_WANT_WRITE:
      /* there is data pending, re-invoke SSL_write() */
      CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> AGAIN", len);
      *curlcode = CURLE_AGAIN;
      return -1;
    default:
      if(backend->io_result == CURLE_AGAIN) {
        CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> AGAIN", len);
        *curlcode = CURLE_AGAIN;
        return -1;
      }
      CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> %d, %d", len, rc, err);
      {
        char error_buffer[256];
        failf(data, "SSL write: %s, errno %d",
              wolfssl_strerror((unsigned long)err, error_buffer,
                               sizeof(error_buffer)),
              SOCKERRNO);
      }
      *curlcode = CURLE_SEND_ERROR;
      return -1;
    }
  }
  CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> %d", len, rc);
  return rc;
}

static CURLcode wolfssl_shutdown(struct Curl_cfilter *cf,
                                 struct Curl_easy *data,
                                 bool send_shutdown, bool *done)
{
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *wctx = (struct wolfssl_ctx *)connssl->backend;
  CURLcode result = CURLE_OK;
  char buf[1024];
  int nread, err;

  DEBUGASSERT(wctx);
  if(!wctx->handle || cf->shutdown) {
    *done = TRUE;
    goto out;
  }

  connssl->io_need = CURL_SSL_IO_NEED_NONE;
  *done = FALSE;
  if(!(wolfSSL_get_shutdown(wctx->handle) & SSL_SENT_SHUTDOWN)) {
    /* We have not started the shutdown from our side yet. Check
     * if the server already sent us one. */
    ERR_clear_error();
    nread = wolfSSL_read(wctx->handle, buf, (int)sizeof(buf));
    err = wolfSSL_get_error(wctx->handle, nread);
    if(!nread && err == SSL_ERROR_ZERO_RETURN) {
      bool input_pending;
      /* Yes, it did. */
      if(!send_shutdown) {
        CURL_TRC_CF(data, cf, "SSL shutdown received, not sending");
        *done = TRUE;
        goto out;
      }
      else if(!cf->next->cft->is_alive(cf->next, data, &input_pending)) {
        /* Server closed the connection after its closy notify. It
         * seems not interested to see our close notify, so do not
         * send it. We are done. */
        CURL_TRC_CF(data, cf, "peer closed connection");
        connssl->peer_closed = TRUE;
        *done = TRUE;
        goto out;
      }
    }
  }

  if(send_shutdown && wolfSSL_shutdown(wctx->handle) == 1) {
    CURL_TRC_CF(data, cf, "SSL shutdown finished");
    *done = TRUE;
    goto out;
  }
  else {
    size_t i;
    /* SSL should now have started the shutdown from our side. Since it
     * was not complete, we are lacking the close notify from the server. */
    for(i = 0; i < 10; ++i) {
      ERR_clear_error();
      nread = wolfSSL_read(wctx->handle, buf, (int)sizeof(buf));
      if(nread <= 0)
        break;
    }
    err = wolfSSL_get_error(wctx->handle, nread);
    switch(err) {
    case SSL_ERROR_ZERO_RETURN: /* no more data */
      CURL_TRC_CF(data, cf, "SSL shutdown received");
      *done = TRUE;
      break;
    case SSL_ERROR_NONE: /* just did not get anything */
    case SSL_ERROR_WANT_READ:
      /* SSL has send its notify and now wants to read the reply
       * from the server. We are not really interested in that. */
      CURL_TRC_CF(data, cf, "SSL shutdown sent, want receive");
      connssl->io_need = CURL_SSL_IO_NEED_RECV;
      break;
    case SSL_ERROR_WANT_WRITE:
      CURL_TRC_CF(data, cf, "SSL shutdown send blocked");
      connssl->io_need = CURL_SSL_IO_NEED_SEND;
      break;
    default: {
      char error_buffer[256];
      int detail = wolfSSL_get_error(wctx->handle, err);
      CURL_TRC_CF(data, cf, "SSL shutdown, error: '%s'(%d)",
                  wolfssl_strerror((unsigned long)err, error_buffer,
                                   sizeof(error_buffer)),
                  detail);
      result = CURLE_RECV_ERROR;
      break;
    }
    }
  }

out:
  cf->shutdown = (result || *done);
  return result;
}

static void wolfssl_close(struct Curl_cfilter *cf, struct Curl_easy *data)
{
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;

  (void) data;

  DEBUGASSERT(backend);

  if(backend->handle) {
    wolfSSL_free(backend->handle);
    backend->handle = NULL;
  }
  if(backend->ctx) {
    wolfSSL_CTX_free(backend->ctx);
    backend->ctx = NULL;
  }
}

static ssize_t wolfssl_recv(struct Curl_cfilter *cf,
                            struct Curl_easy *data,
                            char *buf, size_t blen,
                            CURLcode *curlcode)
{
  struct ssl_connect_data *connssl = cf->ctx;
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;
  int buffsize = (blen > (size_t)INT_MAX) ? INT_MAX : (int)blen;
  int nread;

  DEBUGASSERT(backend);

  wolfSSL_ERR_clear_error();
  *curlcode = CURLE_OK;

  nread = wolfSSL_read(backend->handle, buf, buffsize);

  if(nread <= 0) {
    int err = wolfSSL_get_error(backend->handle, nread);

    switch(err) {
    case SSL_ERROR_ZERO_RETURN: /* no more data */
      CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> CLOSED", blen);
      *curlcode = CURLE_OK;
      return 0;
    case SSL_ERROR_NONE:
    case SSL_ERROR_WANT_READ:
    case SSL_ERROR_WANT_WRITE:
      /* there is data pending, re-invoke wolfSSL_read() */
      CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> AGAIN", blen);
      *curlcode = CURLE_AGAIN;
      return -1;
    default:
      if(backend->io_result == CURLE_AGAIN) {
        CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> AGAIN", blen);
        *curlcode = CURLE_AGAIN;
        return -1;
      }
      {
        char error_buffer[256];
        failf(data, "SSL read: %s, errno %d",
              wolfssl_strerror((unsigned long)err, error_buffer,
                               sizeof(error_buffer)),
              SOCKERRNO);
      }
      *curlcode = CURLE_RECV_ERROR;
      return -1;
    }
  }
  CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> %d", blen, nread);
  return nread;
}


static size_t wolfssl_version(char *buffer, size_t size)
{
#if LIBWOLFSSL_VERSION_HEX >= 0x03006000
  return msnprintf(buffer, size, "wolfSSL/%s", wolfSSL_lib_version());
#elif defined(WOLFSSL_VERSION)
  return msnprintf(buffer, size, "wolfSSL/%s", WOLFSSL_VERSION);
#endif
}


static int wolfssl_init(void)
{
  int ret;

#ifdef OPENSSL_EXTRA
  Curl_tls_keylog_open();
#endif
  ret = (wolfSSL_Init() == SSL_SUCCESS);
  wolfssl_bio_cf_init_methods();
  return ret;
}


static void wolfssl_cleanup(void)
{
  wolfssl_bio_cf_free_methods();
  wolfSSL_Cleanup();
#ifdef OPENSSL_EXTRA
  Curl_tls_keylog_close();
#endif
}


static bool wolfssl_data_pending(struct Curl_cfilter *cf,
                                 const struct Curl_easy *data)
{
  struct ssl_connect_data *ctx = cf->ctx;
  struct wolfssl_ctx *backend;

  (void)data;
  DEBUGASSERT(ctx && ctx->backend);

  backend = (struct wolfssl_ctx *)ctx->backend;
  if(backend->handle)   /* SSL is in use */
    return (0 != wolfSSL_pending(backend->handle)) ? TRUE : FALSE;
  else
    return FALSE;
}

static CURLcode
wolfssl_connect_common(struct Curl_cfilter *cf,
                       struct Curl_easy *data,
                       bool nonblocking,
                       bool *done)
{
  CURLcode result;
  struct ssl_connect_data *connssl = cf->ctx;
  curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data);
  int what;

  /* check if the connection has already been established */
  if(ssl_connection_complete == connssl->state) {
    *done = TRUE;
    return CURLE_OK;
  }

  if(ssl_connect_1 == connssl->connecting_state) {
    /* Find out how much more time we are allowed */
    const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);

    if(timeout_ms < 0) {
      /* no need to continue if time already is up */
      failf(data, "SSL connection timeout");
      return CURLE_OPERATION_TIMEDOUT;
    }

    result = wolfssl_connect_step1(cf, data);
    if(result)
      return result;
  }

  while(ssl_connect_2 == connssl->connecting_state) {

    /* check allowed time left */
    const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);

    if(timeout_ms < 0) {
      /* no need to continue if time already is up */
      failf(data, "SSL connection timeout");
      return CURLE_OPERATION_TIMEDOUT;
    }

    /* if ssl is expecting something, check if it is available. */
    if(connssl->io_need) {

      curl_socket_t writefd = (connssl->io_need & CURL_SSL_IO_NEED_SEND)?
                              sockfd:CURL_SOCKET_BAD;
      curl_socket_t readfd = (connssl->io_need & CURL_SSL_IO_NEED_RECV)?
                             sockfd:CURL_SOCKET_BAD;

      what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
                               nonblocking?0:timeout_ms);
      if(what < 0) {
        /* fatal error */
        failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
        return CURLE_SSL_CONNECT_ERROR;
      }
      else if(0 == what) {
        if(nonblocking) {
          *done = FALSE;
          return CURLE_OK;
        }
        else {
          /* timeout */
          failf(data, "SSL connection timeout");
          return CURLE_OPERATION_TIMEDOUT;
        }
      }
      /* socket is readable or writable */
    }

    /* Run transaction, and return to the caller if it failed or if
     * this connection is part of a multi handle and this loop would
     * execute again. This permits the owner of a multi handle to
     * abort a connection attempt before step2 has completed while
     * ensuring that a client using select() or epoll() will always
     * have a valid fdset to wait on.
     */
    result = wolfssl_connect_step2(cf, data);
    if(result || (nonblocking && (ssl_connect_2 == connssl->connecting_state)))
      return result;
  } /* repeat step2 until all transactions are done. */

  if(ssl_connect_3 == connssl->connecting_state) {
    result = wolfssl_connect_step3(cf, data);
    if(result)
      return result;
  }

  if(ssl_connect_done == connssl->connecting_state) {
    connssl->state = ssl_connection_complete;
    *done = TRUE;
  }
  else
    *done = FALSE;

  /* Reset our connect state machine */
  connssl->connecting_state = ssl_connect_1;

  return CURLE_OK;
}


static CURLcode wolfssl_connect_nonblocking(struct Curl_cfilter *cf,
                                            struct Curl_easy *data,
                                            bool *done)
{
  return wolfssl_connect_common(cf, data, TRUE, done);
}


static CURLcode wolfssl_connect(struct Curl_cfilter *cf,
                                struct Curl_easy *data)
{
  CURLcode result;
  bool done = FALSE;

  result = wolfssl_connect_common(cf, data, FALSE, &done);
  if(result)
    return result;

  DEBUGASSERT(done);

  return CURLE_OK;
}

static CURLcode wolfssl_random(struct Curl_easy *data,
                               unsigned char *entropy, size_t length)
{
  WC_RNG rng;
  (void)data;
  if(wc_InitRng(&rng))
    return CURLE_FAILED_INIT;
  if(length > UINT_MAX)
    return CURLE_FAILED_INIT;
  if(wc_RNG_GenerateBlock(&rng, entropy, (unsigned)length))
    return CURLE_FAILED_INIT;
  if(wc_FreeRng(&rng))
    return CURLE_FAILED_INIT;
  return CURLE_OK;
}

static CURLcode wolfssl_sha256sum(const unsigned char *tmp, /* input */
                                  size_t tmplen,
                                  unsigned char *sha256sum /* output */,
                                  size_t unused)
{
  wc_Sha256 SHA256pw;
  (void)unused;
  if(wc_InitSha256(&SHA256pw))
    return CURLE_FAILED_INIT;
  wc_Sha256Update(&SHA256pw, tmp, (word32)tmplen);
  wc_Sha256Final(&SHA256pw, sha256sum);
  return CURLE_OK;
}

static void *wolfssl_get_internals(struct ssl_connect_data *connssl,
                                   CURLINFO info UNUSED_PARAM)
{
  struct wolfssl_ctx *backend =
    (struct wolfssl_ctx *)connssl->backend;
  (void)info;
  DEBUGASSERT(backend);
  return backend->handle;
}

const struct Curl_ssl Curl_ssl_wolfssl = {
  { CURLSSLBACKEND_WOLFSSL, "wolfssl" }, /* info */

#ifdef KEEP_PEER_CERT
  SSLSUPP_PINNEDPUBKEY |
#endif
#ifdef USE_BIO_CHAIN
  SSLSUPP_HTTPS_PROXY |
#endif
  SSLSUPP_CA_PATH |
  SSLSUPP_CAINFO_BLOB |
#ifdef USE_ECH
  SSLSUPP_ECH |
#endif
  SSLSUPP_SSL_CTX |
  SSLSUPP_CA_CACHE,

  sizeof(struct wolfssl_ctx),

  wolfssl_init,                    /* init */
  wolfssl_cleanup,                 /* cleanup */
  wolfssl_version,                 /* version */
  Curl_none_check_cxn,             /* check_cxn */
  wolfssl_shutdown,                /* shutdown */
  wolfssl_data_pending,            /* data_pending */
  wolfssl_random,                  /* random */
  Curl_none_cert_status_request,   /* cert_status_request */
  wolfssl_connect,                 /* connect */
  wolfssl_connect_nonblocking,     /* connect_nonblocking */
  Curl_ssl_adjust_pollset,         /* adjust_pollset */
  wolfssl_get_internals,           /* get_internals */
  wolfssl_close,                   /* close_one */
  Curl_none_close_all,             /* close_all */
  Curl_none_set_engine,            /* set_engine */
  Curl_none_set_engine_default,    /* set_engine_default */
  Curl_none_engines_list,          /* engines_list */
  Curl_none_false_start,           /* false_start */
  wolfssl_sha256sum,               /* sha256sum */
  NULL,                            /* associate_connection */
  NULL,                            /* disassociate_connection */
  wolfssl_recv,                    /* recv decrypted data */
  wolfssl_send,                    /* send data to encrypt */
};

#endif
