Home | History | Annotate | Line # | Download | only in apps
      1 /*
      2  * Copyright 1995-2026 The OpenSSL Project Authors. All Rights Reserved.
      3  * Copyright 2005 Nokia. All rights reserved.
      4  *
      5  * Licensed under the Apache License 2.0 (the "License").  You may not use
      6  * this file except in compliance with the License.  You can obtain a copy
      7  * in the file LICENSE in the source distribution or at
      8  * https://www.openssl.org/source/license.html
      9  */
     10 
     11 #include "internal/e_os.h"
     12 #include <ctype.h>
     13 #include <stdio.h>
     14 #include <stdlib.h>
     15 #include <string.h>
     16 #include <errno.h>
     17 #include <openssl/e_os2.h>
     18 #include "internal/nelem.h"
     19 #include "internal/sockets.h" /* for openssl_fdset() */
     20 
     21 #ifndef OPENSSL_NO_SOCK
     22 
     23 /*
     24  * With IPv6, it looks like Digital has mixed up the proper order of
     25  * recursive header file inclusion, resulting in the compiler complaining
     26  * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
     27  * needed to have fileno() declared correctly...  So let's define u_int
     28  */
     29 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
     30 #define __U_INT
     31 typedef unsigned int u_int;
     32 #endif
     33 
     34 #include "apps.h"
     35 #include "progs.h"
     36 #include <openssl/x509.h>
     37 #include <openssl/ssl.h>
     38 #include <openssl/err.h>
     39 #include <openssl/pem.h>
     40 #include <openssl/rand.h>
     41 #include <openssl/ocsp.h>
     42 #include <openssl/bn.h>
     43 #include <openssl/trace.h>
     44 #include <openssl/async.h>
     45 #ifndef OPENSSL_NO_CT
     46 #include <openssl/ct.h>
     47 #endif
     48 #include "s_apps.h"
     49 #include "timeouts.h"
     50 #include "internal/sockets.h"
     51 
     52 #if defined(__has_feature)
     53 #if __has_feature(memory_sanitizer)
     54 #include <sanitizer/msan_interface.h>
     55 #endif
     56 #endif
     57 
     58 #undef BUFSIZZ
     59 #define BUFSIZZ 1024 * 16
     60 #define S_CLIENT_IRC_READ_TIMEOUT 8
     61 
     62 #define USER_DATA_MODE_NONE 0
     63 #define USER_DATA_MODE_BASIC 1
     64 #define USER_DATA_MODE_ADVANCED 2
     65 
     66 #define USER_DATA_PROCESS_BAD_ARGUMENT 0
     67 #define USER_DATA_PROCESS_SHUT 1
     68 #define USER_DATA_PROCESS_RESTART 2
     69 #define USER_DATA_PROCESS_NO_DATA 3
     70 #define USER_DATA_PROCESS_CONTINUE 4
     71 
     72 struct user_data_st {
     73     /* SSL connection we are processing commands for */
     74     SSL *con;
     75 
     76     /* Buffer where we are storing data supplied by the user */
     77     char *buf;
     78 
     79     /* Allocated size of the buffer */
     80     size_t bufmax;
     81 
     82     /* Amount of the buffer actually used */
     83     size_t buflen;
     84 
     85     /* Current location in the buffer where we will read from next*/
     86     size_t bufoff;
     87 
     88     /* The mode we are using for processing commands */
     89     int mode;
     90 
     91     /* Whether FIN has ben sent on the stream */
     92     int isfin;
     93 };
     94 
     95 static void user_data_init(struct user_data_st *user_data, SSL *con, char *buf,
     96     size_t bufmax, int mode);
     97 static int user_data_add(struct user_data_st *user_data, size_t i);
     98 static int user_data_process(struct user_data_st *user_data, size_t *len,
     99     size_t *off);
    100 static int user_data_has_data(struct user_data_st *user_data);
    101 
    102 static char *prog;
    103 static int c_debug = 0;
    104 static int c_showcerts = 0;
    105 static char *keymatexportlabel = NULL;
    106 static int keymatexportlen = 20;
    107 static BIO *bio_c_out = NULL;
    108 static int c_quiet = 0;
    109 static char *sess_out = NULL;
    110 static SSL_SESSION *psksess = NULL;
    111 
    112 static void print_stuff(BIO *berr, SSL *con, int full);
    113 #ifndef OPENSSL_NO_OCSP
    114 static int ocsp_resp_cb(SSL *s, void *arg);
    115 #endif
    116 static int ldap_ExtendedResponse_parse(const char *buf, long rem);
    117 static int is_dNS_name(const char *host);
    118 
    119 static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 };
    120 static int enable_server_rpk = 0;
    121 
    122 static int saved_errno;
    123 
    124 static void save_errno(void)
    125 {
    126     saved_errno = errno;
    127     errno = 0;
    128 }
    129 
    130 static int restore_errno(void)
    131 {
    132     int ret = errno;
    133     errno = saved_errno;
    134     return ret;
    135 }
    136 
    137 /* Default PSK identity and key */
    138 static char *psk_identity = "Client_identity";
    139 
    140 #ifndef OPENSSL_NO_PSK
    141 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity,
    142     unsigned int max_identity_len,
    143     unsigned char *psk,
    144     unsigned int max_psk_len)
    145 {
    146     int ret;
    147     long key_len;
    148     unsigned char *key;
    149 
    150     if (c_debug)
    151         BIO_printf(bio_c_out, "psk_client_cb\n");
    152     if (!hint) {
    153         /* no ServerKeyExchange message */
    154         if (c_debug)
    155             BIO_printf(bio_c_out,
    156                 "NULL received PSK identity hint, continuing anyway\n");
    157     } else if (c_debug) {
    158         BIO_printf(bio_c_out, "Received PSK identity hint '%s'\n", hint);
    159     }
    160 
    161     /*
    162      * lookup PSK identity and PSK key based on the given identity hint here
    163      */
    164     ret = BIO_snprintf(identity, max_identity_len, "%s", psk_identity);
    165     if (ret < 0 || (unsigned int)ret > max_identity_len)
    166         goto out_err;
    167     if (c_debug)
    168         BIO_printf(bio_c_out, "created identity '%s' len=%d\n", identity,
    169             ret);
    170 
    171     /* convert the PSK key to binary */
    172     key = OPENSSL_hexstr2buf(psk_key, &key_len);
    173     if (key == NULL) {
    174         BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
    175             psk_key);
    176         return 0;
    177     }
    178     if (max_psk_len > INT_MAX || key_len > (long)max_psk_len) {
    179         BIO_printf(bio_err,
    180             "psk buffer of callback is too small (%d) for key (%ld)\n",
    181             max_psk_len, key_len);
    182         OPENSSL_free(key);
    183         return 0;
    184     }
    185 
    186     memcpy(psk, key, key_len);
    187     OPENSSL_free(key);
    188 
    189     if (c_debug)
    190         BIO_printf(bio_c_out, "created PSK len=%ld\n", key_len);
    191 
    192     return key_len;
    193 out_err:
    194     if (c_debug)
    195         BIO_printf(bio_err, "Error in PSK client callback\n");
    196     return 0;
    197 }
    198 #endif
    199 
    200 const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 };
    201 const unsigned char tls13_aes256gcmsha384_id[] = { 0x13, 0x02 };
    202 
    203 static int psk_use_session_cb(SSL *s, const EVP_MD *md,
    204     const unsigned char **id, size_t *idlen,
    205     SSL_SESSION **sess)
    206 {
    207     SSL_SESSION *usesess = NULL;
    208     const SSL_CIPHER *cipher = NULL;
    209 
    210     if (psksess != NULL) {
    211         if (!SSL_SESSION_up_ref(psksess))
    212             goto err;
    213         usesess = psksess;
    214     } else {
    215         long key_len;
    216         unsigned char *key = OPENSSL_hexstr2buf(psk_key, &key_len);
    217 
    218         if (key == NULL) {
    219             BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n",
    220                 psk_key);
    221             return 0;
    222         }
    223 
    224         /* We default to SHA-256 */
    225         cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id);
    226         if (cipher == NULL) {
    227             BIO_printf(bio_err, "Error finding suitable ciphersuite\n");
    228             OPENSSL_free(key);
    229             return 0;
    230         }
    231 
    232         usesess = SSL_SESSION_new();
    233         if (usesess == NULL
    234             || !SSL_SESSION_set1_master_key(usesess, key, key_len)
    235             || !SSL_SESSION_set_cipher(usesess, cipher)
    236             || !SSL_SESSION_set_protocol_version(usesess, TLS1_3_VERSION)) {
    237             OPENSSL_free(key);
    238             goto err;
    239         }
    240         OPENSSL_free(key);
    241     }
    242 
    243     cipher = SSL_SESSION_get0_cipher(usesess);
    244     if (cipher == NULL)
    245         goto err;
    246 
    247     if (md != NULL && SSL_CIPHER_get_handshake_digest(cipher) != md) {
    248         /* PSK not usable, ignore it */
    249         *id = NULL;
    250         *idlen = 0;
    251         *sess = NULL;
    252         SSL_SESSION_free(usesess);
    253     } else {
    254         *sess = usesess;
    255         *id = (unsigned char *)psk_identity;
    256         *idlen = strlen(psk_identity);
    257     }
    258 
    259     return 1;
    260 
    261 err:
    262     SSL_SESSION_free(usesess);
    263     return 0;
    264 }
    265 
    266 /* This is a context that we pass to callbacks */
    267 typedef struct tlsextctx_st {
    268     BIO *biodebug;
    269     int ack;
    270 } tlsextctx;
    271 
    272 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
    273 {
    274     tlsextctx *p = (tlsextctx *)arg;
    275     const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
    276     if (SSL_get_servername_type(s) != -1)
    277         p->ack = !SSL_session_reused(s) && hn != NULL;
    278     else
    279         BIO_printf(bio_err, "Can't use SSL_get_servername\n");
    280 
    281     return SSL_TLSEXT_ERR_OK;
    282 }
    283 
    284 #ifndef OPENSSL_NO_NEXTPROTONEG
    285 /* This the context that we pass to next_proto_cb */
    286 typedef struct tlsextnextprotoctx_st {
    287     unsigned char *data;
    288     size_t len;
    289     int status;
    290 } tlsextnextprotoctx;
    291 
    292 static tlsextnextprotoctx next_proto;
    293 
    294 static int next_proto_cb(SSL *s, unsigned char **out, unsigned char *outlen,
    295     const unsigned char *in, unsigned int inlen,
    296     void *arg)
    297 {
    298     tlsextnextprotoctx *ctx = arg;
    299 
    300     if (!c_quiet) {
    301         /* We can assume that |in| is syntactically valid. */
    302         unsigned i;
    303         BIO_printf(bio_c_out, "Protocols advertised by server: ");
    304         for (i = 0; i < inlen;) {
    305             if (i)
    306                 BIO_write(bio_c_out, ", ", 2);
    307             BIO_write(bio_c_out, &in[i + 1], in[i]);
    308             i += in[i] + 1;
    309         }
    310         BIO_write(bio_c_out, "\n", 1);
    311     }
    312 
    313     ctx->status = SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len);
    314     return SSL_TLSEXT_ERR_OK;
    315 }
    316 #endif /* ndef OPENSSL_NO_NEXTPROTONEG */
    317 
    318 static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type,
    319     const unsigned char *in, size_t inlen,
    320     int *al, void *arg)
    321 {
    322     char pem_name[100];
    323     unsigned char ext_buf[4 + 65536];
    324 
    325     /* Reconstruct the type/len fields prior to extension data */
    326     inlen &= 0xffff; /* for formal memcmpy correctness */
    327     ext_buf[0] = (unsigned char)(ext_type >> 8);
    328     ext_buf[1] = (unsigned char)(ext_type);
    329     ext_buf[2] = (unsigned char)(inlen >> 8);
    330     ext_buf[3] = (unsigned char)(inlen);
    331     memcpy(ext_buf + 4, in, inlen);
    332 
    333     BIO_snprintf(pem_name, sizeof(pem_name), "SERVERINFO FOR EXTENSION %d",
    334         ext_type);
    335     PEM_write_bio(bio_c_out, pem_name, "", ext_buf, 4 + inlen);
    336     return 1;
    337 }
    338 
    339 /*
    340  * Hex decoder that tolerates optional whitespace.  Returns number of bytes
    341  * produced, advances inptr to end of input string.
    342  */
    343 static ossl_ssize_t hexdecode(const char **inptr, void *result)
    344 {
    345     unsigned char **out = (unsigned char **)result;
    346     const char *in = *inptr;
    347     unsigned char *ret = app_malloc(strlen(in) / 2, "hexdecode");
    348     unsigned char *cp = ret;
    349     uint8_t byte;
    350     int nibble = 0;
    351 
    352     if (ret == NULL)
    353         return -1;
    354 
    355     for (byte = 0; *in; ++in) {
    356         int x;
    357 
    358         if (isspace(_UC(*in)))
    359             continue;
    360         x = OPENSSL_hexchar2int(*in);
    361         if (x < 0) {
    362             OPENSSL_free(ret);
    363             return 0;
    364         }
    365         byte |= (char)x;
    366         if ((nibble ^= 1) == 0) {
    367             *cp++ = byte;
    368             byte = 0;
    369         } else {
    370             byte <<= 4;
    371         }
    372     }
    373     if (nibble != 0) {
    374         OPENSSL_free(ret);
    375         return 0;
    376     }
    377     *inptr = in;
    378 
    379     return cp - (*out = ret);
    380 }
    381 
    382 /*
    383  * Decode unsigned 0..255, returns 1 on success, <= 0 on failure. Advances
    384  * inptr to next field skipping leading whitespace.
    385  */
    386 static ossl_ssize_t checked_uint8(const char **inptr, void *out)
    387 {
    388     uint8_t *result = (uint8_t *)out;
    389     const char *in = *inptr;
    390     char *endp;
    391     long v;
    392     int e;
    393 
    394     save_errno();
    395     v = strtol(in, &endp, 10);
    396     e = restore_errno();
    397 
    398     if (((v == LONG_MIN || v == LONG_MAX) && e == ERANGE) || endp == in || !isspace(_UC(*endp)) || v != (*result = (uint8_t)v)) {
    399         return -1;
    400     }
    401     for (in = endp; isspace(_UC(*in)); ++in)
    402         continue;
    403 
    404     *inptr = in;
    405     return 1;
    406 }
    407 
    408 struct tlsa_field {
    409     void *var;
    410     const char *name;
    411     ossl_ssize_t (*parser)(const char **, void *);
    412 };
    413 
    414 static int tlsa_import_rr(SSL *con, const char *rrdata)
    415 {
    416     /* Not necessary to re-init these values; the "parsers" do that. */
    417     static uint8_t usage;
    418     static uint8_t selector;
    419     static uint8_t mtype;
    420     static unsigned char *data;
    421     static struct tlsa_field tlsa_fields[] = {
    422         { &usage, "usage", checked_uint8 },
    423         { &selector, "selector", checked_uint8 },
    424         { &mtype, "mtype", checked_uint8 },
    425         { &data, "data", hexdecode },
    426         {
    427             NULL,
    428         }
    429     };
    430     struct tlsa_field *f;
    431     int ret;
    432     const char *cp = rrdata;
    433     ossl_ssize_t len = 0;
    434 
    435     for (f = tlsa_fields; f->var; ++f) {
    436         /* Returns number of bytes produced, advances cp to next field */
    437         if ((len = f->parser(&cp, f->var)) <= 0) {
    438             BIO_printf(bio_err, "%s: warning: bad TLSA %s field in: %s\n",
    439                 prog, f->name, rrdata);
    440             return 0;
    441         }
    442     }
    443     /* The data field is last, so len is its length */
    444     ret = SSL_dane_tlsa_add(con, usage, selector, mtype, data, len);
    445     OPENSSL_free(data);
    446 
    447     if (ret == 0) {
    448         ERR_print_errors(bio_err);
    449         BIO_printf(bio_err, "%s: warning: unusable TLSA rrdata: %s\n",
    450             prog, rrdata);
    451         return 0;
    452     }
    453     if (ret < 0) {
    454         ERR_print_errors(bio_err);
    455         BIO_printf(bio_err, "%s: warning: error loading TLSA rrdata: %s\n",
    456             prog, rrdata);
    457         return 0;
    458     }
    459     return ret;
    460 }
    461 
    462 static int tlsa_import_rrset(SSL *con, STACK_OF(OPENSSL_STRING) *rrset)
    463 {
    464     int num = sk_OPENSSL_STRING_num(rrset);
    465     int count = 0;
    466     int i;
    467 
    468     for (i = 0; i < num; ++i) {
    469         char *rrdata = sk_OPENSSL_STRING_value(rrset, i);
    470         if (tlsa_import_rr(con, rrdata) > 0)
    471             ++count;
    472     }
    473     return count > 0;
    474 }
    475 
    476 typedef enum OPTION_choice {
    477     OPT_COMMON,
    478     OPT_4,
    479     OPT_6,
    480     OPT_HOST,
    481     OPT_PORT,
    482     OPT_CONNECT,
    483     OPT_BIND,
    484     OPT_UNIX,
    485     OPT_XMPPHOST,
    486     OPT_VERIFY,
    487     OPT_NAMEOPT,
    488     OPT_CERT,
    489     OPT_CRL,
    490     OPT_CRL_DOWNLOAD,
    491     OPT_SESS_OUT,
    492     OPT_SESS_IN,
    493     OPT_CERTFORM,
    494     OPT_CRLFORM,
    495     OPT_VERIFY_RET_ERROR,
    496     OPT_VERIFY_QUIET,
    497     OPT_BRIEF,
    498     OPT_PREXIT,
    499     OPT_NO_INTERACTIVE,
    500     OPT_CRLF,
    501     OPT_QUIET,
    502     OPT_NBIO,
    503     OPT_SSL_CLIENT_ENGINE,
    504     OPT_IGN_EOF,
    505     OPT_NO_IGN_EOF,
    506     OPT_DEBUG,
    507     OPT_TLSEXTDEBUG,
    508     OPT_STATUS,
    509     OPT_WDEBUG,
    510     OPT_MSG,
    511     OPT_MSGFILE,
    512     OPT_ENGINE,
    513     OPT_TRACE,
    514     OPT_SECURITY_DEBUG,
    515     OPT_SECURITY_DEBUG_VERBOSE,
    516     OPT_SHOWCERTS,
    517     OPT_NBIO_TEST,
    518     OPT_STATE,
    519     OPT_PSK_IDENTITY,
    520     OPT_PSK,
    521     OPT_PSK_SESS,
    522 #ifndef OPENSSL_NO_SRP
    523     OPT_SRPUSER,
    524     OPT_SRPPASS,
    525     OPT_SRP_STRENGTH,
    526     OPT_SRP_LATEUSER,
    527     OPT_SRP_MOREGROUPS,
    528 #endif
    529     OPT_SSL3,
    530     OPT_SSL_CONFIG,
    531     OPT_TLS1_3,
    532     OPT_TLS1_2,
    533     OPT_TLS1_1,
    534     OPT_TLS1,
    535     OPT_DTLS,
    536     OPT_DTLS1,
    537     OPT_DTLS1_2,
    538     OPT_QUIC,
    539     OPT_SCTP,
    540     OPT_TIMEOUT,
    541     OPT_MTU,
    542     OPT_KEYFORM,
    543     OPT_PASS,
    544     OPT_CERT_CHAIN,
    545     OPT_KEY,
    546     OPT_RECONNECT,
    547     OPT_BUILD_CHAIN,
    548     OPT_NEXTPROTONEG,
    549     OPT_ALPN,
    550     OPT_CAPATH,
    551     OPT_NOCAPATH,
    552     OPT_CHAINCAPATH,
    553     OPT_VERIFYCAPATH,
    554     OPT_CAFILE,
    555     OPT_NOCAFILE,
    556     OPT_CHAINCAFILE,
    557     OPT_VERIFYCAFILE,
    558     OPT_CASTORE,
    559     OPT_NOCASTORE,
    560     OPT_CHAINCASTORE,
    561     OPT_VERIFYCASTORE,
    562     OPT_SERVERINFO,
    563     OPT_STARTTLS,
    564     OPT_SERVERNAME,
    565     OPT_NOSERVERNAME,
    566     OPT_ASYNC,
    567     OPT_USE_SRTP,
    568     OPT_KEYMATEXPORT,
    569     OPT_KEYMATEXPORTLEN,
    570     OPT_PROTOHOST,
    571     OPT_MAXFRAGLEN,
    572     OPT_MAX_SEND_FRAG,
    573     OPT_SPLIT_SEND_FRAG,
    574     OPT_MAX_PIPELINES,
    575     OPT_READ_BUF,
    576     OPT_KEYLOG_FILE,
    577     OPT_EARLY_DATA,
    578     OPT_REQCAFILE,
    579     OPT_TFO,
    580     OPT_V_ENUM,
    581     OPT_X_ENUM,
    582     OPT_S_ENUM,
    583     OPT_IGNORE_UNEXPECTED_EOF,
    584     OPT_FALLBACKSCSV,
    585     OPT_NOCMDS,
    586     OPT_ADV,
    587     OPT_PROXY,
    588     OPT_PROXY_USER,
    589     OPT_PROXY_PASS,
    590     OPT_DANE_TLSA_DOMAIN,
    591 #ifndef OPENSSL_NO_CT
    592     OPT_CT,
    593     OPT_NOCT,
    594     OPT_CTLOG_FILE,
    595 #endif
    596     OPT_DANE_TLSA_RRDATA,
    597     OPT_DANE_EE_NO_NAME,
    598     OPT_ENABLE_PHA,
    599     OPT_ENABLE_SERVER_RPK,
    600     OPT_ENABLE_CLIENT_RPK,
    601     OPT_SCTP_LABEL_BUG,
    602     OPT_KTLS,
    603     OPT_R_ENUM,
    604     OPT_PROV_ENUM
    605 } OPTION_CHOICE;
    606 
    607 const OPTIONS s_client_options[] = {
    608     { OPT_HELP_STR, 1, '-', "Usage: %s [options] [host:port]\n" },
    609 
    610     OPT_SECTION("General"),
    611     { "help", OPT_HELP, '-', "Display this summary" },
    612 #ifndef OPENSSL_NO_ENGINE
    613     { "engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device" },
    614     { "ssl_client_engine", OPT_SSL_CLIENT_ENGINE, 's',
    615         "Specify engine to be used for client certificate operations" },
    616 #endif
    617     { "ssl_config", OPT_SSL_CONFIG, 's', "Use specified section for SSL_CTX configuration" },
    618 #ifndef OPENSSL_NO_CT
    619     { "ct", OPT_CT, '-', "Request and parse SCTs (also enables OCSP stapling)" },
    620     { "noct", OPT_NOCT, '-', "Do not request or parse SCTs (default)" },
    621     { "ctlogfile", OPT_CTLOG_FILE, '<', "CT log list CONF file" },
    622 #endif
    623 
    624     OPT_SECTION("Network"),
    625     { "host", OPT_HOST, 's', "Use -connect instead" },
    626     { "port", OPT_PORT, 'p', "Use -connect instead" },
    627     { "connect", OPT_CONNECT, 's',
    628         "TCP/IP where to connect; default: " PORT ")" },
    629     { "bind", OPT_BIND, 's', "bind local address for connection" },
    630     { "proxy", OPT_PROXY, 's',
    631         "Connect to via specified proxy to the real server" },
    632     { "proxy_user", OPT_PROXY_USER, 's', "UserID for proxy authentication" },
    633     { "proxy_pass", OPT_PROXY_PASS, 's', "Proxy authentication password source" },
    634 #ifdef AF_UNIX
    635     { "unix", OPT_UNIX, 's', "Connect over the specified Unix-domain socket" },
    636 #endif
    637     { "4", OPT_4, '-', "Use IPv4 only" },
    638 #ifdef AF_INET6
    639     { "6", OPT_6, '-', "Use IPv6 only" },
    640 #endif
    641     { "maxfraglen", OPT_MAXFRAGLEN, 'p',
    642         "Enable Maximum Fragment Length Negotiation (len values: 512, 1024, 2048 and 4096)" },
    643     { "max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames " },
    644     { "split_send_frag", OPT_SPLIT_SEND_FRAG, 'p',
    645         "Size used to split data for encrypt pipelines" },
    646     { "max_pipelines", OPT_MAX_PIPELINES, 'p',
    647         "Maximum number of encrypt/decrypt pipelines to be used" },
    648     { "read_buf", OPT_READ_BUF, 'p',
    649         "Default read buffer size to be used for connections" },
    650     { "fallback_scsv", OPT_FALLBACKSCSV, '-', "Send the fallback SCSV" },
    651 
    652     OPT_SECTION("Identity"),
    653     { "cert", OPT_CERT, '<', "Client certificate file to use" },
    654     { "certform", OPT_CERTFORM, 'F',
    655         "Client certificate file format (PEM/DER/P12); has no effect" },
    656     { "cert_chain", OPT_CERT_CHAIN, '<',
    657         "Client certificate chain file (in PEM format)" },
    658     { "build_chain", OPT_BUILD_CHAIN, '-', "Build client certificate chain" },
    659     { "key", OPT_KEY, 's', "Private key file to use; default: -cert file" },
    660     { "keyform", OPT_KEYFORM, 'E', "Key format (ENGINE, other values ignored)" },
    661     { "pass", OPT_PASS, 's', "Private key and cert file pass phrase source" },
    662     { "verify", OPT_VERIFY, 'p', "Turn on peer certificate verification" },
    663     { "nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options" },
    664     { "CApath", OPT_CAPATH, '/', "PEM format directory of CA's" },
    665     { "CAfile", OPT_CAFILE, '<', "PEM format file of CA's" },
    666     { "CAstore", OPT_CASTORE, ':', "URI to store of CA's" },
    667     { "no-CAfile", OPT_NOCAFILE, '-',
    668         "Do not load the default certificates file" },
    669     { "no-CApath", OPT_NOCAPATH, '-',
    670         "Do not load certificates from the default certificates directory" },
    671     { "no-CAstore", OPT_NOCASTORE, '-',
    672         "Do not load certificates from the default certificates store" },
    673     { "requestCAfile", OPT_REQCAFILE, '<',
    674         "PEM format file of CA names to send to the server" },
    675 #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO)
    676     { "tfo", OPT_TFO, '-', "Connect using TCP Fast Open" },
    677 #endif
    678     { "dane_tlsa_domain", OPT_DANE_TLSA_DOMAIN, 's', "DANE TLSA base domain" },
    679     { "dane_tlsa_rrdata", OPT_DANE_TLSA_RRDATA, 's',
    680         "DANE TLSA rrdata presentation form" },
    681     { "dane_ee_no_namechecks", OPT_DANE_EE_NO_NAME, '-',
    682         "Disable name checks when matching DANE-EE(3) TLSA records" },
    683     { "psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity" },
    684     { "psk", OPT_PSK, 's', "PSK in hex (without 0x)" },
    685     { "psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from" },
    686     { "name", OPT_PROTOHOST, 's',
    687         "Hostname to use for \"-starttls lmtp\", \"-starttls smtp\" or \"-starttls xmpp[-server]\"" },
    688 
    689     OPT_SECTION("Session"),
    690     { "reconnect", OPT_RECONNECT, '-',
    691         "Drop and re-make the connection with the same Session-ID" },
    692     { "sess_out", OPT_SESS_OUT, '>', "File to write SSL session to" },
    693     { "sess_in", OPT_SESS_IN, '<', "File to read SSL session from" },
    694 
    695     OPT_SECTION("Input/Output"),
    696     { "crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF" },
    697     { "quiet", OPT_QUIET, '-', "No s_client output" },
    698     { "ign_eof", OPT_IGN_EOF, '-', "Ignore input eof (default when -quiet)" },
    699     { "no_ign_eof", OPT_NO_IGN_EOF, '-', "Don't ignore input eof" },
    700     { "starttls", OPT_STARTTLS, 's',
    701         "Use the appropriate STARTTLS command before starting TLS" },
    702     { "xmpphost", OPT_XMPPHOST, 's',
    703         "Alias of -name option for \"-starttls xmpp[-server]\"" },
    704     { "brief", OPT_BRIEF, '-',
    705         "Restrict output to brief summary of connection parameters" },
    706     { "prexit", OPT_PREXIT, '-',
    707         "Print session information when the program exits" },
    708     { "no-interactive", OPT_NO_INTERACTIVE, '-',
    709         "Don't run the client in the interactive mode" },
    710 
    711     OPT_SECTION("Debug"),
    712     { "showcerts", OPT_SHOWCERTS, '-',
    713         "Show all certificates sent by the server" },
    714     { "debug", OPT_DEBUG, '-', "Extra output" },
    715     { "msg", OPT_MSG, '-', "Show protocol messages" },
    716     { "msgfile", OPT_MSGFILE, '>',
    717         "File to send output of -msg or -trace, instead of stdout" },
    718     { "nbio_test", OPT_NBIO_TEST, '-', "More ssl protocol testing" },
    719     { "state", OPT_STATE, '-', "Print the ssl states" },
    720     { "keymatexport", OPT_KEYMATEXPORT, 's',
    721         "Export keying material using label" },
    722     { "keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
    723         "Export len bytes of keying material; default 20" },
    724     { "security_debug", OPT_SECURITY_DEBUG, '-',
    725         "Enable security debug messages" },
    726     { "security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
    727         "Output more security debug output" },
    728 #ifndef OPENSSL_NO_SSL_TRACE
    729     { "trace", OPT_TRACE, '-', "Show trace output of protocol messages" },
    730 #endif
    731 #ifdef WATT32
    732     { "wdebug", OPT_WDEBUG, '-', "WATT-32 tcp debugging" },
    733 #endif
    734     { "keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file" },
    735     { "nocommands", OPT_NOCMDS, '-', "Do not use interactive command letters" },
    736     { "adv", OPT_ADV, '-', "Advanced command mode" },
    737     { "servername", OPT_SERVERNAME, 's',
    738         "Set TLS extension servername (SNI) in ClientHello (default)" },
    739     { "noservername", OPT_NOSERVERNAME, '-',
    740         "Do not send the server name (SNI) extension in the ClientHello" },
    741     { "tlsextdebug", OPT_TLSEXTDEBUG, '-',
    742         "Hex dump of all TLS extensions received" },
    743     { "ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF, '-',
    744         "Do not treat lack of close_notify from a peer as an error" },
    745 #ifndef OPENSSL_NO_OCSP
    746     { "status", OPT_STATUS, '-', "Request certificate status from server" },
    747 #endif
    748     { "serverinfo", OPT_SERVERINFO, 's',
    749         "types  Send empty ClientHello extensions (comma-separated numbers)" },
    750     { "alpn", OPT_ALPN, 's',
    751         "Enable ALPN extension, considering named protocols supported (comma-separated list)" },
    752     { "async", OPT_ASYNC, '-', "Support asynchronous operation" },
    753     { "nbio", OPT_NBIO, '-', "Use non-blocking IO" },
    754 
    755     OPT_SECTION("Protocol and version"),
    756 #ifndef OPENSSL_NO_SSL3
    757     { "ssl3", OPT_SSL3, '-', "Just use SSLv3" },
    758 #endif
    759 #ifndef OPENSSL_NO_TLS1
    760     { "tls1", OPT_TLS1, '-', "Just use TLSv1" },
    761 #endif
    762 #ifndef OPENSSL_NO_TLS1_1
    763     { "tls1_1", OPT_TLS1_1, '-', "Just use TLSv1.1" },
    764 #endif
    765 #ifndef OPENSSL_NO_TLS1_2
    766     { "tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2" },
    767 #endif
    768 #ifndef OPENSSL_NO_TLS1_3
    769     { "tls1_3", OPT_TLS1_3, '-', "Just use TLSv1.3" },
    770 #endif
    771 #ifndef OPENSSL_NO_DTLS
    772     { "dtls", OPT_DTLS, '-', "Use any version of DTLS" },
    773     { "quic", OPT_QUIC, '-', "Use QUIC" },
    774     { "timeout", OPT_TIMEOUT, '-',
    775         "Enable send/receive timeout on DTLS connections" },
    776     { "mtu", OPT_MTU, 'p', "Set the link layer MTU" },
    777 #endif
    778 #ifndef OPENSSL_NO_DTLS1
    779     { "dtls1", OPT_DTLS1, '-', "Just use DTLSv1" },
    780 #endif
    781 #ifndef OPENSSL_NO_DTLS1_2
    782     { "dtls1_2", OPT_DTLS1_2, '-', "Just use DTLSv1.2" },
    783 #endif
    784 #ifndef OPENSSL_NO_SCTP
    785     { "sctp", OPT_SCTP, '-', "Use SCTP" },
    786     { "sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug" },
    787 #endif
    788 #ifndef OPENSSL_NO_NEXTPROTONEG
    789     { "nextprotoneg", OPT_NEXTPROTONEG, 's',
    790         "Enable NPN extension, considering named protocols supported (comma-separated list)" },
    791 #endif
    792     { "early_data", OPT_EARLY_DATA, '<', "File to send as early data" },
    793     { "enable_pha", OPT_ENABLE_PHA, '-', "Enable post-handshake-authentication" },
    794     { "enable_server_rpk", OPT_ENABLE_SERVER_RPK, '-', "Enable raw public keys (RFC7250) from the server" },
    795     { "enable_client_rpk", OPT_ENABLE_CLIENT_RPK, '-', "Enable raw public keys (RFC7250) from the client" },
    796 #ifndef OPENSSL_NO_SRTP
    797     { "use_srtp", OPT_USE_SRTP, 's',
    798         "Offer SRTP key management with a colon-separated profile list" },
    799 #endif
    800 #ifndef OPENSSL_NO_SRP
    801     { "srpuser", OPT_SRPUSER, 's', "(deprecated) SRP authentication for 'user'" },
    802     { "srppass", OPT_SRPPASS, 's', "(deprecated) Password for 'user'" },
    803     { "srp_lateuser", OPT_SRP_LATEUSER, '-',
    804         "(deprecated) SRP username into second ClientHello message" },
    805     { "srp_moregroups", OPT_SRP_MOREGROUPS, '-',
    806         "(deprecated) Tolerate other than the known g N values." },
    807     { "srp_strength", OPT_SRP_STRENGTH, 'p',
    808         "(deprecated) Minimal length in bits for N" },
    809 #endif
    810 #ifndef OPENSSL_NO_KTLS
    811     { "ktls", OPT_KTLS, '-', "Enable Kernel TLS for sending and receiving" },
    812 #endif
    813 
    814     OPT_R_OPTIONS,
    815     OPT_S_OPTIONS,
    816     OPT_V_OPTIONS,
    817     { "CRL", OPT_CRL, '<', "CRL file to use" },
    818     { "crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRL from distribution points" },
    819     { "CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER); default PEM" },
    820     { "verify_return_error", OPT_VERIFY_RET_ERROR, '-',
    821         "Close connection on verification error" },
    822     { "verify_quiet", OPT_VERIFY_QUIET, '-', "Restrict verify output to errors" },
    823     { "chainCAfile", OPT_CHAINCAFILE, '<',
    824         "CA file for certificate chain (PEM format)" },
    825     { "chainCApath", OPT_CHAINCAPATH, '/',
    826         "Use dir as certificate store path to build CA certificate chain" },
    827     { "chainCAstore", OPT_CHAINCASTORE, ':',
    828         "CA store URI for certificate chain" },
    829     { "verifyCAfile", OPT_VERIFYCAFILE, '<',
    830         "CA file for certificate verification (PEM format)" },
    831     { "verifyCApath", OPT_VERIFYCAPATH, '/',
    832         "Use dir as certificate store path to verify CA certificate" },
    833     { "verifyCAstore", OPT_VERIFYCASTORE, ':',
    834         "CA store URI for certificate verification" },
    835     OPT_X_OPTIONS,
    836     OPT_PROV_OPTIONS,
    837 
    838     OPT_PARAMETERS(),
    839     { "host:port", 0, 0, "Where to connect; same as -connect option" },
    840     { NULL }
    841 };
    842 
    843 typedef enum PROTOCOL_choice {
    844     PROTO_OFF,
    845     PROTO_SMTP,
    846     PROTO_POP3,
    847     PROTO_IMAP,
    848     PROTO_FTP,
    849     PROTO_TELNET,
    850     PROTO_XMPP,
    851     PROTO_XMPP_SERVER,
    852     PROTO_IRC,
    853     PROTO_MYSQL,
    854     PROTO_POSTGRES,
    855     PROTO_LMTP,
    856     PROTO_NNTP,
    857     PROTO_SIEVE,
    858     PROTO_LDAP
    859 } PROTOCOL_CHOICE;
    860 
    861 static const OPT_PAIR services[] = {
    862     { "smtp", PROTO_SMTP },
    863     { "pop3", PROTO_POP3 },
    864     { "imap", PROTO_IMAP },
    865     { "ftp", PROTO_FTP },
    866     { "xmpp", PROTO_XMPP },
    867     { "xmpp-server", PROTO_XMPP_SERVER },
    868     { "telnet", PROTO_TELNET },
    869     { "irc", PROTO_IRC },
    870     { "mysql", PROTO_MYSQL },
    871     { "postgres", PROTO_POSTGRES },
    872     { "lmtp", PROTO_LMTP },
    873     { "nntp", PROTO_NNTP },
    874     { "sieve", PROTO_SIEVE },
    875     { "ldap", PROTO_LDAP },
    876     { NULL, 0 }
    877 };
    878 
    879 #define IS_INET_FLAG(o) \
    880     (o == OPT_4 || o == OPT_6 || o == OPT_HOST || o == OPT_PORT || o == OPT_CONNECT)
    881 #define IS_UNIX_FLAG(o) (o == OPT_UNIX)
    882 
    883 #define IS_PROT_FLAG(o)                                                           \
    884     (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2         \
    885         || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2 \
    886         || o == OPT_QUIC)
    887 
    888 /* Free |*dest| and optionally set it to a copy of |source|. */
    889 static void freeandcopy(char **dest, const char *source)
    890 {
    891     OPENSSL_free(*dest);
    892     *dest = NULL;
    893     if (source != NULL)
    894         *dest = OPENSSL_strdup(source);
    895 }
    896 
    897 static int new_session_cb(SSL *s, SSL_SESSION *sess)
    898 {
    899 
    900     if (sess_out != NULL) {
    901         BIO *stmp = BIO_new_file(sess_out, "w");
    902 
    903         if (stmp == NULL) {
    904             BIO_printf(bio_err, "Error writing session file %s\n", sess_out);
    905         } else {
    906             PEM_write_bio_SSL_SESSION(stmp, sess);
    907             BIO_free(stmp);
    908         }
    909     }
    910 
    911     /*
    912      * Session data gets dumped on connection for TLSv1.2 and below, and on
    913      * arrival of the NewSessionTicket for TLSv1.3.
    914      */
    915     if (SSL_version(s) == TLS1_3_VERSION) {
    916         BIO_printf(bio_c_out,
    917             "---\nPost-Handshake New Session Ticket arrived:\n");
    918         SSL_SESSION_print(bio_c_out, sess);
    919         BIO_printf(bio_c_out, "---\n");
    920     }
    921 
    922     /*
    923      * We always return a "fail" response so that the session gets freed again
    924      * because we haven't used the reference.
    925      */
    926     return 0;
    927 }
    928 
    929 int s_client_main(int argc, char **argv)
    930 {
    931     BIO *sbio;
    932     EVP_PKEY *key = NULL;
    933     SSL *con = NULL;
    934     SSL_CTX *ctx = NULL;
    935     STACK_OF(X509) *chain = NULL;
    936     X509 *cert = NULL;
    937     X509_VERIFY_PARAM *vpm = NULL;
    938     SSL_EXCERT *exc = NULL;
    939     SSL_CONF_CTX *cctx = NULL;
    940     STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
    941     char *dane_tlsa_domain = NULL;
    942     STACK_OF(OPENSSL_STRING) *dane_tlsa_rrset = NULL;
    943     int dane_ee_no_name = 0;
    944     STACK_OF(X509_CRL) *crls = NULL;
    945     const SSL_METHOD *meth = TLS_client_method();
    946     const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL;
    947     char *cbuf = NULL, *sbuf = NULL, *mbuf = NULL;
    948     char *proxystr = NULL, *proxyuser = NULL;
    949     char *proxypassarg = NULL, *proxypass = NULL;
    950     char *connectstr = NULL, *bindstr = NULL;
    951     char *cert_file = NULL, *key_file = NULL, *chain_file = NULL;
    952     char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL, *host = NULL;
    953     char *thost = NULL, *tport = NULL;
    954     char *port = NULL;
    955     char *bindhost = NULL, *bindport = NULL;
    956     char *passarg = NULL, *pass = NULL;
    957     char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL;
    958     char *ReqCAfile = NULL;
    959     char *sess_in = NULL, *crl_file = NULL, *p;
    960     const char *protohost = NULL;
    961     struct timeval timeout, *timeoutp;
    962     fd_set readfds, writefds;
    963     int noCApath = 0, noCAfile = 0, noCAstore = 0;
    964     int build_chain = 0, cert_format = FORMAT_UNDEF;
    965     size_t cbuf_len, cbuf_off;
    966     int key_format = FORMAT_UNDEF, crlf = 0, full_log = 1, mbuf_len = 0;
    967     int prexit = 0;
    968     int nointeractive = 0;
    969     int sdebug = 0;
    970     int reconnect = 0, verify = SSL_VERIFY_NONE, vpmtouched = 0;
    971     int ret = 1, in_init = 1, i, nbio_test = 0, sock = -1, k, width, state = 0;
    972     int sbuf_len, sbuf_off, cmdmode = USER_DATA_MODE_BASIC;
    973     int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0;
    974     int starttls_proto = PROTO_OFF, crl_format = FORMAT_UNDEF, crl_download = 0;
    975     int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending;
    976     int first_loop;
    977 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
    978     int at_eof = 0;
    979 #endif
    980     int read_buf_len = 0;
    981     int fallback_scsv = 0;
    982     OPTION_CHOICE o;
    983 #ifndef OPENSSL_NO_DTLS
    984     int enable_timeouts = 0;
    985     long socket_mtu = 0;
    986 #endif
    987 #ifndef OPENSSL_NO_ENGINE
    988     ENGINE *ssl_client_engine = NULL;
    989 #endif
    990     ENGINE *e = NULL;
    991 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
    992     struct timeval tv;
    993 #endif
    994     const char *servername = NULL;
    995     char *sname_alloc = NULL;
    996     int noservername = 0;
    997     const char *alpn_in = NULL;
    998     tlsextctx tlsextcbp = { NULL, 0 };
    999     const char *ssl_config = NULL;
   1000 #define MAX_SI_TYPES 100
   1001     unsigned short serverinfo_types[MAX_SI_TYPES];
   1002     int serverinfo_count = 0, start = 0, len;
   1003 #ifndef OPENSSL_NO_NEXTPROTONEG
   1004     const char *next_proto_neg_in = NULL;
   1005 #endif
   1006 #ifndef OPENSSL_NO_SRP
   1007     char *srppass = NULL;
   1008     int srp_lateuser = 0;
   1009     SRP_ARG srp_arg = { NULL, NULL, 0, 0, 0, 1024 };
   1010 #endif
   1011 #ifndef OPENSSL_NO_SRTP
   1012     char *srtp_profiles = NULL;
   1013 #endif
   1014 #ifndef OPENSSL_NO_CT
   1015     char *ctlog_file = NULL;
   1016     int ct_validation = 0;
   1017 #endif
   1018     int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
   1019     int async = 0;
   1020     unsigned int max_send_fragment = 0;
   1021     unsigned int split_send_fragment = 0, max_pipelines = 0;
   1022     enum { use_inet,
   1023         use_unix,
   1024         use_unknown } connect_type
   1025         = use_unknown;
   1026     int count4or6 = 0;
   1027     uint8_t maxfraglen = 0;
   1028     int c_nbio = 0, c_msg = 0, c_ign_eof = 0, c_brief = 0;
   1029     int c_tlsextdebug = 0;
   1030 #ifndef OPENSSL_NO_OCSP
   1031     int c_status_req = 0;
   1032 #endif
   1033     BIO *bio_c_msg = NULL;
   1034     const char *keylog_file = NULL, *early_data_file = NULL;
   1035     int isdtls = 0, isquic = 0;
   1036     char *psksessf = NULL;
   1037     int enable_pha = 0;
   1038     int enable_client_rpk = 0;
   1039 #ifndef OPENSSL_NO_SCTP
   1040     int sctp_label_bug = 0;
   1041 #endif
   1042     int ignore_unexpected_eof = 0;
   1043 #ifndef OPENSSL_NO_KTLS
   1044     int enable_ktls = 0;
   1045 #endif
   1046     int tfo = 0;
   1047     int is_infinite;
   1048     BIO_ADDR *peer_addr = NULL;
   1049     struct user_data_st user_data;
   1050 
   1051     FD_ZERO(&readfds);
   1052     FD_ZERO(&writefds);
   1053 /* Known false-positive of MemorySanitizer. */
   1054 #if defined(__has_feature)
   1055 #if __has_feature(memory_sanitizer)
   1056     __msan_unpoison(&readfds, sizeof(readfds));
   1057     __msan_unpoison(&writefds, sizeof(writefds));
   1058 #endif
   1059 #endif
   1060 
   1061     c_quiet = 0;
   1062     c_debug = 0;
   1063     c_showcerts = 0;
   1064     c_nbio = 0;
   1065     port = OPENSSL_strdup(PORT);
   1066     vpm = X509_VERIFY_PARAM_new();
   1067     cctx = SSL_CONF_CTX_new();
   1068 
   1069     if (port == NULL || vpm == NULL || cctx == NULL) {
   1070         BIO_printf(bio_err, "%s: out of memory\n", opt_getprog());
   1071         goto end;
   1072     }
   1073 
   1074     cbuf = app_malloc(BUFSIZZ, "cbuf");
   1075     sbuf = app_malloc(BUFSIZZ, "sbuf");
   1076     mbuf = app_malloc(BUFSIZZ, "mbuf");
   1077 
   1078     SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT | SSL_CONF_FLAG_CMDLINE);
   1079 
   1080     prog = opt_init(argc, argv, s_client_options);
   1081     while ((o = opt_next()) != OPT_EOF) {
   1082         /* Check for intermixing flags. */
   1083         if (connect_type == use_unix && IS_INET_FLAG(o)) {
   1084             BIO_printf(bio_err,
   1085                 "%s: Intermixed protocol flags (unix and internet domains)\n",
   1086                 prog);
   1087             goto end;
   1088         }
   1089         if (connect_type == use_inet && IS_UNIX_FLAG(o)) {
   1090             BIO_printf(bio_err,
   1091                 "%s: Intermixed protocol flags (internet and unix domains)\n",
   1092                 prog);
   1093             goto end;
   1094         }
   1095 
   1096         if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
   1097             BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
   1098             goto end;
   1099         }
   1100         if (IS_NO_PROT_FLAG(o))
   1101             no_prot_opt++;
   1102         if (prot_opt == 1 && no_prot_opt) {
   1103             BIO_printf(bio_err,
   1104                 "Cannot supply both a protocol flag and '-no_<prot>'\n");
   1105             goto end;
   1106         }
   1107 
   1108         switch (o) {
   1109         case OPT_EOF:
   1110         case OPT_ERR:
   1111         opthelp:
   1112             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
   1113             goto end;
   1114         case OPT_HELP:
   1115             opt_help(s_client_options);
   1116             ret = 0;
   1117             goto end;
   1118         case OPT_4:
   1119             connect_type = use_inet;
   1120             socket_family = AF_INET;
   1121             count4or6++;
   1122             break;
   1123 #ifdef AF_INET6
   1124         case OPT_6:
   1125             connect_type = use_inet;
   1126             socket_family = AF_INET6;
   1127             count4or6++;
   1128             break;
   1129 #endif
   1130         case OPT_HOST:
   1131             connect_type = use_inet;
   1132             freeandcopy(&host, opt_arg());
   1133             break;
   1134         case OPT_PORT:
   1135             connect_type = use_inet;
   1136             freeandcopy(&port, opt_arg());
   1137             break;
   1138         case OPT_CONNECT:
   1139             connect_type = use_inet;
   1140             freeandcopy(&connectstr, opt_arg());
   1141             break;
   1142         case OPT_BIND:
   1143             freeandcopy(&bindstr, opt_arg());
   1144             break;
   1145         case OPT_PROXY:
   1146             proxystr = opt_arg();
   1147             break;
   1148         case OPT_PROXY_USER:
   1149             proxyuser = opt_arg();
   1150             break;
   1151         case OPT_PROXY_PASS:
   1152             proxypassarg = opt_arg();
   1153             break;
   1154 #ifdef AF_UNIX
   1155         case OPT_UNIX:
   1156             connect_type = use_unix;
   1157             socket_family = AF_UNIX;
   1158             freeandcopy(&host, opt_arg());
   1159             break;
   1160 #endif
   1161         case OPT_XMPPHOST:
   1162             /* fall through, since this is an alias */
   1163         case OPT_PROTOHOST:
   1164             protohost = opt_arg();
   1165             break;
   1166         case OPT_VERIFY:
   1167             verify = SSL_VERIFY_PEER;
   1168             verify_args.depth = atoi(opt_arg());
   1169             if (!c_quiet)
   1170                 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
   1171             break;
   1172         case OPT_CERT:
   1173             cert_file = opt_arg();
   1174             break;
   1175         case OPT_NAMEOPT:
   1176             if (!set_nameopt(opt_arg()))
   1177                 goto end;
   1178             break;
   1179         case OPT_CRL:
   1180             crl_file = opt_arg();
   1181             break;
   1182         case OPT_CRL_DOWNLOAD:
   1183             crl_download = 1;
   1184             break;
   1185         case OPT_SESS_OUT:
   1186             sess_out = opt_arg();
   1187             break;
   1188         case OPT_SESS_IN:
   1189             sess_in = opt_arg();
   1190             break;
   1191         case OPT_CERTFORM:
   1192             if (!opt_format(opt_arg(), OPT_FMT_ANY, &cert_format))
   1193                 goto opthelp;
   1194             break;
   1195         case OPT_CRLFORM:
   1196             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
   1197                 goto opthelp;
   1198             break;
   1199         case OPT_VERIFY_RET_ERROR:
   1200             verify = SSL_VERIFY_PEER;
   1201             verify_args.return_error = 1;
   1202             break;
   1203         case OPT_VERIFY_QUIET:
   1204             verify_args.quiet = 1;
   1205             break;
   1206         case OPT_BRIEF:
   1207             c_brief = verify_args.quiet = c_quiet = 1;
   1208             break;
   1209         case OPT_S_CASES:
   1210             if (ssl_args == NULL)
   1211                 ssl_args = sk_OPENSSL_STRING_new_null();
   1212             if (ssl_args == NULL
   1213                 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
   1214                 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
   1215                 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
   1216                 goto end;
   1217             }
   1218             break;
   1219         case OPT_V_CASES:
   1220             if (!opt_verify(o, vpm))
   1221                 goto end;
   1222             vpmtouched++;
   1223             break;
   1224         case OPT_X_CASES:
   1225             if (!args_excert(o, &exc))
   1226                 goto end;
   1227             break;
   1228         case OPT_IGNORE_UNEXPECTED_EOF:
   1229             ignore_unexpected_eof = 1;
   1230             break;
   1231         case OPT_PREXIT:
   1232             prexit = 1;
   1233             break;
   1234         case OPT_NO_INTERACTIVE:
   1235             nointeractive = 1;
   1236             break;
   1237         case OPT_CRLF:
   1238             crlf = 1;
   1239             break;
   1240         case OPT_QUIET:
   1241             c_quiet = c_ign_eof = 1;
   1242             break;
   1243         case OPT_NBIO:
   1244             c_nbio = 1;
   1245             break;
   1246         case OPT_NOCMDS:
   1247             cmdmode = USER_DATA_MODE_NONE;
   1248             break;
   1249         case OPT_ADV:
   1250             cmdmode = USER_DATA_MODE_ADVANCED;
   1251             break;
   1252         case OPT_ENGINE:
   1253             e = setup_engine(opt_arg(), 1);
   1254             break;
   1255         case OPT_SSL_CLIENT_ENGINE:
   1256 #ifndef OPENSSL_NO_ENGINE
   1257             ssl_client_engine = setup_engine(opt_arg(), 0);
   1258             if (ssl_client_engine == NULL) {
   1259                 BIO_printf(bio_err, "Error getting client auth engine\n");
   1260                 goto opthelp;
   1261             }
   1262 #endif
   1263             break;
   1264         case OPT_R_CASES:
   1265             if (!opt_rand(o))
   1266                 goto end;
   1267             break;
   1268         case OPT_PROV_CASES:
   1269             if (!opt_provider(o))
   1270                 goto end;
   1271             break;
   1272         case OPT_IGN_EOF:
   1273             c_ign_eof = 1;
   1274             break;
   1275         case OPT_NO_IGN_EOF:
   1276             c_ign_eof = 0;
   1277             break;
   1278         case OPT_DEBUG:
   1279             c_debug = 1;
   1280             break;
   1281         case OPT_TLSEXTDEBUG:
   1282             c_tlsextdebug = 1;
   1283             break;
   1284         case OPT_STATUS:
   1285 #ifndef OPENSSL_NO_OCSP
   1286             c_status_req = 1;
   1287 #endif
   1288             break;
   1289         case OPT_WDEBUG:
   1290 #ifdef WATT32
   1291             dbug_init();
   1292 #endif
   1293             break;
   1294         case OPT_MSG:
   1295             c_msg = 1;
   1296             break;
   1297         case OPT_MSGFILE:
   1298             bio_c_msg = BIO_new_file(opt_arg(), "w");
   1299             if (bio_c_msg == NULL) {
   1300                 BIO_printf(bio_err, "Error writing file %s\n", opt_arg());
   1301                 goto end;
   1302             }
   1303             break;
   1304         case OPT_TRACE:
   1305 #ifndef OPENSSL_NO_SSL_TRACE
   1306             c_msg = 2;
   1307 #endif
   1308             break;
   1309         case OPT_SECURITY_DEBUG:
   1310             sdebug = 1;
   1311             break;
   1312         case OPT_SECURITY_DEBUG_VERBOSE:
   1313             sdebug = 2;
   1314             break;
   1315         case OPT_SHOWCERTS:
   1316             c_showcerts = 1;
   1317             break;
   1318         case OPT_NBIO_TEST:
   1319             nbio_test = 1;
   1320             break;
   1321         case OPT_STATE:
   1322             state = 1;
   1323             break;
   1324         case OPT_PSK_IDENTITY:
   1325             psk_identity = opt_arg();
   1326             break;
   1327         case OPT_PSK:
   1328             for (p = psk_key = opt_arg(); *p; p++) {
   1329                 if (isxdigit(_UC(*p)))
   1330                     continue;
   1331                 BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
   1332                 goto end;
   1333             }
   1334             break;
   1335         case OPT_PSK_SESS:
   1336             psksessf = opt_arg();
   1337             break;
   1338 #ifndef OPENSSL_NO_SRP
   1339         case OPT_SRPUSER:
   1340             srp_arg.srplogin = opt_arg();
   1341             if (min_version < TLS1_VERSION)
   1342                 min_version = TLS1_VERSION;
   1343             break;
   1344         case OPT_SRPPASS:
   1345             srppass = opt_arg();
   1346             if (min_version < TLS1_VERSION)
   1347                 min_version = TLS1_VERSION;
   1348             break;
   1349         case OPT_SRP_STRENGTH:
   1350             srp_arg.strength = atoi(opt_arg());
   1351             BIO_printf(bio_err, "SRP minimal length for N is %d\n",
   1352                 srp_arg.strength);
   1353             if (min_version < TLS1_VERSION)
   1354                 min_version = TLS1_VERSION;
   1355             break;
   1356         case OPT_SRP_LATEUSER:
   1357             srp_lateuser = 1;
   1358             if (min_version < TLS1_VERSION)
   1359                 min_version = TLS1_VERSION;
   1360             break;
   1361         case OPT_SRP_MOREGROUPS:
   1362             srp_arg.amp = 1;
   1363             if (min_version < TLS1_VERSION)
   1364                 min_version = TLS1_VERSION;
   1365             break;
   1366 #endif
   1367         case OPT_SSL_CONFIG:
   1368             ssl_config = opt_arg();
   1369             break;
   1370         case OPT_SSL3:
   1371             min_version = SSL3_VERSION;
   1372             max_version = SSL3_VERSION;
   1373             socket_type = SOCK_STREAM;
   1374 #ifndef OPENSSL_NO_DTLS
   1375             isdtls = 0;
   1376 #endif
   1377             isquic = 0;
   1378             break;
   1379         case OPT_TLS1_3:
   1380             min_version = TLS1_3_VERSION;
   1381             max_version = TLS1_3_VERSION;
   1382             socket_type = SOCK_STREAM;
   1383 #ifndef OPENSSL_NO_DTLS
   1384             isdtls = 0;
   1385 #endif
   1386             isquic = 0;
   1387             break;
   1388         case OPT_TLS1_2:
   1389             min_version = TLS1_2_VERSION;
   1390             max_version = TLS1_2_VERSION;
   1391             socket_type = SOCK_STREAM;
   1392 #ifndef OPENSSL_NO_DTLS
   1393             isdtls = 0;
   1394 #endif
   1395             isquic = 0;
   1396             break;
   1397         case OPT_TLS1_1:
   1398             min_version = TLS1_1_VERSION;
   1399             max_version = TLS1_1_VERSION;
   1400             socket_type = SOCK_STREAM;
   1401 #ifndef OPENSSL_NO_DTLS
   1402             isdtls = 0;
   1403 #endif
   1404             isquic = 0;
   1405             break;
   1406         case OPT_TLS1:
   1407             min_version = TLS1_VERSION;
   1408             max_version = TLS1_VERSION;
   1409             socket_type = SOCK_STREAM;
   1410 #ifndef OPENSSL_NO_DTLS
   1411             isdtls = 0;
   1412 #endif
   1413             isquic = 0;
   1414             break;
   1415         case OPT_DTLS:
   1416 #ifndef OPENSSL_NO_DTLS
   1417             meth = DTLS_client_method();
   1418             socket_type = SOCK_DGRAM;
   1419             isdtls = 1;
   1420             isquic = 0;
   1421 #endif
   1422             break;
   1423         case OPT_DTLS1:
   1424 #ifndef OPENSSL_NO_DTLS1
   1425             meth = DTLS_client_method();
   1426             min_version = DTLS1_VERSION;
   1427             max_version = DTLS1_VERSION;
   1428             socket_type = SOCK_DGRAM;
   1429             isdtls = 1;
   1430             isquic = 0;
   1431 #endif
   1432             break;
   1433         case OPT_DTLS1_2:
   1434 #ifndef OPENSSL_NO_DTLS1_2
   1435             meth = DTLS_client_method();
   1436             min_version = DTLS1_2_VERSION;
   1437             max_version = DTLS1_2_VERSION;
   1438             socket_type = SOCK_DGRAM;
   1439             isdtls = 1;
   1440             isquic = 0;
   1441 #endif
   1442             break;
   1443         case OPT_QUIC:
   1444 #ifndef OPENSSL_NO_QUIC
   1445             meth = OSSL_QUIC_client_method();
   1446             min_version = 0;
   1447             max_version = 0;
   1448             socket_type = SOCK_DGRAM;
   1449 #ifndef OPENSSL_NO_DTLS
   1450             isdtls = 0;
   1451 #endif
   1452             isquic = 1;
   1453 #endif
   1454             break;
   1455         case OPT_SCTP:
   1456 #ifndef OPENSSL_NO_SCTP
   1457             protocol = IPPROTO_SCTP;
   1458 #endif
   1459             break;
   1460         case OPT_SCTP_LABEL_BUG:
   1461 #ifndef OPENSSL_NO_SCTP
   1462             sctp_label_bug = 1;
   1463 #endif
   1464             break;
   1465         case OPT_TIMEOUT:
   1466 #ifndef OPENSSL_NO_DTLS
   1467             enable_timeouts = 1;
   1468 #endif
   1469             break;
   1470         case OPT_MTU:
   1471 #ifndef OPENSSL_NO_DTLS
   1472             socket_mtu = atol(opt_arg());
   1473 #endif
   1474             break;
   1475         case OPT_FALLBACKSCSV:
   1476             fallback_scsv = 1;
   1477             break;
   1478         case OPT_KEYFORM:
   1479             if (!opt_format(opt_arg(), OPT_FMT_ANY, &key_format))
   1480                 goto opthelp;
   1481             break;
   1482         case OPT_PASS:
   1483             passarg = opt_arg();
   1484             break;
   1485         case OPT_CERT_CHAIN:
   1486             chain_file = opt_arg();
   1487             break;
   1488         case OPT_KEY:
   1489             key_file = opt_arg();
   1490             break;
   1491         case OPT_RECONNECT:
   1492             reconnect = 5;
   1493             break;
   1494         case OPT_CAPATH:
   1495             CApath = opt_arg();
   1496             break;
   1497         case OPT_NOCAPATH:
   1498             noCApath = 1;
   1499             break;
   1500         case OPT_CHAINCAPATH:
   1501             chCApath = opt_arg();
   1502             break;
   1503         case OPT_VERIFYCAPATH:
   1504             vfyCApath = opt_arg();
   1505             break;
   1506         case OPT_BUILD_CHAIN:
   1507             build_chain = 1;
   1508             break;
   1509         case OPT_REQCAFILE:
   1510             ReqCAfile = opt_arg();
   1511             break;
   1512         case OPT_CAFILE:
   1513             CAfile = opt_arg();
   1514             break;
   1515         case OPT_NOCAFILE:
   1516             noCAfile = 1;
   1517             break;
   1518 #ifndef OPENSSL_NO_CT
   1519         case OPT_NOCT:
   1520             ct_validation = 0;
   1521             break;
   1522         case OPT_CT:
   1523             ct_validation = 1;
   1524             break;
   1525         case OPT_CTLOG_FILE:
   1526             ctlog_file = opt_arg();
   1527             break;
   1528 #endif
   1529         case OPT_CHAINCAFILE:
   1530             chCAfile = opt_arg();
   1531             break;
   1532         case OPT_VERIFYCAFILE:
   1533             vfyCAfile = opt_arg();
   1534             break;
   1535         case OPT_CASTORE:
   1536             CAstore = opt_arg();
   1537             break;
   1538         case OPT_NOCASTORE:
   1539             noCAstore = 1;
   1540             break;
   1541         case OPT_CHAINCASTORE:
   1542             chCAstore = opt_arg();
   1543             break;
   1544         case OPT_VERIFYCASTORE:
   1545             vfyCAstore = opt_arg();
   1546             break;
   1547         case OPT_DANE_TLSA_DOMAIN:
   1548             dane_tlsa_domain = opt_arg();
   1549             break;
   1550         case OPT_DANE_TLSA_RRDATA:
   1551             if (dane_tlsa_rrset == NULL)
   1552                 dane_tlsa_rrset = sk_OPENSSL_STRING_new_null();
   1553             if (dane_tlsa_rrset == NULL || !sk_OPENSSL_STRING_push(dane_tlsa_rrset, opt_arg())) {
   1554                 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
   1555                 goto end;
   1556             }
   1557             break;
   1558         case OPT_DANE_EE_NO_NAME:
   1559             dane_ee_no_name = 1;
   1560             break;
   1561         case OPT_NEXTPROTONEG:
   1562 #ifndef OPENSSL_NO_NEXTPROTONEG
   1563             next_proto_neg_in = opt_arg();
   1564 #endif
   1565             break;
   1566         case OPT_ALPN:
   1567             alpn_in = opt_arg();
   1568             break;
   1569         case OPT_SERVERINFO:
   1570             p = opt_arg();
   1571             len = strlen(p);
   1572             for (start = 0, i = 0; i <= len; ++i) {
   1573                 if (i == len || p[i] == ',') {
   1574                     serverinfo_types[serverinfo_count] = atoi(p + start);
   1575                     if (++serverinfo_count == MAX_SI_TYPES)
   1576                         break;
   1577                     start = i + 1;
   1578                 }
   1579             }
   1580             break;
   1581         case OPT_STARTTLS:
   1582             if (!opt_pair(opt_arg(), services, &starttls_proto))
   1583                 goto end;
   1584             break;
   1585         case OPT_TFO:
   1586             tfo = 1;
   1587             break;
   1588         case OPT_SERVERNAME:
   1589             servername = opt_arg();
   1590             break;
   1591         case OPT_NOSERVERNAME:
   1592             noservername = 1;
   1593             break;
   1594         case OPT_USE_SRTP:
   1595 #ifndef OPENSSL_NO_SRTP
   1596             srtp_profiles = opt_arg();
   1597 #endif
   1598             break;
   1599         case OPT_KEYMATEXPORT:
   1600             keymatexportlabel = opt_arg();
   1601             break;
   1602         case OPT_KEYMATEXPORTLEN:
   1603             keymatexportlen = atoi(opt_arg());
   1604             break;
   1605         case OPT_ASYNC:
   1606             async = 1;
   1607             break;
   1608         case OPT_MAXFRAGLEN:
   1609             len = atoi(opt_arg());
   1610             switch (len) {
   1611             case 512:
   1612                 maxfraglen = TLSEXT_max_fragment_length_512;
   1613                 break;
   1614             case 1024:
   1615                 maxfraglen = TLSEXT_max_fragment_length_1024;
   1616                 break;
   1617             case 2048:
   1618                 maxfraglen = TLSEXT_max_fragment_length_2048;
   1619                 break;
   1620             case 4096:
   1621                 maxfraglen = TLSEXT_max_fragment_length_4096;
   1622                 break;
   1623             default:
   1624                 BIO_printf(bio_err,
   1625                     "%s: Max Fragment Len %u is out of permitted values",
   1626                     prog, len);
   1627                 goto opthelp;
   1628             }
   1629             break;
   1630         case OPT_MAX_SEND_FRAG:
   1631             max_send_fragment = atoi(opt_arg());
   1632             break;
   1633         case OPT_SPLIT_SEND_FRAG:
   1634             split_send_fragment = atoi(opt_arg());
   1635             break;
   1636         case OPT_MAX_PIPELINES:
   1637             max_pipelines = atoi(opt_arg());
   1638             break;
   1639         case OPT_READ_BUF:
   1640             read_buf_len = atoi(opt_arg());
   1641             break;
   1642         case OPT_KEYLOG_FILE:
   1643             keylog_file = opt_arg();
   1644             break;
   1645         case OPT_EARLY_DATA:
   1646             early_data_file = opt_arg();
   1647             break;
   1648         case OPT_ENABLE_PHA:
   1649             enable_pha = 1;
   1650             break;
   1651         case OPT_KTLS:
   1652 #ifndef OPENSSL_NO_KTLS
   1653             enable_ktls = 1;
   1654 #endif
   1655             break;
   1656         case OPT_ENABLE_SERVER_RPK:
   1657             enable_server_rpk = 1;
   1658             break;
   1659         case OPT_ENABLE_CLIENT_RPK:
   1660             enable_client_rpk = 1;
   1661             break;
   1662         }
   1663     }
   1664 
   1665     /* Optional argument is connect string if -connect not used. */
   1666     if (opt_num_rest() == 1) {
   1667         /* Don't allow -connect and a separate argument. */
   1668         if (connectstr != NULL) {
   1669             BIO_printf(bio_err,
   1670                 "%s: cannot provide both -connect option and target parameter\n",
   1671                 prog);
   1672             goto opthelp;
   1673         }
   1674         connect_type = use_inet;
   1675         freeandcopy(&connectstr, *opt_rest());
   1676     } else if (!opt_check_rest_arg(NULL)) {
   1677         goto opthelp;
   1678     }
   1679     if (!app_RAND_load())
   1680         goto end;
   1681 
   1682     if (c_ign_eof)
   1683         cmdmode = USER_DATA_MODE_NONE;
   1684 
   1685     if (count4or6 >= 2) {
   1686         BIO_printf(bio_err, "%s: Can't use both -4 and -6\n", prog);
   1687         goto opthelp;
   1688     }
   1689     if (noservername) {
   1690         if (servername != NULL) {
   1691             BIO_printf(bio_err,
   1692                 "%s: Can't use -servername and -noservername together\n",
   1693                 prog);
   1694             goto opthelp;
   1695         }
   1696         if (dane_tlsa_domain != NULL) {
   1697             BIO_printf(bio_err,
   1698                 "%s: Can't use -dane_tlsa_domain and -noservername together\n",
   1699                 prog);
   1700             goto opthelp;
   1701         }
   1702     }
   1703 
   1704 #ifndef OPENSSL_NO_NEXTPROTONEG
   1705     if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) {
   1706         BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n");
   1707         goto opthelp;
   1708     }
   1709 #endif
   1710 
   1711     if (connectstr != NULL) {
   1712         int res;
   1713         char *tmp_host = host, *tmp_port = port;
   1714 
   1715         res = BIO_parse_hostserv(connectstr, &host, &port, BIO_PARSE_PRIO_HOST);
   1716         if (tmp_host != host)
   1717             OPENSSL_free(tmp_host);
   1718         if (tmp_port != port)
   1719             OPENSSL_free(tmp_port);
   1720         if (!res) {
   1721             BIO_printf(bio_err,
   1722                 "%s: -connect argument or target parameter malformed or ambiguous\n",
   1723                 prog);
   1724             goto end;
   1725         }
   1726     }
   1727 
   1728     if (proxystr != NULL) {
   1729 #ifndef OPENSSL_NO_HTTP
   1730         int res;
   1731         char *tmp_host = host, *tmp_port = port;
   1732 
   1733         if (host == NULL || port == NULL) {
   1734             BIO_printf(bio_err, "%s: -proxy requires use of -connect or target parameter\n", prog);
   1735             goto opthelp;
   1736         }
   1737 
   1738         if (servername == NULL && !noservername) {
   1739             servername = sname_alloc = OPENSSL_strdup(host);
   1740             if (sname_alloc == NULL) {
   1741                 BIO_printf(bio_err, "%s: out of memory\n", prog);
   1742                 goto end;
   1743             }
   1744         }
   1745 
   1746         /* Retain the original target host:port for use in the HTTP proxy connect string */
   1747         thost = OPENSSL_strdup(host);
   1748         tport = OPENSSL_strdup(port);
   1749         if (thost == NULL || tport == NULL) {
   1750             BIO_printf(bio_err, "%s: out of memory\n", prog);
   1751             goto end;
   1752         }
   1753 
   1754         res = BIO_parse_hostserv(proxystr, &host, &port, BIO_PARSE_PRIO_HOST);
   1755         if (tmp_host != host)
   1756             OPENSSL_free(tmp_host);
   1757         if (tmp_port != port)
   1758             OPENSSL_free(tmp_port);
   1759         if (!res) {
   1760             BIO_printf(bio_err,
   1761                 "%s: -proxy argument malformed or ambiguous\n", prog);
   1762             goto end;
   1763         }
   1764 #else
   1765         BIO_printf(bio_err,
   1766             "%s: -proxy not supported in no-http build\n", prog);
   1767         goto end;
   1768 #endif
   1769     }
   1770 
   1771     if (bindstr != NULL) {
   1772         int res;
   1773         res = BIO_parse_hostserv(bindstr, &bindhost, &bindport,
   1774             BIO_PARSE_PRIO_HOST);
   1775         if (!res) {
   1776             BIO_printf(bio_err,
   1777                 "%s: -bind argument parameter malformed or ambiguous\n",
   1778                 prog);
   1779             goto end;
   1780         }
   1781     }
   1782 
   1783 #ifdef AF_UNIX
   1784     if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
   1785         BIO_printf(bio_err,
   1786             "Can't use unix sockets and datagrams together\n");
   1787         goto end;
   1788     }
   1789 #endif
   1790 
   1791 #ifndef OPENSSL_NO_SCTP
   1792     if (protocol == IPPROTO_SCTP) {
   1793         if (socket_type != SOCK_DGRAM) {
   1794             BIO_printf(bio_err, "Can't use -sctp without DTLS\n");
   1795             goto end;
   1796         }
   1797         /* SCTP is unusual. It uses DTLS over a SOCK_STREAM protocol */
   1798         socket_type = SOCK_STREAM;
   1799     }
   1800 #endif
   1801 
   1802 #if !defined(OPENSSL_NO_NEXTPROTONEG)
   1803     next_proto.status = -1;
   1804     if (next_proto_neg_in) {
   1805         next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in);
   1806         if (next_proto.data == NULL) {
   1807             BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n");
   1808             goto end;
   1809         }
   1810     } else
   1811         next_proto.data = NULL;
   1812 #endif
   1813 
   1814     if (!app_passwd(passarg, NULL, &pass, NULL)) {
   1815         BIO_printf(bio_err, "Error getting private key password\n");
   1816         goto end;
   1817     }
   1818 
   1819     if (!app_passwd(proxypassarg, NULL, &proxypass, NULL)) {
   1820         BIO_printf(bio_err, "Error getting proxy password\n");
   1821         goto end;
   1822     }
   1823 
   1824     if (proxypass != NULL && proxyuser == NULL) {
   1825         BIO_printf(bio_err, "Error: Must specify proxy_user with proxy_pass\n");
   1826         goto end;
   1827     }
   1828 
   1829     if (key_file == NULL)
   1830         key_file = cert_file;
   1831 
   1832     if (key_file != NULL) {
   1833         key = load_key(key_file, key_format, 0, pass, e,
   1834             "client certificate private key");
   1835         if (key == NULL)
   1836             goto end;
   1837     }
   1838 
   1839     if (cert_file != NULL) {
   1840         cert = load_cert_pass(cert_file, cert_format, 1, pass,
   1841             "client certificate");
   1842         if (cert == NULL)
   1843             goto end;
   1844     }
   1845 
   1846     if (chain_file != NULL) {
   1847         if (!load_certs(chain_file, 0, &chain, pass, "client certificate chain"))
   1848             goto end;
   1849     }
   1850 
   1851     if (crl_file != NULL) {
   1852         X509_CRL *crl;
   1853         crl = load_crl(crl_file, crl_format, 0, "CRL");
   1854         if (crl == NULL)
   1855             goto end;
   1856         crls = sk_X509_CRL_new_null();
   1857         if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
   1858             BIO_puts(bio_err, "Error adding CRL\n");
   1859             ERR_print_errors(bio_err);
   1860             X509_CRL_free(crl);
   1861             goto end;
   1862         }
   1863     }
   1864 
   1865     if (!load_excert(&exc))
   1866         goto end;
   1867 
   1868     if (bio_c_out == NULL) {
   1869         if (c_quiet && !c_debug) {
   1870             bio_c_out = BIO_new(BIO_s_null());
   1871             if (c_msg && bio_c_msg == NULL) {
   1872                 bio_c_msg = dup_bio_out(FORMAT_TEXT);
   1873                 if (bio_c_msg == NULL) {
   1874                     BIO_printf(bio_err, "Out of memory\n");
   1875                     goto end;
   1876                 }
   1877             }
   1878         } else {
   1879             bio_c_out = dup_bio_out(FORMAT_TEXT);
   1880         }
   1881 
   1882         if (bio_c_out == NULL) {
   1883             BIO_printf(bio_err, "Unable to create BIO\n");
   1884             goto end;
   1885         }
   1886     }
   1887 #ifndef OPENSSL_NO_SRP
   1888     if (!app_passwd(srppass, NULL, &srp_arg.srppassin, NULL)) {
   1889         BIO_printf(bio_err, "Error getting password\n");
   1890         goto end;
   1891     }
   1892 #endif
   1893 
   1894     ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth);
   1895     if (ctx == NULL) {
   1896         ERR_print_errors(bio_err);
   1897         goto end;
   1898     }
   1899 
   1900     SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
   1901 
   1902     if (sdebug)
   1903         ssl_ctx_security_debug(ctx, sdebug);
   1904 
   1905     if (!config_ctx(cctx, ssl_args, ctx))
   1906         goto end;
   1907 
   1908     if (ssl_config != NULL) {
   1909         if (SSL_CTX_config(ctx, ssl_config) == 0) {
   1910             BIO_printf(bio_err, "Error using configuration \"%s\"\n",
   1911                 ssl_config);
   1912             ERR_print_errors(bio_err);
   1913             goto end;
   1914         }
   1915     }
   1916 
   1917 #ifndef OPENSSL_NO_SCTP
   1918     if (protocol == IPPROTO_SCTP && sctp_label_bug == 1)
   1919         SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
   1920 #endif
   1921 
   1922     if (min_version != 0
   1923         && SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
   1924         goto end;
   1925     if (max_version != 0
   1926         && SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
   1927         goto end;
   1928 
   1929     if (ignore_unexpected_eof)
   1930         SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
   1931 #ifndef OPENSSL_NO_KTLS
   1932     if (enable_ktls)
   1933         SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS);
   1934 #endif
   1935 
   1936     if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
   1937         BIO_printf(bio_err, "Error setting verify params\n");
   1938         ERR_print_errors(bio_err);
   1939         goto end;
   1940     }
   1941 
   1942     if (async) {
   1943         SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
   1944     }
   1945 
   1946     if (max_send_fragment > 0
   1947         && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) {
   1948         BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n",
   1949             prog, max_send_fragment);
   1950         goto end;
   1951     }
   1952 
   1953     if (split_send_fragment > 0
   1954         && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) {
   1955         BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n",
   1956             prog, split_send_fragment);
   1957         goto end;
   1958     }
   1959 
   1960     if (max_pipelines > 0
   1961         && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) {
   1962         BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n",
   1963             prog, max_pipelines);
   1964         goto end;
   1965     }
   1966 
   1967     if (read_buf_len > 0) {
   1968         SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
   1969     }
   1970 
   1971     if (maxfraglen > 0
   1972         && !SSL_CTX_set_tlsext_max_fragment_length(ctx, maxfraglen)) {
   1973         BIO_printf(bio_err,
   1974             "%s: Max Fragment Length code %u is out of permitted values"
   1975             "\n",
   1976             prog, maxfraglen);
   1977         goto end;
   1978     }
   1979 
   1980     if (!ssl_load_stores(ctx,
   1981             vfyCApath, vfyCAfile, vfyCAstore,
   1982             chCApath, chCAfile, chCAstore,
   1983             crls, crl_download)) {
   1984         BIO_printf(bio_err, "Error loading store locations\n");
   1985         ERR_print_errors(bio_err);
   1986         goto end;
   1987     }
   1988     if (ReqCAfile != NULL) {
   1989         STACK_OF(X509_NAME) *nm = sk_X509_NAME_new_null();
   1990 
   1991         if (nm == NULL || !SSL_add_file_cert_subjects_to_stack(nm, ReqCAfile)) {
   1992             sk_X509_NAME_pop_free(nm, X509_NAME_free);
   1993             BIO_printf(bio_err, "Error loading CA names\n");
   1994             ERR_print_errors(bio_err);
   1995             goto end;
   1996         }
   1997         SSL_CTX_set0_CA_list(ctx, nm);
   1998     }
   1999 #ifndef OPENSSL_NO_ENGINE
   2000     if (ssl_client_engine) {
   2001         if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) {
   2002             BIO_puts(bio_err, "Error setting client auth engine\n");
   2003             ERR_print_errors(bio_err);
   2004             release_engine(ssl_client_engine);
   2005             goto end;
   2006         }
   2007         release_engine(ssl_client_engine);
   2008     }
   2009 #endif
   2010 
   2011 #ifndef OPENSSL_NO_PSK
   2012     if (psk_key != NULL) {
   2013         if (c_debug)
   2014             BIO_printf(bio_c_out, "PSK key given, setting client callback\n");
   2015         SSL_CTX_set_psk_client_callback(ctx, psk_client_cb);
   2016     }
   2017 #endif
   2018     if (psksessf != NULL) {
   2019         BIO *stmp = BIO_new_file(psksessf, "r");
   2020 
   2021         if (stmp == NULL) {
   2022             BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf);
   2023             ERR_print_errors(bio_err);
   2024             goto end;
   2025         }
   2026         psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
   2027         BIO_free(stmp);
   2028         if (psksess == NULL) {
   2029             BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf);
   2030             ERR_print_errors(bio_err);
   2031             goto end;
   2032         }
   2033     }
   2034     if (psk_key != NULL || psksess != NULL)
   2035         SSL_CTX_set_psk_use_session_callback(ctx, psk_use_session_cb);
   2036 
   2037 #ifndef OPENSSL_NO_SRTP
   2038     if (srtp_profiles != NULL) {
   2039         /* Returns 0 on success! */
   2040         if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
   2041             BIO_printf(bio_err, "Error setting SRTP profile\n");
   2042             ERR_print_errors(bio_err);
   2043             goto end;
   2044         }
   2045     }
   2046 #endif
   2047 
   2048     if (exc != NULL)
   2049         ssl_ctx_set_excert(ctx, exc);
   2050 
   2051 #if !defined(OPENSSL_NO_NEXTPROTONEG)
   2052     if (next_proto.data != NULL)
   2053         SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto);
   2054 #endif
   2055     if (alpn_in) {
   2056         size_t alpn_len;
   2057         unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in);
   2058 
   2059         if (alpn == NULL) {
   2060             BIO_printf(bio_err, "Error parsing -alpn argument\n");
   2061             goto end;
   2062         }
   2063         /* Returns 0 on success! */
   2064         if (SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len) != 0) {
   2065             BIO_printf(bio_err, "Error setting ALPN\n");
   2066             goto end;
   2067         }
   2068         OPENSSL_free(alpn);
   2069     }
   2070 
   2071     for (i = 0; i < serverinfo_count; i++) {
   2072         if (!SSL_CTX_add_client_custom_ext(ctx,
   2073                 serverinfo_types[i],
   2074                 NULL, NULL, NULL,
   2075                 serverinfo_cli_parse_cb, NULL)) {
   2076             BIO_printf(bio_err,
   2077                 "Warning: Unable to add custom extension %u, skipping\n",
   2078                 serverinfo_types[i]);
   2079         }
   2080     }
   2081 
   2082     if (state)
   2083         SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
   2084 
   2085 #ifndef OPENSSL_NO_CT
   2086     /* Enable SCT processing, without early connection termination */
   2087     if (ct_validation && !SSL_CTX_enable_ct(ctx, SSL_CT_VALIDATION_PERMISSIVE)) {
   2088         ERR_print_errors(bio_err);
   2089         goto end;
   2090     }
   2091 
   2092     if (!ctx_set_ctlog_list_file(ctx, ctlog_file)) {
   2093         if (ct_validation) {
   2094             ERR_print_errors(bio_err);
   2095             goto end;
   2096         }
   2097 
   2098         /*
   2099          * If CT validation is not enabled, the log list isn't needed so don't
   2100          * show errors or abort. We try to load it regardless because then we
   2101          * can show the names of the logs any SCTs came from (SCTs may be seen
   2102          * even with validation disabled).
   2103          */
   2104         ERR_clear_error();
   2105     }
   2106 #endif
   2107 
   2108     SSL_CTX_set_verify(ctx, verify, verify_callback);
   2109 
   2110     if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath,
   2111             CAstore, noCAstore)) {
   2112         ERR_print_errors(bio_err);
   2113         goto end;
   2114     }
   2115 
   2116     ssl_ctx_add_crls(ctx, crls, crl_download);
   2117 
   2118     if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain))
   2119         goto end;
   2120 
   2121     if (!noservername) {
   2122         tlsextcbp.biodebug = bio_err;
   2123         SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
   2124         SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
   2125     }
   2126 #ifndef OPENSSL_NO_SRP
   2127     if (srp_arg.srplogin != NULL
   2128         && !set_up_srp_arg(ctx, &srp_arg, srp_lateuser, c_msg, c_debug))
   2129         goto end;
   2130 #endif
   2131 
   2132     if (dane_tlsa_domain != NULL) {
   2133         if (SSL_CTX_dane_enable(ctx) <= 0) {
   2134             BIO_printf(bio_err,
   2135                 "%s: Error enabling DANE TLSA authentication.\n",
   2136                 prog);
   2137             ERR_print_errors(bio_err);
   2138             goto end;
   2139         }
   2140     }
   2141 
   2142     /*
   2143      * In TLSv1.3 NewSessionTicket messages arrive after the handshake and can
   2144      * come at any time. Therefore, we use a callback to write out the session
   2145      * when we know about it. This approach works for < TLSv1.3 as well.
   2146      */
   2147     SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
   2148     SSL_CTX_sess_set_new_cb(ctx, new_session_cb);
   2149 
   2150     if (set_keylog_file(ctx, keylog_file))
   2151         goto end;
   2152 
   2153     con = SSL_new(ctx);
   2154     if (con == NULL)
   2155         goto end;
   2156 
   2157     if (enable_pha)
   2158         SSL_set_post_handshake_auth(con, 1);
   2159 
   2160     if (enable_client_rpk)
   2161         if (!SSL_set1_client_cert_type(con, cert_type_rpk, sizeof(cert_type_rpk))) {
   2162             BIO_printf(bio_err, "Error setting client certificate types\n");
   2163             goto end;
   2164         }
   2165     if (enable_server_rpk) {
   2166         if (!SSL_set1_server_cert_type(con, cert_type_rpk, sizeof(cert_type_rpk))) {
   2167             BIO_printf(bio_err, "Error setting server certificate types\n");
   2168             goto end;
   2169         }
   2170     }
   2171 
   2172     if (sess_in != NULL) {
   2173         SSL_SESSION *sess;
   2174         BIO *stmp = BIO_new_file(sess_in, "r");
   2175         if (stmp == NULL) {
   2176             BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
   2177             ERR_print_errors(bio_err);
   2178             goto end;
   2179         }
   2180         sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
   2181         BIO_free(stmp);
   2182         if (sess == NULL) {
   2183             BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
   2184             ERR_print_errors(bio_err);
   2185             goto end;
   2186         }
   2187         if (!SSL_set_session(con, sess)) {
   2188             BIO_printf(bio_err, "Can't set session\n");
   2189             ERR_print_errors(bio_err);
   2190             goto end;
   2191         }
   2192 
   2193         SSL_SESSION_free(sess);
   2194     }
   2195 
   2196     if (fallback_scsv)
   2197         SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV);
   2198 
   2199     if (!noservername && (servername != NULL || dane_tlsa_domain == NULL)) {
   2200         if (servername == NULL) {
   2201             if (host == NULL || is_dNS_name(host))
   2202                 servername = (host == NULL) ? "localhost" : host;
   2203         }
   2204         if (servername != NULL && !SSL_set_tlsext_host_name(con, servername)) {
   2205             BIO_printf(bio_err, "Unable to set TLS servername extension.\n");
   2206             ERR_print_errors(bio_err);
   2207             goto end;
   2208         }
   2209     }
   2210 
   2211     if (dane_tlsa_domain != NULL) {
   2212         if (SSL_dane_enable(con, dane_tlsa_domain) <= 0) {
   2213             BIO_printf(bio_err, "%s: Error enabling DANE TLSA "
   2214                                 "authentication.\n",
   2215                 prog);
   2216             ERR_print_errors(bio_err);
   2217             goto end;
   2218         }
   2219         if (dane_tlsa_rrset == NULL) {
   2220             BIO_printf(bio_err, "%s: DANE TLSA authentication requires at "
   2221                                 "least one -dane_tlsa_rrdata option.\n",
   2222                 prog);
   2223             goto end;
   2224         }
   2225         if (tlsa_import_rrset(con, dane_tlsa_rrset) <= 0) {
   2226             BIO_printf(bio_err, "%s: Failed to import any TLSA "
   2227                                 "records.\n",
   2228                 prog);
   2229             goto end;
   2230         }
   2231         if (dane_ee_no_name)
   2232             SSL_dane_set_flags(con, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
   2233     } else if (dane_tlsa_rrset != NULL) {
   2234         BIO_printf(bio_err, "%s: DANE TLSA authentication requires the "
   2235                             "-dane_tlsa_domain option.\n",
   2236             prog);
   2237         goto end;
   2238     }
   2239 #ifndef OPENSSL_NO_DTLS
   2240     if (isdtls && tfo) {
   2241         BIO_printf(bio_err, "%s: DTLS does not support the -tfo option\n", prog);
   2242         goto end;
   2243     }
   2244 #endif
   2245 #ifndef OPENSSL_NO_QUIC
   2246     if (isquic && tfo) {
   2247         BIO_printf(bio_err, "%s: QUIC does not support the -tfo option\n", prog);
   2248         goto end;
   2249     }
   2250     if (isquic && alpn_in == NULL) {
   2251         BIO_printf(bio_err, "%s: QUIC requires ALPN to be specified (e.g. \"h3\" for HTTP/3) via the -alpn option\n", prog);
   2252         goto end;
   2253     }
   2254 #endif
   2255 
   2256     if (tfo)
   2257         BIO_printf(bio_c_out, "Connecting via TFO\n");
   2258 re_start:
   2259     /* peer_addr might be set from previous connections */
   2260     BIO_ADDR_free(peer_addr);
   2261     peer_addr = NULL;
   2262     if (init_client(&sock, host, port, bindhost, bindport, socket_family,
   2263             socket_type, protocol, tfo, !isquic, &peer_addr)
   2264         == 0) {
   2265         BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error());
   2266         BIO_closesocket(sock);
   2267         goto end;
   2268     }
   2269     BIO_printf(bio_c_out, "CONNECTED(%08X)\n", sock);
   2270 
   2271     /*
   2272      * QUIC always uses a non-blocking socket - and we have to switch on
   2273      * non-blocking mode at the SSL level
   2274      */
   2275     if (c_nbio || isquic) {
   2276         if (!BIO_socket_nbio(sock, 1)) {
   2277             ERR_print_errors(bio_err);
   2278             goto end;
   2279         }
   2280         if (c_nbio) {
   2281             if (isquic && !SSL_set_blocking_mode(con, 0))
   2282                 goto end;
   2283             BIO_printf(bio_c_out, "Turned on non blocking io\n");
   2284         }
   2285     }
   2286 #ifndef OPENSSL_NO_DTLS
   2287     if (isdtls) {
   2288         union BIO_sock_info_u peer_info;
   2289 
   2290 #ifndef OPENSSL_NO_SCTP
   2291         if (protocol == IPPROTO_SCTP)
   2292             sbio = BIO_new_dgram_sctp(sock, BIO_NOCLOSE);
   2293         else
   2294 #endif
   2295             sbio = BIO_new_dgram(sock, BIO_NOCLOSE);
   2296 
   2297         if (sbio == NULL || (peer_info.addr = BIO_ADDR_new()) == NULL) {
   2298             BIO_printf(bio_err, "memory allocation failure\n");
   2299             BIO_free(sbio);
   2300             BIO_closesocket(sock);
   2301             goto end;
   2302         }
   2303         if (!BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &peer_info)) {
   2304             BIO_printf(bio_err, "getsockname:errno=%d\n",
   2305                 get_last_socket_error());
   2306             BIO_free(sbio);
   2307             BIO_ADDR_free(peer_info.addr);
   2308             BIO_closesocket(sock);
   2309             goto end;
   2310         }
   2311 
   2312         (void)BIO_ctrl_set_connected(sbio, peer_info.addr);
   2313         BIO_ADDR_free(peer_info.addr);
   2314         peer_info.addr = NULL;
   2315 
   2316         if (enable_timeouts) {
   2317             timeout.tv_sec = 0;
   2318             timeout.tv_usec = DGRAM_RCV_TIMEOUT;
   2319             BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
   2320 
   2321             timeout.tv_sec = 0;
   2322             timeout.tv_usec = DGRAM_SND_TIMEOUT;
   2323             BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
   2324         }
   2325 
   2326         if (socket_mtu) {
   2327             if (socket_mtu < DTLS_get_link_min_mtu(con)) {
   2328                 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
   2329                     DTLS_get_link_min_mtu(con));
   2330                 BIO_free(sbio);
   2331                 goto shut;
   2332             }
   2333             SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
   2334             if (!DTLS_set_link_mtu(con, socket_mtu)) {
   2335                 BIO_printf(bio_err, "Failed to set MTU\n");
   2336                 BIO_free(sbio);
   2337                 goto shut;
   2338             }
   2339         } else {
   2340             /* want to do MTU discovery */
   2341             BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
   2342         }
   2343     } else
   2344 #endif /* OPENSSL_NO_DTLS */
   2345 #ifndef OPENSSL_NO_QUIC
   2346         if (isquic) {
   2347         sbio = BIO_new_dgram(sock, BIO_NOCLOSE);
   2348         if (!SSL_set1_initial_peer_addr(con, peer_addr)) {
   2349             BIO_printf(bio_err, "Failed to set the initial peer address\n");
   2350             goto shut;
   2351         }
   2352     } else
   2353 #endif
   2354         sbio = BIO_new_socket(sock, BIO_NOCLOSE);
   2355 
   2356     if (sbio == NULL) {
   2357         BIO_printf(bio_err, "Unable to create BIO\n");
   2358         ERR_print_errors(bio_err);
   2359         BIO_closesocket(sock);
   2360         goto end;
   2361     }
   2362 
   2363     /* Now that we're using a BIO... */
   2364     if (tfo) {
   2365         (void)BIO_set_conn_address(sbio, peer_addr);
   2366         (void)BIO_set_tfo(sbio, 1);
   2367     }
   2368 
   2369     if (nbio_test) {
   2370         BIO *test;
   2371 
   2372         test = BIO_new(BIO_f_nbio_test());
   2373         if (test == NULL) {
   2374             BIO_printf(bio_err, "Unable to create BIO\n");
   2375             BIO_free(sbio);
   2376             goto shut;
   2377         }
   2378         sbio = BIO_push(test, sbio);
   2379     }
   2380 
   2381     if (c_debug) {
   2382         BIO_set_callback_ex(sbio, bio_dump_callback);
   2383         BIO_set_callback_arg(sbio, (char *)bio_c_out);
   2384     }
   2385     if (c_msg) {
   2386 #ifndef OPENSSL_NO_SSL_TRACE
   2387         if (c_msg == 2)
   2388             SSL_set_msg_callback(con, SSL_trace);
   2389         else
   2390 #endif
   2391             SSL_set_msg_callback(con, msg_cb);
   2392         SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out);
   2393     }
   2394 
   2395     if (c_tlsextdebug) {
   2396         SSL_set_tlsext_debug_callback(con, tlsext_cb);
   2397         SSL_set_tlsext_debug_arg(con, bio_c_out);
   2398     }
   2399 #ifndef OPENSSL_NO_OCSP
   2400     if (c_status_req) {
   2401         SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
   2402         SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
   2403         SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
   2404     }
   2405 #endif
   2406 
   2407     SSL_set_bio(con, sbio, sbio);
   2408     SSL_set_connect_state(con);
   2409 
   2410     /* ok, lets connect */
   2411     if (fileno_stdin() > SSL_get_fd(con))
   2412         width = fileno_stdin() + 1;
   2413     else
   2414         width = SSL_get_fd(con) + 1;
   2415 
   2416     read_tty = 1;
   2417     write_tty = 0;
   2418     tty_on = 0;
   2419     read_ssl = 1;
   2420     write_ssl = 1;
   2421     first_loop = 1;
   2422 
   2423     cbuf_len = 0;
   2424     cbuf_off = 0;
   2425     sbuf_len = 0;
   2426     sbuf_off = 0;
   2427 
   2428 #ifndef OPENSSL_NO_HTTP
   2429     if (proxystr != NULL) {
   2430         /* Here we must use the connect string target host & port */
   2431         if (!OSSL_HTTP_proxy_connect(sbio, thost, tport, proxyuser, proxypass,
   2432                 0 /* no timeout */, bio_err, prog))
   2433             goto shut;
   2434     }
   2435 #endif
   2436 
   2437     switch ((PROTOCOL_CHOICE)starttls_proto) {
   2438     case PROTO_OFF:
   2439         break;
   2440     case PROTO_LMTP:
   2441     case PROTO_SMTP: {
   2442         /*
   2443          * This is an ugly hack that does a lot of assumptions. We do
   2444          * have to handle multi-line responses which may come in a single
   2445          * packet or not. We therefore have to use BIO_gets() which does
   2446          * need a buffering BIO. So during the initial chitchat we do
   2447          * push a buffering BIO into the chain that is removed again
   2448          * later on to not disturb the rest of the s_client operation.
   2449          */
   2450         int foundit = 0;
   2451         BIO *fbio = BIO_new(BIO_f_buffer());
   2452 
   2453         if (fbio == NULL) {
   2454             BIO_printf(bio_err, "Unable to create BIO\n");
   2455             goto shut;
   2456         }
   2457         BIO_push(fbio, sbio);
   2458         /* Wait for multi-line response to end from LMTP or SMTP */
   2459         do {
   2460             mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
   2461         } while (mbuf_len > 3 && mbuf[3] == '-');
   2462         if (protohost == NULL)
   2463             protohost = "mail.example.com";
   2464         if (starttls_proto == (int)PROTO_LMTP)
   2465             BIO_printf(fbio, "LHLO %s\r\n", protohost);
   2466         else
   2467             BIO_printf(fbio, "EHLO %s\r\n", protohost);
   2468         (void)BIO_flush(fbio);
   2469         /*
   2470          * Wait for multi-line response to end LHLO LMTP or EHLO SMTP
   2471          * response.
   2472          */
   2473         do {
   2474             mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
   2475             if (strstr(mbuf, "STARTTLS"))
   2476                 foundit = 1;
   2477         } while (mbuf_len > 3 && mbuf[3] == '-');
   2478         (void)BIO_flush(fbio);
   2479         BIO_pop(fbio);
   2480         BIO_free(fbio);
   2481         if (!foundit)
   2482             BIO_printf(bio_err,
   2483                 "Didn't find STARTTLS in server response,"
   2484                 " trying anyway...\n");
   2485         BIO_printf(sbio, "STARTTLS\r\n");
   2486         BIO_read(sbio, sbuf, BUFSIZZ);
   2487     } break;
   2488     case PROTO_POP3: {
   2489         BIO_read(sbio, mbuf, BUFSIZZ);
   2490         BIO_printf(sbio, "STLS\r\n");
   2491         mbuf_len = BIO_read(sbio, sbuf, BUFSIZZ);
   2492         if (mbuf_len < 0) {
   2493             BIO_printf(bio_err, "BIO_read failed\n");
   2494             goto end;
   2495         }
   2496     } break;
   2497     case PROTO_IMAP: {
   2498         int foundit = 0;
   2499         BIO *fbio = BIO_new(BIO_f_buffer());
   2500 
   2501         if (fbio == NULL) {
   2502             BIO_printf(bio_err, "Unable to create BIO\n");
   2503             goto shut;
   2504         }
   2505         BIO_push(fbio, sbio);
   2506         BIO_gets(fbio, mbuf, BUFSIZZ);
   2507         /* STARTTLS command requires CAPABILITY... */
   2508         BIO_printf(fbio, ". CAPABILITY\r\n");
   2509         (void)BIO_flush(fbio);
   2510         /* wait for multi-line CAPABILITY response */
   2511         do {
   2512             mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
   2513             if (strstr(mbuf, "STARTTLS"))
   2514                 foundit = 1;
   2515         } while (mbuf_len > 3 && mbuf[0] != '.');
   2516         (void)BIO_flush(fbio);
   2517         BIO_pop(fbio);
   2518         BIO_free(fbio);
   2519         if (!foundit)
   2520             BIO_printf(bio_err,
   2521                 "Didn't find STARTTLS in server response,"
   2522                 " trying anyway...\n");
   2523         BIO_printf(sbio, ". STARTTLS\r\n");
   2524         BIO_read(sbio, sbuf, BUFSIZZ);
   2525     } break;
   2526     case PROTO_FTP: {
   2527         BIO *fbio = BIO_new(BIO_f_buffer());
   2528 
   2529         if (fbio == NULL) {
   2530             BIO_printf(bio_err, "Unable to create BIO\n");
   2531             goto shut;
   2532         }
   2533         BIO_push(fbio, sbio);
   2534         /* wait for multi-line response to end from FTP */
   2535         do {
   2536             mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
   2537         } while (mbuf_len > 3 && (!isdigit((unsigned char)mbuf[0]) || !isdigit((unsigned char)mbuf[1]) || !isdigit((unsigned char)mbuf[2]) || mbuf[3] != ' '));
   2538         (void)BIO_flush(fbio);
   2539         BIO_pop(fbio);
   2540         BIO_free(fbio);
   2541         BIO_printf(sbio, "AUTH TLS\r\n");
   2542         BIO_read(sbio, sbuf, BUFSIZZ);
   2543     } break;
   2544     case PROTO_XMPP:
   2545     case PROTO_XMPP_SERVER: {
   2546         int seen = 0;
   2547         BIO_printf(sbio, "<stream:stream "
   2548                          "xmlns:stream='http://etherx.jabber.org/streams' "
   2549                          "xmlns='jabber:%s' to='%s' version='1.0'>",
   2550             starttls_proto == PROTO_XMPP ? "client" : "server",
   2551             protohost ? protohost : host);
   2552         seen = BIO_read(sbio, mbuf, BUFSIZZ);
   2553         if (seen < 0) {
   2554             BIO_printf(bio_err, "BIO_read failed\n");
   2555             goto end;
   2556         }
   2557         mbuf[seen] = '\0';
   2558         while (!strstr(mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")
   2559             && !strstr(mbuf,
   2560                 "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"")) {
   2561             seen = BIO_read(sbio, mbuf, BUFSIZZ);
   2562 
   2563             if (seen <= 0)
   2564                 goto shut;
   2565 
   2566             mbuf[seen] = '\0';
   2567         }
   2568         BIO_printf(sbio,
   2569             "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
   2570         seen = BIO_read(sbio, sbuf, BUFSIZZ);
   2571         if (seen < 0) {
   2572             BIO_printf(bio_err, "BIO_read failed\n");
   2573             goto shut;
   2574         }
   2575         sbuf[seen] = '\0';
   2576         if (!strstr(sbuf, "<proceed"))
   2577             goto shut;
   2578         mbuf[0] = '\0';
   2579     } break;
   2580     case PROTO_TELNET: {
   2581         static const unsigned char tls_do[] = {
   2582             /* IAC    DO   START_TLS */
   2583             255, 253, 46
   2584         };
   2585         static const unsigned char tls_will[] = {
   2586             /* IAC  WILL START_TLS */
   2587             255, 251, 46
   2588         };
   2589         static const unsigned char tls_follows[] = {
   2590             /* IAC  SB   START_TLS FOLLOWS IAC  SE */
   2591             255, 250, 46, 1, 255, 240
   2592         };
   2593         int bytes;
   2594 
   2595         /* Telnet server should demand we issue START_TLS */
   2596         bytes = BIO_read(sbio, mbuf, BUFSIZZ);
   2597         if (bytes != 3 || memcmp(mbuf, tls_do, 3) != 0)
   2598             goto shut;
   2599         /* Agree to issue START_TLS and send the FOLLOWS sub-command */
   2600         BIO_write(sbio, tls_will, 3);
   2601         BIO_write(sbio, tls_follows, 6);
   2602         (void)BIO_flush(sbio);
   2603         /* Telnet server also sent the FOLLOWS sub-command */
   2604         bytes = BIO_read(sbio, mbuf, BUFSIZZ);
   2605         if (bytes != 6 || memcmp(mbuf, tls_follows, 6) != 0)
   2606             goto shut;
   2607     } break;
   2608     case PROTO_IRC: {
   2609         int numeric;
   2610         BIO *fbio = BIO_new(BIO_f_buffer());
   2611 
   2612         if (fbio == NULL) {
   2613             BIO_printf(bio_err, "Unable to create BIO\n");
   2614             goto end;
   2615         }
   2616         BIO_push(fbio, sbio);
   2617         BIO_printf(fbio, "STARTTLS\r\n");
   2618         (void)BIO_flush(fbio);
   2619         width = SSL_get_fd(con) + 1;
   2620 
   2621         do {
   2622             numeric = 0;
   2623 
   2624             FD_ZERO(&readfds);
   2625             openssl_fdset(SSL_get_fd(con), &readfds);
   2626             timeout.tv_sec = S_CLIENT_IRC_READ_TIMEOUT;
   2627             timeout.tv_usec = 0;
   2628             /*
   2629              * If the IRCd doesn't respond within
   2630              * S_CLIENT_IRC_READ_TIMEOUT seconds, assume
   2631              * it doesn't support STARTTLS. Many IRCds
   2632              * will not give _any_ sort of response to a
   2633              * STARTTLS command when it's not supported.
   2634              */
   2635             if (!BIO_get_buffer_num_lines(fbio)
   2636                 && !BIO_pending(fbio)
   2637                 && !BIO_pending(sbio)
   2638                 && select(width, (void *)&readfds, NULL, NULL,
   2639                        &timeout)
   2640                     < 1) {
   2641                 BIO_printf(bio_err,
   2642                     "Timeout waiting for response (%d seconds).\n",
   2643                     S_CLIENT_IRC_READ_TIMEOUT);
   2644                 break;
   2645             }
   2646 
   2647             mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
   2648             if (mbuf_len < 1 || sscanf(mbuf, "%*s %d", &numeric) != 1)
   2649                 break;
   2650             /* :example.net 451 STARTTLS :You have not registered */
   2651             /* :example.net 421 STARTTLS :Unknown command */
   2652             if ((numeric == 451 || numeric == 421)
   2653                 && strstr(mbuf, "STARTTLS") != NULL) {
   2654                 BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
   2655                 break;
   2656             }
   2657             if (numeric == 691) {
   2658                 BIO_printf(bio_err, "STARTTLS negotiation failed: ");
   2659                 ERR_print_errors(bio_err);
   2660                 break;
   2661             }
   2662         } while (numeric != 670);
   2663 
   2664         (void)BIO_flush(fbio);
   2665         BIO_pop(fbio);
   2666         BIO_free(fbio);
   2667         if (numeric != 670) {
   2668             BIO_printf(bio_err, "Server does not support STARTTLS.\n");
   2669             ret = 1;
   2670             goto shut;
   2671         }
   2672     } break;
   2673     case PROTO_MYSQL: {
   2674         /* SSL request packet */
   2675         static const unsigned char ssl_req[] = {
   2676             /* payload_length,   sequence_id */
   2677             0x20, 0x00, 0x00, 0x01,
   2678             /* payload */
   2679             /* capability flags, CLIENT_SSL always set */
   2680             0x85, 0xae, 0x7f, 0x00,
   2681             /* max-packet size */
   2682             0x00, 0x00, 0x00, 0x01,
   2683             /* character set */
   2684             0x21,
   2685             /* string[23] reserved (all [0]) */
   2686             0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   2687             0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   2688             0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
   2689         };
   2690         int bytes = 0;
   2691         int ssl_flg = 0x800;
   2692         int pos;
   2693         const unsigned char *packet = (const unsigned char *)sbuf;
   2694 
   2695         /* Receiving Initial Handshake packet. */
   2696         bytes = BIO_read(sbio, (void *)packet, BUFSIZZ);
   2697         if (bytes < 0) {
   2698             BIO_printf(bio_err, "BIO_read failed\n");
   2699             goto shut;
   2700             /* Packet length[3], Packet number[1] + minimum payload[17] */
   2701         } else if (bytes < 21) {
   2702             BIO_printf(bio_err, "MySQL packet too short.\n");
   2703             goto shut;
   2704         } else if (bytes != (4 + packet[0] + (packet[1] << 8) + (packet[2] << 16))) {
   2705             BIO_printf(bio_err, "MySQL packet length does not match.\n");
   2706             goto shut;
   2707             /* protocol version[1] */
   2708         } else if (packet[4] != 0xA) {
   2709             BIO_printf(bio_err,
   2710                 "Only MySQL protocol version 10 is supported.\n");
   2711             goto shut;
   2712         }
   2713 
   2714         pos = 5;
   2715         /* server version[string+NULL] */
   2716         for (;;) {
   2717             if (pos >= bytes) {
   2718                 BIO_printf(bio_err, "Cannot confirm server version. ");
   2719                 goto shut;
   2720             } else if (packet[pos++] == '\0') {
   2721                 break;
   2722             }
   2723         }
   2724 
   2725         /* make sure we have at least 15 bytes left in the packet */
   2726         if (pos + 15 > bytes) {
   2727             BIO_printf(bio_err,
   2728                 "MySQL server handshake packet is broken.\n");
   2729             goto shut;
   2730         }
   2731 
   2732         pos += 12; /* skip over conn id[4] + SALT[8] */
   2733         if (packet[pos++] != '\0') { /* verify filler */
   2734             BIO_printf(bio_err,
   2735                 "MySQL packet is broken.\n");
   2736             goto shut;
   2737         }
   2738 
   2739         /* capability flags[2] */
   2740         if (!((packet[pos] + (packet[pos + 1] << 8)) & ssl_flg)) {
   2741             BIO_printf(bio_err, "MySQL server does not support SSL.\n");
   2742             goto shut;
   2743         }
   2744 
   2745         /* Sending SSL Handshake packet. */
   2746         BIO_write(sbio, ssl_req, sizeof(ssl_req));
   2747         (void)BIO_flush(sbio);
   2748     } break;
   2749     case PROTO_POSTGRES: {
   2750         static const unsigned char ssl_request[] = {
   2751             /* Length        SSLRequest */
   2752             0, 0, 0, 8, 4, 210, 22, 47
   2753         };
   2754         int bytes;
   2755 
   2756         /* Send SSLRequest packet */
   2757         BIO_write(sbio, ssl_request, 8);
   2758         (void)BIO_flush(sbio);
   2759 
   2760         /* Reply will be a single S if SSL is enabled */
   2761         bytes = BIO_read(sbio, sbuf, BUFSIZZ);
   2762         if (bytes != 1 || sbuf[0] != 'S')
   2763             goto shut;
   2764     } break;
   2765     case PROTO_NNTP: {
   2766         int foundit = 0;
   2767         BIO *fbio = BIO_new(BIO_f_buffer());
   2768 
   2769         if (fbio == NULL) {
   2770             BIO_printf(bio_err, "Unable to create BIO\n");
   2771             goto end;
   2772         }
   2773         BIO_push(fbio, sbio);
   2774         BIO_gets(fbio, mbuf, BUFSIZZ);
   2775         /* STARTTLS command requires CAPABILITIES... */
   2776         BIO_printf(fbio, "CAPABILITIES\r\n");
   2777         (void)BIO_flush(fbio);
   2778         BIO_gets(fbio, mbuf, BUFSIZZ);
   2779         /* no point in trying to parse the CAPABILITIES response if there is none */
   2780         if (strstr(mbuf, "101") != NULL) {
   2781             /* wait for multi-line CAPABILITIES response */
   2782             do {
   2783                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
   2784                 if (strstr(mbuf, "STARTTLS"))
   2785                     foundit = 1;
   2786             } while (mbuf_len > 1 && mbuf[0] != '.');
   2787         }
   2788         (void)BIO_flush(fbio);
   2789         BIO_pop(fbio);
   2790         BIO_free(fbio);
   2791         if (!foundit)
   2792             BIO_printf(bio_err,
   2793                 "Didn't find STARTTLS in server response,"
   2794                 " trying anyway...\n");
   2795         BIO_printf(sbio, "STARTTLS\r\n");
   2796         mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
   2797         if (mbuf_len < 0) {
   2798             BIO_printf(bio_err, "BIO_read failed\n");
   2799             goto end;
   2800         }
   2801         mbuf[mbuf_len] = '\0';
   2802         if (strstr(mbuf, "382") == NULL) {
   2803             BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
   2804             goto shut;
   2805         }
   2806     } break;
   2807     case PROTO_SIEVE: {
   2808         int foundit = 0;
   2809         BIO *fbio = BIO_new(BIO_f_buffer());
   2810 
   2811         if (fbio == NULL) {
   2812             BIO_printf(bio_err, "Unable to create BIO\n");
   2813             goto end;
   2814         }
   2815         BIO_push(fbio, sbio);
   2816         /* wait for multi-line response to end from Sieve */
   2817         do {
   2818             mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
   2819             /*
   2820              * According to RFC 5804  1.7, capability
   2821              * is case-insensitive, make it uppercase
   2822              */
   2823             if (mbuf_len > 1 && mbuf[0] == '"') {
   2824                 make_uppercase(mbuf);
   2825                 if (HAS_PREFIX(mbuf, "\"STARTTLS\""))
   2826                     foundit = 1;
   2827             }
   2828         } while (mbuf_len > 1 && mbuf[0] == '"');
   2829         (void)BIO_flush(fbio);
   2830         BIO_pop(fbio);
   2831         BIO_free(fbio);
   2832         if (!foundit)
   2833             BIO_printf(bio_err,
   2834                 "Didn't find STARTTLS in server response,"
   2835                 " trying anyway...\n");
   2836         BIO_printf(sbio, "STARTTLS\r\n");
   2837         mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
   2838         if (mbuf_len < 0) {
   2839             BIO_printf(bio_err, "BIO_read failed\n");
   2840             goto end;
   2841         }
   2842         mbuf[mbuf_len] = '\0';
   2843         if (mbuf_len < 2) {
   2844             BIO_printf(bio_err, "STARTTLS failed: %s", mbuf);
   2845             goto shut;
   2846         }
   2847         /*
   2848          * According to RFC 5804  2.2, response codes are case-
   2849          * insensitive, make it uppercase but preserve the response.
   2850          */
   2851         strncpy(sbuf, mbuf, 2);
   2852         make_uppercase(sbuf);
   2853         if (!HAS_PREFIX(sbuf, "OK")) {
   2854             BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
   2855             goto shut;
   2856         }
   2857     } break;
   2858     case PROTO_LDAP: {
   2859         /* StartTLS Operation according to RFC 4511 */
   2860         static char ldap_tls_genconf[] = "asn1=SEQUENCE:LDAPMessage\n"
   2861                                          "[LDAPMessage]\n"
   2862                                          "messageID=INTEGER:1\n"
   2863                                          "extendedReq=EXPLICIT:23A,IMPLICIT:0C,"
   2864                                          "FORMAT:ASCII,OCT:1.3.6.1.4.1.1466.20037\n";
   2865         long errline = -1;
   2866         char *genstr = NULL;
   2867         int result = -1;
   2868         ASN1_TYPE *atyp = NULL;
   2869         BIO *ldapbio = BIO_new(BIO_s_mem());
   2870         CONF *cnf = NCONF_new(NULL);
   2871 
   2872         if (ldapbio == NULL || cnf == NULL) {
   2873             BIO_free(ldapbio);
   2874             NCONF_free(cnf);
   2875             goto end;
   2876         }
   2877         BIO_puts(ldapbio, ldap_tls_genconf);
   2878         if (NCONF_load_bio(cnf, ldapbio, &errline) <= 0) {
   2879             BIO_free(ldapbio);
   2880             NCONF_free(cnf);
   2881             if (errline <= 0) {
   2882                 BIO_printf(bio_err, "NCONF_load_bio failed\n");
   2883                 goto end;
   2884             } else {
   2885                 BIO_printf(bio_err, "Error on line %ld\n", errline);
   2886                 goto end;
   2887             }
   2888         }
   2889         BIO_free(ldapbio);
   2890         genstr = NCONF_get_string(cnf, "default", "asn1");
   2891         if (genstr == NULL) {
   2892             NCONF_free(cnf);
   2893             BIO_printf(bio_err, "NCONF_get_string failed\n");
   2894             goto end;
   2895         }
   2896         atyp = ASN1_generate_nconf(genstr, cnf);
   2897         if (atyp == NULL || atyp->type != V_ASN1_SEQUENCE) {
   2898             NCONF_free(cnf);
   2899             ASN1_TYPE_free(atyp);
   2900             BIO_printf(bio_err, "ASN1_generate_nconf failed\n");
   2901             goto end;
   2902         }
   2903         NCONF_free(cnf);
   2904 
   2905         /* Send SSLRequest packet */
   2906         BIO_write(sbio, atyp->value.sequence->data,
   2907             atyp->value.sequence->length);
   2908         (void)BIO_flush(sbio);
   2909         ASN1_TYPE_free(atyp);
   2910 
   2911         mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ);
   2912         if (mbuf_len < 0) {
   2913             BIO_printf(bio_err, "BIO_read failed\n");
   2914             goto end;
   2915         }
   2916         result = ldap_ExtendedResponse_parse(mbuf, mbuf_len);
   2917         if (result < 0) {
   2918             BIO_printf(bio_err, "ldap_ExtendedResponse_parse failed\n");
   2919             goto shut;
   2920         } else if (result > 0) {
   2921             BIO_printf(bio_err, "STARTTLS failed, LDAP Result Code: %i\n",
   2922                 result);
   2923             goto shut;
   2924         }
   2925         mbuf_len = 0;
   2926     } break;
   2927     }
   2928 
   2929     if (early_data_file != NULL
   2930         && ((SSL_get0_session(con) != NULL
   2931                 && SSL_SESSION_get_max_early_data(SSL_get0_session(con)) > 0)
   2932             || (psksess != NULL
   2933                 && SSL_SESSION_get_max_early_data(psksess) > 0))) {
   2934         BIO *edfile = BIO_new_file(early_data_file, "r");
   2935         size_t readbytes, writtenbytes;
   2936         int finish = 0;
   2937 
   2938         if (edfile == NULL) {
   2939             BIO_printf(bio_err, "Cannot open early data file\n");
   2940             goto shut;
   2941         }
   2942 
   2943         while (!finish) {
   2944             if (!BIO_read_ex(edfile, cbuf, BUFSIZZ, &readbytes))
   2945                 finish = 1;
   2946 
   2947             while (!SSL_write_early_data(con, cbuf, readbytes, &writtenbytes)) {
   2948                 switch (SSL_get_error(con, 0)) {
   2949                 case SSL_ERROR_WANT_WRITE:
   2950                 case SSL_ERROR_WANT_ASYNC:
   2951                 case SSL_ERROR_WANT_READ:
   2952                     /* Just keep trying - busy waiting */
   2953                     continue;
   2954                 default:
   2955                     BIO_printf(bio_err, "Error writing early data\n");
   2956                     BIO_free(edfile);
   2957                     ERR_print_errors(bio_err);
   2958                     goto shut;
   2959                 }
   2960             }
   2961         }
   2962 
   2963         BIO_free(edfile);
   2964     }
   2965 
   2966     user_data_init(&user_data, con, cbuf, BUFSIZZ, cmdmode);
   2967     for (;;) {
   2968         FD_ZERO(&readfds);
   2969         FD_ZERO(&writefds);
   2970 
   2971         if ((isdtls || isquic)
   2972             && SSL_get_event_timeout(con, &timeout, &is_infinite)
   2973             && !is_infinite)
   2974             timeoutp = &timeout;
   2975         else
   2976             timeoutp = NULL;
   2977 
   2978         if (!SSL_is_init_finished(con) && SSL_total_renegotiations(con) == 0
   2979             && SSL_get_key_update_type(con) == SSL_KEY_UPDATE_NONE) {
   2980             in_init = 1;
   2981             tty_on = 0;
   2982         } else {
   2983             tty_on = 1;
   2984             if (in_init) {
   2985                 in_init = 0;
   2986                 if (c_brief) {
   2987                     BIO_puts(bio_err, "CONNECTION ESTABLISHED\n");
   2988                     print_ssl_summary(con);
   2989                 }
   2990 
   2991                 print_stuff(bio_c_out, con, full_log);
   2992                 if (full_log > 0)
   2993                     full_log--;
   2994 
   2995                 if (starttls_proto) {
   2996                     BIO_write(bio_err, mbuf, mbuf_len);
   2997                     /* We don't need to know any more */
   2998                     if (!reconnect)
   2999                         starttls_proto = PROTO_OFF;
   3000                 }
   3001 
   3002                 if (reconnect) {
   3003                     reconnect--;
   3004                     BIO_printf(bio_c_out,
   3005                         "drop connection and then reconnect\n");
   3006                     do_ssl_shutdown(con);
   3007                     SSL_set_connect_state(con);
   3008                     BIO_closesocket(SSL_get_fd(con));
   3009                     goto re_start;
   3010                 }
   3011             }
   3012         }
   3013 
   3014         if (!write_ssl) {
   3015             do {
   3016                 switch (user_data_process(&user_data, &cbuf_len, &cbuf_off)) {
   3017                 default:
   3018                     BIO_printf(bio_err, "ERROR\n");
   3019                     /* fall through */
   3020                 case USER_DATA_PROCESS_SHUT:
   3021                     ret = 0;
   3022                     goto shut;
   3023 
   3024                 case USER_DATA_PROCESS_RESTART:
   3025                     goto re_start;
   3026 
   3027                 case USER_DATA_PROCESS_NO_DATA:
   3028                     break;
   3029 
   3030                 case USER_DATA_PROCESS_CONTINUE:
   3031                     write_ssl = 1;
   3032                     break;
   3033                 }
   3034             } while (!write_ssl
   3035                 && cbuf_len == 0
   3036                 && user_data_has_data(&user_data));
   3037             if (cbuf_len > 0) {
   3038                 read_tty = 0;
   3039                 timeout.tv_sec = 0;
   3040                 timeout.tv_usec = 0;
   3041             } else {
   3042                 read_tty = 1;
   3043             }
   3044         }
   3045 
   3046         ssl_pending = read_ssl && SSL_has_pending(con);
   3047 
   3048         if (!ssl_pending) {
   3049 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
   3050             if (tty_on) {
   3051                 /*
   3052                  * Note that select() returns when read _would not block_,
   3053                  * and EOF satisfies that.  To avoid a CPU-hogging loop,
   3054                  * set the flag so we exit.
   3055                  */
   3056                 if (read_tty && !at_eof)
   3057                     openssl_fdset(fileno_stdin(), &readfds);
   3058 #if !defined(OPENSSL_SYS_VMS)
   3059                 if (write_tty)
   3060                     openssl_fdset(fileno_stdout(), &writefds);
   3061 #endif
   3062             }
   3063 
   3064             /*
   3065              * Note that for QUIC we never actually check FD_ISSET() for the
   3066              * underlying network fds. We just rely on select waking up when
   3067              * they become readable/writeable and then SSL_handle_events() doing
   3068              * the right thing.
   3069              */
   3070             if ((!isquic && read_ssl)
   3071                 || (isquic && SSL_net_read_desired(con)))
   3072                 openssl_fdset(SSL_get_fd(con), &readfds);
   3073             if ((!isquic && write_ssl)
   3074                 || (isquic && (first_loop || SSL_net_write_desired(con))))
   3075                 openssl_fdset(SSL_get_fd(con), &writefds);
   3076 #else
   3077             if (!tty_on || !write_tty) {
   3078                 if ((!isquic && read_ssl)
   3079                     || (isquic && SSL_net_read_desired(con)))
   3080                     openssl_fdset(SSL_get_fd(con), &readfds);
   3081                 if ((!isquic && write_ssl)
   3082                     || (isquic && (first_loop || SSL_net_write_desired(con))))
   3083                     openssl_fdset(SSL_get_fd(con), &writefds);
   3084             }
   3085 #endif
   3086 
   3087             /*
   3088              * Note: under VMS with SOCKETSHR the second parameter is
   3089              * currently of type (int *) whereas under other systems it is
   3090              * (void *) if you don't have a cast it will choke the compiler:
   3091              * if you do have a cast then you can either go for (int *) or
   3092              * (void *).
   3093              */
   3094 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
   3095             /*
   3096              * Under Windows/DOS we make the assumption that we can always
   3097              * write to the tty: therefore, if we need to write to the tty we
   3098              * just fall through. Otherwise we timeout the select every
   3099              * second and see if there are any keypresses. Note: this is a
   3100              * hack, in a proper Windows application we wouldn't do this.
   3101              */
   3102             i = 0;
   3103             if (!write_tty) {
   3104                 if (read_tty) {
   3105                     tv.tv_sec = 1;
   3106                     tv.tv_usec = 0;
   3107                     i = select(width, (void *)&readfds, (void *)&writefds,
   3108                         NULL, &tv);
   3109                     if (!i && (!has_stdin_waiting() || !read_tty))
   3110                         continue;
   3111                 } else
   3112                     i = select(width, (void *)&readfds, (void *)&writefds,
   3113                         NULL, timeoutp);
   3114             }
   3115 #else
   3116             i = select(width, (void *)&readfds, (void *)&writefds,
   3117                 NULL, timeoutp);
   3118 #endif
   3119             if (i < 0) {
   3120                 BIO_printf(bio_err, "bad select %d\n",
   3121                     get_last_socket_error());
   3122                 goto shut;
   3123             }
   3124         }
   3125 
   3126         if (timeoutp != NULL) {
   3127             SSL_handle_events(con);
   3128             if (isdtls
   3129                 && !FD_ISSET(SSL_get_fd(con), &readfds)
   3130                 && !FD_ISSET(SSL_get_fd(con), &writefds))
   3131                 BIO_printf(bio_err, "TIMEOUT occurred\n");
   3132         }
   3133 
   3134         if (!ssl_pending
   3135             && ((!isquic && FD_ISSET(SSL_get_fd(con), &writefds))
   3136                 || (isquic && (cbuf_len > 0 || first_loop)))) {
   3137             k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len);
   3138             switch (SSL_get_error(con, k)) {
   3139             case SSL_ERROR_NONE:
   3140                 cbuf_off += k;
   3141                 cbuf_len -= k;
   3142                 if (k <= 0)
   3143                     goto end;
   3144                 /* we have done a  write(con,NULL,0); */
   3145                 if (cbuf_len == 0) {
   3146                     read_tty = 1;
   3147                     write_ssl = 0;
   3148                 } else { /* if (cbuf_len > 0) */
   3149 
   3150                     read_tty = 0;
   3151                     write_ssl = 1;
   3152                 }
   3153                 break;
   3154             case SSL_ERROR_WANT_WRITE:
   3155                 BIO_printf(bio_c_out, "write W BLOCK\n");
   3156                 write_ssl = 1;
   3157                 read_tty = 0;
   3158                 break;
   3159             case SSL_ERROR_WANT_ASYNC:
   3160                 BIO_printf(bio_c_out, "write A BLOCK\n");
   3161                 wait_for_async(con);
   3162                 write_ssl = 1;
   3163                 read_tty = 0;
   3164                 break;
   3165             case SSL_ERROR_WANT_READ:
   3166                 BIO_printf(bio_c_out, "write R BLOCK\n");
   3167                 write_tty = 0;
   3168                 read_ssl = 1;
   3169                 write_ssl = 0;
   3170                 break;
   3171             case SSL_ERROR_WANT_X509_LOOKUP:
   3172                 BIO_printf(bio_c_out, "write X BLOCK\n");
   3173                 break;
   3174             case SSL_ERROR_ZERO_RETURN:
   3175                 if (cbuf_len != 0) {
   3176                     BIO_printf(bio_c_out, "shutdown\n");
   3177                     ret = 0;
   3178                     goto shut;
   3179                 } else {
   3180                     read_tty = 1;
   3181                     write_ssl = 0;
   3182                     break;
   3183                 }
   3184 
   3185             case SSL_ERROR_SYSCALL:
   3186                 if ((k != 0) || (cbuf_len != 0)) {
   3187                     int sockerr = get_last_socket_error();
   3188 
   3189                     if (!tfo || sockerr != EISCONN) {
   3190                         BIO_printf(bio_err, "write:errno=%d\n", sockerr);
   3191                         goto shut;
   3192                     }
   3193                 } else {
   3194                     read_tty = 1;
   3195                     write_ssl = 0;
   3196                 }
   3197                 break;
   3198             case SSL_ERROR_WANT_ASYNC_JOB:
   3199                 /* This shouldn't ever happen in s_client - treat as an error */
   3200             case SSL_ERROR_SSL:
   3201                 ERR_print_errors(bio_err);
   3202                 goto shut;
   3203             }
   3204         }
   3205 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VMS)
   3206         /* Assume Windows/DOS/BeOS can always write */
   3207         else if (!ssl_pending && write_tty)
   3208 #else
   3209         else if (!ssl_pending && FD_ISSET(fileno_stdout(), &writefds))
   3210 #endif
   3211         {
   3212 #ifdef CHARSET_EBCDIC
   3213             ascii2ebcdic(&(sbuf[sbuf_off]), &(sbuf[sbuf_off]), sbuf_len);
   3214 #endif
   3215             i = raw_write_stdout(&(sbuf[sbuf_off]), sbuf_len);
   3216 
   3217             if (i <= 0) {
   3218                 BIO_printf(bio_c_out, "DONE\n");
   3219                 ret = 0;
   3220                 goto shut;
   3221             }
   3222 
   3223             sbuf_len -= i;
   3224             sbuf_off += i;
   3225             if (sbuf_len <= 0) {
   3226                 read_ssl = 1;
   3227                 write_tty = 0;
   3228             }
   3229         } else if (ssl_pending
   3230             || (!isquic && FD_ISSET(SSL_get_fd(con), &readfds))) {
   3231 #ifdef RENEG
   3232             {
   3233                 static int iiii;
   3234                 if (++iiii == 52) {
   3235                     SSL_renegotiate(con);
   3236                     iiii = 0;
   3237                 }
   3238             }
   3239 #endif
   3240             k = SSL_read(con, sbuf, BUFSIZZ);
   3241 
   3242             switch (SSL_get_error(con, k)) {
   3243             case SSL_ERROR_NONE:
   3244                 if (k <= 0)
   3245                     goto end;
   3246                 sbuf_off = 0;
   3247                 sbuf_len = k;
   3248 
   3249                 read_ssl = 0;
   3250                 write_tty = 1;
   3251                 break;
   3252             case SSL_ERROR_WANT_ASYNC:
   3253                 BIO_printf(bio_c_out, "read A BLOCK\n");
   3254                 wait_for_async(con);
   3255                 write_tty = 0;
   3256                 read_ssl = 1;
   3257                 if ((read_tty == 0) && (write_ssl == 0))
   3258                     write_ssl = 1;
   3259                 break;
   3260             case SSL_ERROR_WANT_WRITE:
   3261                 BIO_printf(bio_c_out, "read W BLOCK\n");
   3262                 write_ssl = 1;
   3263                 read_tty = 0;
   3264                 break;
   3265             case SSL_ERROR_WANT_READ:
   3266                 BIO_printf(bio_c_out, "read R BLOCK\n");
   3267                 write_tty = 0;
   3268                 read_ssl = 1;
   3269                 if ((read_tty == 0) && (write_ssl == 0))
   3270                     write_ssl = 1;
   3271                 break;
   3272             case SSL_ERROR_WANT_X509_LOOKUP:
   3273                 BIO_printf(bio_c_out, "read X BLOCK\n");
   3274                 break;
   3275             case SSL_ERROR_SYSCALL:
   3276                 ret = get_last_socket_error();
   3277                 if (c_brief)
   3278                     BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n");
   3279                 else
   3280                     BIO_printf(bio_err, "read:errno=%d\n", ret);
   3281                 goto shut;
   3282             case SSL_ERROR_ZERO_RETURN:
   3283                 BIO_printf(bio_c_out, "closed\n");
   3284                 ret = 0;
   3285                 goto shut;
   3286             case SSL_ERROR_WANT_ASYNC_JOB:
   3287                 /* This shouldn't ever happen in s_client. Treat as an error */
   3288             case SSL_ERROR_SSL:
   3289                 ERR_print_errors(bio_err);
   3290                 goto shut;
   3291             }
   3292         }
   3293 
   3294         /* don't wait for client input in the non-interactive mode */
   3295         else if (nointeractive) {
   3296             ret = 0;
   3297             goto shut;
   3298         }
   3299 
   3300 /* OPENSSL_SYS_MSDOS includes OPENSSL_SYS_WINDOWS */
   3301 #if defined(OPENSSL_SYS_MSDOS)
   3302         else if (has_stdin_waiting())
   3303 #else
   3304         else if (FD_ISSET(fileno_stdin(), &readfds))
   3305 #endif
   3306         {
   3307             if (crlf) {
   3308                 int j, lf_num;
   3309 
   3310                 i = raw_read_stdin(cbuf, BUFSIZZ / 2);
   3311                 lf_num = 0;
   3312                 /* both loops are skipped when i <= 0 */
   3313                 for (j = 0; j < i; j++)
   3314                     if (cbuf[j] == '\n')
   3315                         lf_num++;
   3316                 for (j = i - 1; j >= 0; j--) {
   3317                     cbuf[j + lf_num] = cbuf[j];
   3318                     if (cbuf[j] == '\n') {
   3319                         lf_num--;
   3320                         i++;
   3321                         cbuf[j + lf_num] = '\r';
   3322                     }
   3323                 }
   3324                 assert(lf_num == 0);
   3325             } else
   3326                 i = raw_read_stdin(cbuf, BUFSIZZ);
   3327 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
   3328             if (i == 0)
   3329                 at_eof = 1;
   3330 #endif
   3331 
   3332             if (!c_ign_eof && i <= 0) {
   3333                 BIO_printf(bio_err, "DONE\n");
   3334                 ret = 0;
   3335                 goto shut;
   3336             }
   3337 
   3338             if (i > 0 && !user_data_add(&user_data, i)) {
   3339                 ret = 0;
   3340                 goto shut;
   3341             }
   3342             read_tty = 0;
   3343         }
   3344         first_loop = 0;
   3345     }
   3346 
   3347 shut:
   3348     if (in_init)
   3349         print_stuff(bio_c_out, con, full_log);
   3350     do_ssl_shutdown(con);
   3351 
   3352     /*
   3353      * If we ended with an alert being sent, but still with data in the
   3354      * network buffer to be read, then calling BIO_closesocket() will
   3355      * result in a TCP-RST being sent. On some platforms (notably
   3356      * Windows) then this will result in the peer immediately abandoning
   3357      * the connection including any buffered alert data before it has
   3358      * had a chance to be read. Shutting down the sending side first,
   3359      * and then closing the socket sends TCP-FIN first followed by
   3360      * TCP-RST. This seems to allow the peer to read the alert data.
   3361      */
   3362     shutdown(SSL_get_fd(con), 1); /* SHUT_WR */
   3363     /*
   3364      * We just said we have nothing else to say, but it doesn't mean that
   3365      * the other side has nothing. It's even recommended to consume incoming
   3366      * data. [In testing context this ensures that alerts are passed on...]
   3367      */
   3368     timeout.tv_sec = 0;
   3369     timeout.tv_usec = 500000; /* some extreme round-trip */
   3370     do {
   3371         FD_ZERO(&readfds);
   3372         openssl_fdset(sock, &readfds);
   3373     } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0
   3374         && BIO_read(sbio, sbuf, BUFSIZZ) > 0);
   3375 
   3376     BIO_closesocket(SSL_get_fd(con));
   3377 end:
   3378     if (con != NULL) {
   3379         if (prexit != 0)
   3380             print_stuff(bio_c_out, con, 1);
   3381         SSL_free(con);
   3382     }
   3383     SSL_SESSION_free(psksess);
   3384 #if !defined(OPENSSL_NO_NEXTPROTONEG)
   3385     OPENSSL_free(next_proto.data);
   3386 #endif
   3387     SSL_CTX_free(ctx);
   3388     set_keylog_file(NULL, NULL);
   3389     X509_free(cert);
   3390     sk_X509_CRL_pop_free(crls, X509_CRL_free);
   3391     EVP_PKEY_free(key);
   3392     OSSL_STACK_OF_X509_free(chain);
   3393     OPENSSL_free(pass);
   3394 #ifndef OPENSSL_NO_SRP
   3395     OPENSSL_free(srp_arg.srppassin);
   3396 #endif
   3397     OPENSSL_free(sname_alloc);
   3398     BIO_ADDR_free(peer_addr);
   3399     OPENSSL_free(connectstr);
   3400     OPENSSL_free(bindstr);
   3401     OPENSSL_free(bindhost);
   3402     OPENSSL_free(bindport);
   3403     OPENSSL_free(host);
   3404     OPENSSL_free(port);
   3405     OPENSSL_free(thost);
   3406     OPENSSL_free(tport);
   3407     X509_VERIFY_PARAM_free(vpm);
   3408     ssl_excert_free(exc);
   3409     sk_OPENSSL_STRING_free(ssl_args);
   3410     sk_OPENSSL_STRING_free(dane_tlsa_rrset);
   3411     SSL_CONF_CTX_free(cctx);
   3412     OPENSSL_clear_free(cbuf, BUFSIZZ);
   3413     OPENSSL_clear_free(sbuf, BUFSIZZ);
   3414     OPENSSL_clear_free(mbuf, BUFSIZZ);
   3415     clear_free(proxypass);
   3416     release_engine(e);
   3417     BIO_free(bio_c_out);
   3418     bio_c_out = NULL;
   3419     BIO_free(bio_c_msg);
   3420     bio_c_msg = NULL;
   3421     return ret;
   3422 }
   3423 
   3424 static char *ec_curve_name(EVP_PKEY *pkey)
   3425 {
   3426     char *curve = 0;
   3427     size_t namelen;
   3428 
   3429     if (EVP_PKEY_get_group_name(pkey, NULL, 0, &namelen)) {
   3430         curve = OPENSSL_malloc(++namelen);
   3431         if (!EVP_PKEY_get_group_name(pkey, curve, namelen, 0)) {
   3432             OPENSSL_free(curve);
   3433             curve = NULL;
   3434         }
   3435     }
   3436     return (curve);
   3437 }
   3438 
   3439 static void print_cert_key_info(BIO *bio, X509 *cert)
   3440 {
   3441     EVP_PKEY *pkey = X509_get0_pubkey(cert);
   3442     char *curve = NULL;
   3443     const char *keyalg;
   3444 
   3445     if (pkey == NULL)
   3446         return;
   3447     keyalg = EVP_PKEY_get0_type_name(pkey);
   3448     if (keyalg == NULL)
   3449         keyalg = OBJ_nid2ln(EVP_PKEY_get_base_id(pkey));
   3450     if (EVP_PKEY_id(pkey) == EVP_PKEY_EC)
   3451         curve = ec_curve_name(pkey);
   3452     if (curve != NULL)
   3453         BIO_printf(bio, "   a:PKEY: %s, (%s); sigalg: %s\n",
   3454             keyalg, curve,
   3455             OBJ_nid2ln(X509_get_signature_nid(cert)));
   3456     else
   3457         BIO_printf(bio, "   a:PKEY: %s, %d (bit); sigalg: %s\n",
   3458             keyalg, EVP_PKEY_get_bits(pkey),
   3459             OBJ_nid2ln(X509_get_signature_nid(cert)));
   3460     OPENSSL_free(curve);
   3461 }
   3462 
   3463 static void print_stuff(BIO *bio, SSL *s, int full)
   3464 {
   3465     X509 *peer = NULL;
   3466     STACK_OF(X509) *sk;
   3467     const SSL_CIPHER *c;
   3468     int i, istls13 = (SSL_version(s) == TLS1_3_VERSION);
   3469     long verify_result;
   3470 #ifndef OPENSSL_NO_COMP
   3471     const COMP_METHOD *comp, *expansion;
   3472 #endif
   3473     unsigned char *exportedkeymat;
   3474 #ifndef OPENSSL_NO_CT
   3475     const SSL_CTX *ctx = SSL_get_SSL_CTX(s);
   3476 #endif
   3477 
   3478     if (full) {
   3479         int got_a_chain = 0;
   3480 
   3481         sk = SSL_get_peer_cert_chain(s);
   3482         if (sk != NULL) {
   3483             got_a_chain = 1;
   3484 
   3485             BIO_printf(bio, "---\nCertificate chain\n");
   3486             for (i = 0; i < sk_X509_num(sk); i++) {
   3487                 X509 *chain_cert = sk_X509_value(sk, i);
   3488 
   3489                 BIO_printf(bio, "%2d s:", i);
   3490                 X509_NAME_print_ex(bio, X509_get_subject_name(chain_cert), 0, get_nameopt());
   3491                 BIO_puts(bio, "\n");
   3492                 BIO_printf(bio, "   i:");
   3493                 X509_NAME_print_ex(bio, X509_get_issuer_name(chain_cert), 0, get_nameopt());
   3494                 BIO_puts(bio, "\n");
   3495                 print_cert_key_info(bio, chain_cert);
   3496                 BIO_printf(bio, "   v:NotBefore: ");
   3497                 ASN1_TIME_print(bio, X509_get0_notBefore(chain_cert));
   3498                 BIO_printf(bio, "; NotAfter: ");
   3499                 ASN1_TIME_print(bio, X509_get0_notAfter(chain_cert));
   3500                 BIO_puts(bio, "\n");
   3501                 if (c_showcerts)
   3502                     PEM_write_bio_X509(bio, chain_cert);
   3503             }
   3504         }
   3505 
   3506         BIO_printf(bio, "---\n");
   3507         peer = SSL_get0_peer_certificate(s);
   3508         if (peer != NULL) {
   3509             BIO_printf(bio, "Server certificate\n");
   3510 
   3511             /* Redundant if we showed the whole chain */
   3512             if (!(c_showcerts && got_a_chain))
   3513                 PEM_write_bio_X509(bio, peer);
   3514             dump_cert_text(bio, peer);
   3515         } else {
   3516             BIO_printf(bio, "no peer certificate available\n");
   3517         }
   3518 
   3519         /* Only display RPK information if configured */
   3520         if (SSL_get_negotiated_client_cert_type(s) == TLSEXT_cert_type_rpk)
   3521             BIO_printf(bio, "Client-to-server raw public key negotiated\n");
   3522         if (SSL_get_negotiated_server_cert_type(s) == TLSEXT_cert_type_rpk)
   3523             BIO_printf(bio, "Server-to-client raw public key negotiated\n");
   3524         if (enable_server_rpk) {
   3525             EVP_PKEY *peer_rpk = SSL_get0_peer_rpk(s);
   3526 
   3527             if (peer_rpk != NULL) {
   3528                 BIO_printf(bio, "Server raw public key\n");
   3529                 EVP_PKEY_print_public(bio, peer_rpk, 2, NULL);
   3530             } else {
   3531                 BIO_printf(bio, "no peer rpk available\n");
   3532             }
   3533         }
   3534 
   3535         print_ca_names(bio, s);
   3536 
   3537         ssl_print_sigalgs(bio, s);
   3538         ssl_print_tmp_key(bio, s);
   3539 
   3540 #ifndef OPENSSL_NO_CT
   3541         /*
   3542          * When the SSL session is anonymous, or resumed via an abbreviated
   3543          * handshake, no SCTs are provided as part of the handshake.  While in
   3544          * a resumed session SCTs may be present in the session's certificate,
   3545          * no callbacks are invoked to revalidate these, and in any case that
   3546          * set of SCTs may be incomplete.  Thus it makes little sense to
   3547          * attempt to display SCTs from a resumed session's certificate, and of
   3548          * course none are associated with an anonymous peer.
   3549          */
   3550         if (peer != NULL && !SSL_session_reused(s) && SSL_ct_is_enabled(s)) {
   3551             const STACK_OF(SCT) *scts = SSL_get0_peer_scts(s);
   3552             int sct_count = scts != NULL ? sk_SCT_num(scts) : 0;
   3553 
   3554             BIO_printf(bio, "---\nSCTs present (%i)\n", sct_count);
   3555             if (sct_count > 0) {
   3556                 const CTLOG_STORE *log_store = SSL_CTX_get0_ctlog_store(ctx);
   3557 
   3558                 BIO_printf(bio, "---\n");
   3559                 for (i = 0; i < sct_count; ++i) {
   3560                     SCT *sct = sk_SCT_value(scts, i);
   3561 
   3562                     BIO_printf(bio, "SCT validation status: %s\n",
   3563                         SCT_validation_status_string(sct));
   3564                     SCT_print(sct, bio, 0, log_store);
   3565                     if (i < sct_count - 1)
   3566                         BIO_printf(bio, "\n---\n");
   3567                 }
   3568                 BIO_printf(bio, "\n");
   3569             }
   3570         }
   3571 #endif
   3572 
   3573         BIO_printf(bio,
   3574             "---\nSSL handshake has read %ju bytes "
   3575             "and written %ju bytes\n",
   3576             BIO_number_read(SSL_get_rbio(s)),
   3577             BIO_number_written(SSL_get_wbio(s)));
   3578     }
   3579     print_verify_detail(s, bio);
   3580     BIO_printf(bio, (SSL_session_reused(s) ? "---\nReused, " : "---\nNew, "));
   3581     c = SSL_get_current_cipher(s);
   3582     BIO_printf(bio, "%s, Cipher is %s\n",
   3583         SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
   3584     BIO_printf(bio, "Protocol: %s\n", SSL_get_version(s));
   3585     if (peer != NULL) {
   3586         EVP_PKEY *pktmp;
   3587 
   3588         pktmp = X509_get0_pubkey(peer);
   3589         BIO_printf(bio, "Server public key is %d bit\n",
   3590             EVP_PKEY_get_bits(pktmp));
   3591     }
   3592 
   3593     ssl_print_secure_renegotiation_notes(bio, s);
   3594 
   3595 #ifndef OPENSSL_NO_COMP
   3596     comp = SSL_get_current_compression(s);
   3597     expansion = SSL_get_current_expansion(s);
   3598     BIO_printf(bio, "Compression: %s\n",
   3599         comp ? SSL_COMP_get_name(comp) : "NONE");
   3600     BIO_printf(bio, "Expansion: %s\n",
   3601         expansion ? SSL_COMP_get_name(expansion) : "NONE");
   3602 #endif
   3603 #ifndef OPENSSL_NO_KTLS
   3604     if (BIO_get_ktls_send(SSL_get_wbio(s)))
   3605         BIO_printf(bio_err, "Using Kernel TLS for sending\n");
   3606     if (BIO_get_ktls_recv(SSL_get_rbio(s)))
   3607         BIO_printf(bio_err, "Using Kernel TLS for receiving\n");
   3608 #endif
   3609 
   3610     if (OSSL_TRACE_ENABLED(TLS)) {
   3611         /* Print out local port of connection: useful for debugging */
   3612         int sock;
   3613         union BIO_sock_info_u info;
   3614 
   3615         sock = SSL_get_fd(s);
   3616         if ((info.addr = BIO_ADDR_new()) != NULL
   3617             && BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &info)) {
   3618             BIO_printf(bio_c_out, "LOCAL PORT is %u\n",
   3619                 ntohs(BIO_ADDR_rawport(info.addr)));
   3620         }
   3621         BIO_ADDR_free(info.addr);
   3622     }
   3623 
   3624 #if !defined(OPENSSL_NO_NEXTPROTONEG)
   3625     if (next_proto.status != -1) {
   3626         const unsigned char *proto;
   3627         unsigned int proto_len;
   3628         SSL_get0_next_proto_negotiated(s, &proto, &proto_len);
   3629         BIO_printf(bio, "Next protocol: (%d) ", next_proto.status);
   3630         BIO_write(bio, proto, proto_len);
   3631         BIO_write(bio, "\n", 1);
   3632     }
   3633 #endif
   3634     {
   3635         const unsigned char *proto;
   3636         unsigned int proto_len;
   3637         SSL_get0_alpn_selected(s, &proto, &proto_len);
   3638         if (proto_len > 0) {
   3639             BIO_printf(bio, "ALPN protocol: ");
   3640             BIO_write(bio, proto, proto_len);
   3641             BIO_write(bio, "\n", 1);
   3642         } else
   3643             BIO_printf(bio, "No ALPN negotiated\n");
   3644     }
   3645 
   3646 #ifndef OPENSSL_NO_SRTP
   3647     {
   3648         SRTP_PROTECTION_PROFILE *srtp_profile = SSL_get_selected_srtp_profile(s);
   3649 
   3650         if (srtp_profile)
   3651             BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n",
   3652                 srtp_profile->name);
   3653     }
   3654 #endif
   3655 
   3656     if (istls13) {
   3657         switch (SSL_get_early_data_status(s)) {
   3658         case SSL_EARLY_DATA_NOT_SENT:
   3659             BIO_printf(bio, "Early data was not sent\n");
   3660             break;
   3661 
   3662         case SSL_EARLY_DATA_REJECTED:
   3663             BIO_printf(bio, "Early data was rejected\n");
   3664             break;
   3665 
   3666         case SSL_EARLY_DATA_ACCEPTED:
   3667             BIO_printf(bio, "Early data was accepted\n");
   3668             break;
   3669         }
   3670 
   3671         /*
   3672          * We also print the verify results when we dump session information,
   3673          * but in TLSv1.3 we may not get that right away (or at all) depending
   3674          * on when we get a NewSessionTicket. Therefore, we print it now as well.
   3675          */
   3676         verify_result = SSL_get_verify_result(s);
   3677         BIO_printf(bio, "Verify return code: %ld (%s)\n", verify_result,
   3678             X509_verify_cert_error_string(verify_result));
   3679     } else {
   3680         /* In TLSv1.3 we do this on arrival of a NewSessionTicket */
   3681         SSL_SESSION_print(bio, SSL_get_session(s));
   3682     }
   3683 
   3684     if (SSL_get_session(s) != NULL && keymatexportlabel != NULL) {
   3685         BIO_printf(bio, "Keying material exporter:\n");
   3686         BIO_printf(bio, "    Label: '%s'\n", keymatexportlabel);
   3687         BIO_printf(bio, "    Length: %i bytes\n", keymatexportlen);
   3688         exportedkeymat = app_malloc(keymatexportlen, "export key");
   3689         if (SSL_export_keying_material(s, exportedkeymat,
   3690                 keymatexportlen,
   3691                 keymatexportlabel,
   3692                 strlen(keymatexportlabel),
   3693                 NULL, 0, 0)
   3694             <= 0) {
   3695             BIO_printf(bio, "    Error\n");
   3696         } else {
   3697             BIO_printf(bio, "    Keying material: ");
   3698             for (i = 0; i < keymatexportlen; i++)
   3699                 BIO_printf(bio, "%02X", exportedkeymat[i]);
   3700             BIO_printf(bio, "\n");
   3701         }
   3702         OPENSSL_free(exportedkeymat);
   3703     }
   3704     BIO_printf(bio, "---\n");
   3705     /* flush, or debugging output gets mixed with http response */
   3706     (void)BIO_flush(bio);
   3707 }
   3708 
   3709 #ifndef OPENSSL_NO_OCSP
   3710 static int ocsp_resp_cb(SSL *s, void *arg)
   3711 {
   3712     const unsigned char *p;
   3713     int len;
   3714     OCSP_RESPONSE *rsp;
   3715     len = SSL_get_tlsext_status_ocsp_resp(s, &p);
   3716     BIO_puts(arg, "OCSP response: ");
   3717     if (p == NULL) {
   3718         BIO_puts(arg, "no response sent\n");
   3719         return 1;
   3720     }
   3721     rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
   3722     if (rsp == NULL) {
   3723         BIO_puts(arg, "response parse error\n");
   3724         BIO_dump_indent(arg, (char *)p, len, 4);
   3725         return 0;
   3726     }
   3727     BIO_puts(arg, "\n======================================\n");
   3728     OCSP_RESPONSE_print(arg, rsp, 0);
   3729     BIO_puts(arg, "======================================\n");
   3730     OCSP_RESPONSE_free(rsp);
   3731     return 1;
   3732 }
   3733 #endif
   3734 
   3735 static int ldap_ExtendedResponse_parse(const char *buf, long rem)
   3736 {
   3737     const unsigned char *cur, *end;
   3738     long len;
   3739     int tag, xclass, inf, ret = -1;
   3740 
   3741     cur = (const unsigned char *)buf;
   3742     end = cur + rem;
   3743 
   3744     /*
   3745      * From RFC 4511:
   3746      *
   3747      *    LDAPMessage ::= SEQUENCE {
   3748      *         messageID       MessageID,
   3749      *         protocolOp      CHOICE {
   3750      *              ...
   3751      *              extendedResp          ExtendedResponse,
   3752      *              ... },
   3753      *         controls       [0] Controls OPTIONAL }
   3754      *
   3755      *    ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
   3756      *         COMPONENTS OF LDAPResult,
   3757      *         responseName     [10] LDAPOID OPTIONAL,
   3758      *         responseValue    [11] OCTET STRING OPTIONAL }
   3759      *
   3760      *    LDAPResult ::= SEQUENCE {
   3761      *         resultCode         ENUMERATED {
   3762      *              success                      (0),
   3763      *              ...
   3764      *              other                        (80),
   3765      *              ...  },
   3766      *         matchedDN          LDAPDN,
   3767      *         diagnosticMessage  LDAPString,
   3768      *         referral           [3] Referral OPTIONAL }
   3769      */
   3770 
   3771     /* pull SEQUENCE */
   3772     inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
   3773     if (inf != V_ASN1_CONSTRUCTED || tag != V_ASN1_SEQUENCE || (rem = end - cur, len > rem)) {
   3774         BIO_printf(bio_err, "Unexpected LDAP response\n");
   3775         goto end;
   3776     }
   3777 
   3778     rem = len; /* ensure that we don't overstep the SEQUENCE */
   3779 
   3780     /* pull MessageID */
   3781     inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
   3782     if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_INTEGER || (rem = end - cur, len > rem)) {
   3783         BIO_printf(bio_err, "No MessageID\n");
   3784         goto end;
   3785     }
   3786 
   3787     cur += len; /* shall we check for MessageId match or just skip? */
   3788 
   3789     /* pull [APPLICATION 24] */
   3790     rem = end - cur;
   3791     inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
   3792     if (inf != V_ASN1_CONSTRUCTED || xclass != V_ASN1_APPLICATION || tag != 24) {
   3793         BIO_printf(bio_err, "Not ExtendedResponse\n");
   3794         goto end;
   3795     }
   3796 
   3797     /* pull resultCode */
   3798     rem = end - cur;
   3799     inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem);
   3800     if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_ENUMERATED || len == 0 || (rem = end - cur, len > rem)) {
   3801         BIO_printf(bio_err, "Not LDAPResult\n");
   3802         goto end;
   3803     }
   3804 
   3805     /* len should always be one, but just in case... */
   3806     for (ret = 0, inf = 0; inf < len; inf++) {
   3807         ret <<= 8;
   3808         ret |= cur[inf];
   3809     }
   3810     /* There is more data, but we don't care... */
   3811 end:
   3812     return ret;
   3813 }
   3814 
   3815 /*
   3816  * Host dNS Name verifier: used for checking that the hostname is in dNS format
   3817  * before setting it as SNI
   3818  */
   3819 static int is_dNS_name(const char *host)
   3820 {
   3821     const size_t MAX_LABEL_LENGTH = 63;
   3822     size_t i;
   3823     int isdnsname = 0;
   3824     size_t length = strlen(host);
   3825     size_t label_length = 0;
   3826     int all_numeric = 1;
   3827 
   3828     /*
   3829      * Deviation from strict DNS name syntax, also check names with '_'
   3830      * Check DNS name syntax, any '-' or '.' must be internal,
   3831      * and on either side of each '.' we can't have a '-' or '.'.
   3832      *
   3833      * If the name has just one label, we don't consider it a DNS name.
   3834      */
   3835     for (i = 0; i < length && label_length < MAX_LABEL_LENGTH; ++i) {
   3836         char c = host[i];
   3837 
   3838         if ((c >= 'a' && c <= 'z')
   3839             || (c >= 'A' && c <= 'Z')
   3840             || c == '_') {
   3841             label_length += 1;
   3842             all_numeric = 0;
   3843             continue;
   3844         }
   3845 
   3846         if (c >= '0' && c <= '9') {
   3847             label_length += 1;
   3848             continue;
   3849         }
   3850 
   3851         /* Dot and hyphen cannot be first or last. */
   3852         if (i > 0 && i < length - 1) {
   3853             if (c == '-') {
   3854                 label_length += 1;
   3855                 continue;
   3856             }
   3857             /*
   3858              * Next to a dot the preceding and following characters must not be
   3859              * another dot or a hyphen.  Otherwise, record that the name is
   3860              * plausible, since it has two or more labels.
   3861              */
   3862             if (c == '.'
   3863                 && host[i + 1] != '.'
   3864                 && host[i - 1] != '-'
   3865                 && host[i + 1] != '-') {
   3866                 label_length = 0;
   3867                 isdnsname = 1;
   3868                 continue;
   3869             }
   3870         }
   3871         isdnsname = 0;
   3872         break;
   3873     }
   3874 
   3875     /* dNS name must not be all numeric and labels must be shorter than 64 characters. */
   3876     isdnsname &= !all_numeric && !(label_length == MAX_LABEL_LENGTH);
   3877 
   3878     return isdnsname;
   3879 }
   3880 
   3881 static void user_data_init(struct user_data_st *user_data, SSL *con, char *buf,
   3882     size_t bufmax, int mode)
   3883 {
   3884     user_data->con = con;
   3885     user_data->buf = buf;
   3886     user_data->bufmax = bufmax;
   3887     user_data->buflen = 0;
   3888     user_data->bufoff = 0;
   3889     user_data->mode = mode;
   3890     user_data->isfin = 0;
   3891 }
   3892 
   3893 static int user_data_add(struct user_data_st *user_data, size_t i)
   3894 {
   3895     if (user_data->buflen != 0 || i > user_data->bufmax)
   3896         return 0;
   3897 
   3898     user_data->buflen = i;
   3899     user_data->bufoff = 0;
   3900 
   3901     return 1;
   3902 }
   3903 
   3904 #define USER_COMMAND_HELP 0
   3905 #define USER_COMMAND_QUIT 1
   3906 #define USER_COMMAND_RECONNECT 2
   3907 #define USER_COMMAND_RENEGOTIATE 3
   3908 #define USER_COMMAND_KEY_UPDATE 4
   3909 #define USER_COMMAND_FIN 5
   3910 
   3911 static int user_data_execute(struct user_data_st *user_data, int cmd, char *arg)
   3912 {
   3913     switch (cmd) {
   3914     case USER_COMMAND_HELP:
   3915         /* This only ever occurs in advanced mode, so just emit advanced help */
   3916         BIO_printf(bio_err, "Enter text to send to the peer followed by <enter>\n");
   3917         BIO_printf(bio_err, "To issue a command insert {cmd} or {cmd:arg} anywhere in the text\n");
   3918         BIO_printf(bio_err, "Entering {{ will send { to the peer\n");
   3919         BIO_printf(bio_err, "The following commands are available\n");
   3920         BIO_printf(bio_err, "  {help}: Get this help text\n");
   3921         BIO_printf(bio_err, "  {quit}: Close the connection to the peer\n");
   3922         BIO_printf(bio_err, "  {reconnect}: Reconnect to the peer\n");
   3923         if (SSL_is_quic(user_data->con)) {
   3924             BIO_printf(bio_err, "  {fin}: Send FIN on the stream. No further writing is possible\n");
   3925         } else if (SSL_version(user_data->con) == TLS1_3_VERSION) {
   3926             BIO_printf(bio_err, "  {keyup:req|noreq}: Send a Key Update message\n");
   3927             BIO_printf(bio_err, "                     Arguments:\n");
   3928             BIO_printf(bio_err, "                     req   = peer update requested (default)\n");
   3929             BIO_printf(bio_err, "                     noreq = peer update not requested\n");
   3930         } else {
   3931             BIO_printf(bio_err, "  {reneg}: Attempt to renegotiate\n");
   3932         }
   3933         BIO_printf(bio_err, "\n");
   3934         return USER_DATA_PROCESS_NO_DATA;
   3935 
   3936     case USER_COMMAND_QUIT:
   3937         BIO_printf(bio_err, "DONE\n");
   3938         return USER_DATA_PROCESS_SHUT;
   3939 
   3940     case USER_COMMAND_RECONNECT:
   3941         BIO_printf(bio_err, "RECONNECTING\n");
   3942         do_ssl_shutdown(user_data->con);
   3943         SSL_set_connect_state(user_data->con);
   3944         BIO_closesocket(SSL_get_fd(user_data->con));
   3945         return USER_DATA_PROCESS_RESTART;
   3946 
   3947     case USER_COMMAND_RENEGOTIATE:
   3948         BIO_printf(bio_err, "RENEGOTIATING\n");
   3949         if (!SSL_renegotiate(user_data->con))
   3950             break;
   3951         return USER_DATA_PROCESS_CONTINUE;
   3952 
   3953     case USER_COMMAND_KEY_UPDATE: {
   3954         int updatetype;
   3955 
   3956         if (OPENSSL_strcasecmp(arg, "req") == 0)
   3957             updatetype = SSL_KEY_UPDATE_REQUESTED;
   3958         else if (OPENSSL_strcasecmp(arg, "noreq") == 0)
   3959             updatetype = SSL_KEY_UPDATE_NOT_REQUESTED;
   3960         else
   3961             return USER_DATA_PROCESS_BAD_ARGUMENT;
   3962         BIO_printf(bio_err, "KEYUPDATE\n");
   3963         if (!SSL_key_update(user_data->con, updatetype))
   3964             break;
   3965         return USER_DATA_PROCESS_CONTINUE;
   3966     }
   3967 
   3968     case USER_COMMAND_FIN:
   3969         if (!SSL_stream_conclude(user_data->con, 0))
   3970             break;
   3971         user_data->isfin = 1;
   3972         return USER_DATA_PROCESS_NO_DATA;
   3973 
   3974     default:
   3975         break;
   3976     }
   3977 
   3978     BIO_printf(bio_err, "ERROR\n");
   3979     ERR_print_errors(bio_err);
   3980 
   3981     return USER_DATA_PROCESS_SHUT;
   3982 }
   3983 
   3984 static int user_data_process(struct user_data_st *user_data, size_t *len,
   3985     size_t *off)
   3986 {
   3987     char *buf_start = user_data->buf + user_data->bufoff;
   3988     size_t outlen = user_data->buflen;
   3989 
   3990     if (user_data->buflen == 0) {
   3991         *len = 0;
   3992         *off = 0;
   3993         return USER_DATA_PROCESS_NO_DATA;
   3994     }
   3995 
   3996     if (user_data->mode == USER_DATA_MODE_BASIC) {
   3997         switch (buf_start[0]) {
   3998         case 'Q':
   3999             user_data->buflen = user_data->bufoff = *len = *off = 0;
   4000             return user_data_execute(user_data, USER_COMMAND_QUIT, NULL);
   4001 
   4002         case 'C':
   4003             user_data->buflen = user_data->bufoff = *len = *off = 0;
   4004             return user_data_execute(user_data, USER_COMMAND_RECONNECT, NULL);
   4005 
   4006         case 'R':
   4007             user_data->buflen = user_data->bufoff = *len = *off = 0;
   4008             return user_data_execute(user_data, USER_COMMAND_RENEGOTIATE, NULL);
   4009 
   4010         case 'K':
   4011         case 'k':
   4012             user_data->buflen = user_data->bufoff = *len = *off = 0;
   4013             return user_data_execute(user_data, USER_COMMAND_KEY_UPDATE,
   4014                 buf_start[0] == 'K' ? "req" : "noreq");
   4015         default:
   4016             break;
   4017         }
   4018     } else if (user_data->mode == USER_DATA_MODE_ADVANCED) {
   4019         char *cmd_start = buf_start;
   4020 
   4021         cmd_start[outlen] = '\0';
   4022         for (;;) {
   4023             cmd_start = strchr(cmd_start, '{');
   4024             if (cmd_start == buf_start && *(cmd_start + 1) == '{') {
   4025                 /* The "{" is escaped, so skip it */
   4026                 cmd_start += 2;
   4027                 buf_start++;
   4028                 user_data->bufoff++;
   4029                 user_data->buflen--;
   4030                 outlen--;
   4031                 continue;
   4032             }
   4033             break;
   4034         }
   4035 
   4036         if (cmd_start == buf_start) {
   4037             /* Command detected */
   4038             char *cmd_end = strchr(cmd_start, '}');
   4039             char *arg_start;
   4040             int cmd = -1, ret = USER_DATA_PROCESS_NO_DATA;
   4041             size_t oldoff;
   4042 
   4043             if (cmd_end == NULL) {
   4044                 /* Malformed command */
   4045                 cmd_start[outlen - 1] = '\0';
   4046                 BIO_printf(bio_err,
   4047                     "ERROR PROCESSING COMMAND. REST OF LINE IGNORED: %s\n",
   4048                     cmd_start);
   4049                 user_data->buflen = user_data->bufoff = *len = *off = 0;
   4050                 return USER_DATA_PROCESS_NO_DATA;
   4051             }
   4052             *cmd_end = '\0';
   4053             arg_start = strchr(cmd_start, ':');
   4054             if (arg_start != NULL) {
   4055                 *arg_start = '\0';
   4056                 arg_start++;
   4057             }
   4058             /* Skip over the { */
   4059             cmd_start++;
   4060             /*
   4061              * Now we have cmd_start pointing to a NUL terminated string for
   4062              * the command, and arg_start either being NULL or pointing to a
   4063              * NUL terminated string for the argument.
   4064              */
   4065             if (OPENSSL_strcasecmp(cmd_start, "help") == 0) {
   4066                 cmd = USER_COMMAND_HELP;
   4067             } else if (OPENSSL_strcasecmp(cmd_start, "quit") == 0) {
   4068                 cmd = USER_COMMAND_QUIT;
   4069             } else if (OPENSSL_strcasecmp(cmd_start, "reconnect") == 0) {
   4070                 cmd = USER_COMMAND_RECONNECT;
   4071             } else if (SSL_is_quic(user_data->con)) {
   4072                 if (OPENSSL_strcasecmp(cmd_start, "fin") == 0)
   4073                     cmd = USER_COMMAND_FIN;
   4074             }
   4075             if (SSL_version(user_data->con) == TLS1_3_VERSION) {
   4076                 if (OPENSSL_strcasecmp(cmd_start, "keyup") == 0) {
   4077                     cmd = USER_COMMAND_KEY_UPDATE;
   4078                     if (arg_start == NULL)
   4079                         arg_start = "req";
   4080                 }
   4081             } else {
   4082                 /* (D)TLSv1.2 or below */
   4083                 if (OPENSSL_strcasecmp(cmd_start, "reneg") == 0)
   4084                     cmd = USER_COMMAND_RENEGOTIATE;
   4085             }
   4086             if (cmd == -1) {
   4087                 BIO_printf(bio_err, "UNRECOGNISED COMMAND (IGNORED): %s\n",
   4088                     cmd_start);
   4089             } else {
   4090                 ret = user_data_execute(user_data, cmd, arg_start);
   4091                 if (ret == USER_DATA_PROCESS_BAD_ARGUMENT) {
   4092                     BIO_printf(bio_err, "BAD ARGUMENT (COMMAND IGNORED): %s\n",
   4093                         arg_start);
   4094                     ret = USER_DATA_PROCESS_NO_DATA;
   4095                 }
   4096             }
   4097             oldoff = user_data->bufoff;
   4098             user_data->bufoff = (cmd_end - user_data->buf) + 1;
   4099             user_data->buflen -= user_data->bufoff - oldoff;
   4100             if (user_data->buf + 1 == cmd_start
   4101                 && user_data->buflen == 1
   4102                 && user_data->buf[user_data->bufoff] == '\n') {
   4103                 /*
   4104                  * This command was the only thing on the whole line. We
   4105                  * suppress the final `\n`
   4106                  */
   4107                 user_data->bufoff = 0;
   4108                 user_data->buflen = 0;
   4109             }
   4110             *len = *off = 0;
   4111             return ret;
   4112         } else if (cmd_start != NULL) {
   4113             /*
   4114              * There is a command on this line, but its not at the start. Output
   4115              * the start of the line, and we'll process the command next time
   4116              * we call this function
   4117              */
   4118             outlen = cmd_start - buf_start;
   4119         }
   4120     }
   4121 
   4122     if (user_data->isfin) {
   4123         user_data->buflen = user_data->bufoff = *len = *off = 0;
   4124         return USER_DATA_PROCESS_NO_DATA;
   4125     }
   4126 
   4127 #ifdef CHARSET_EBCDIC
   4128     ebcdic2ascii(buf_start, buf_start, outlen);
   4129 #endif
   4130     *len = outlen;
   4131     *off = user_data->bufoff;
   4132     user_data->buflen -= outlen;
   4133     if (user_data->buflen == 0)
   4134         user_data->bufoff = 0;
   4135     else
   4136         user_data->bufoff += outlen;
   4137     return USER_DATA_PROCESS_CONTINUE;
   4138 }
   4139 
   4140 static int user_data_has_data(struct user_data_st *user_data)
   4141 {
   4142     return user_data->buflen > 0;
   4143 }
   4144 #endif /* OPENSSL_NO_SOCK */
   4145