Add Postgres support to -starttls
[openssl.git] / apps / s_client.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /* ====================================================================
11  * Copyright 2005 Nokia. All rights reserved.
12  *
13  * The portions of the attached software ("Contribution") is developed by
14  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
15  * license.
16  *
17  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
18  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
19  * support (see RFC 4279) to OpenSSL.
20  *
21  * No patent licenses or other rights except those expressly stated in
22  * the OpenSSL open source license shall be deemed granted or received
23  * expressly, by implication, estoppel, or otherwise.
24  *
25  * No assurances are provided by Nokia that the Contribution does not
26  * infringe the patent or other intellectual property rights of any third
27  * party or that the license provides you with all the necessary rights
28  * to make use of the Contribution.
29  *
30  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
31  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
32  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
33  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
34  * OTHERWISE.
35  */
36
37 #include <ctype.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <errno.h>
42 #include <openssl/e_os2.h>
43
44 #ifndef OPENSSL_NO_SOCK
45
46 /*
47  * With IPv6, it looks like Digital has mixed up the proper order of
48  * recursive header file inclusion, resulting in the compiler complaining
49  * that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which is
50  * needed to have fileno() declared correctly...  So let's define u_int
51  */
52 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
53 # define __U_INT
54 typedef unsigned int u_int;
55 #endif
56
57 #define USE_SOCKETS
58 #include "apps.h"
59 #include <openssl/x509.h>
60 #include <openssl/ssl.h>
61 #include <openssl/err.h>
62 #include <openssl/pem.h>
63 #include <openssl/rand.h>
64 #include <openssl/ocsp.h>
65 #include <openssl/bn.h>
66 #include <openssl/async.h>
67 #ifndef OPENSSL_NO_SRP
68 # include <openssl/srp.h>
69 #endif
70 #ifndef OPENSSL_NO_CT
71 # include <openssl/ct.h>
72 #endif
73 #include "s_apps.h"
74 #include "timeouts.h"
75
76 #if defined(__has_feature)
77 # if __has_feature(memory_sanitizer)
78 #  include <sanitizer/msan_interface.h>
79 # endif
80 #endif
81
82 #undef BUFSIZZ
83 #define BUFSIZZ 1024*8
84 #define S_CLIENT_IRC_READ_TIMEOUT 8
85
86 static char *prog;
87 static int c_debug = 0;
88 static int c_showcerts = 0;
89 static char *keymatexportlabel = NULL;
90 static int keymatexportlen = 20;
91 static BIO *bio_c_out = NULL;
92 static int c_quiet = 0;
93
94 static void print_stuff(BIO *berr, SSL *con, int full);
95 #ifndef OPENSSL_NO_OCSP
96 static int ocsp_resp_cb(SSL *s, void *arg);
97 #endif
98
99 static int saved_errno;
100
101 static void save_errno(void)
102 {
103     saved_errno = errno;
104     errno = 0;
105 }
106
107 static int restore_errno(void)
108 {
109     int ret = errno;
110     errno = saved_errno;
111     return ret;
112 }
113
114 static void do_ssl_shutdown(SSL *ssl)
115 {
116     int ret;
117
118     do {
119         /* We only do unidirectional shutdown */
120         ret = SSL_shutdown(ssl);
121         if (ret < 0) {
122             switch (SSL_get_error(ssl, ret)) {
123             case SSL_ERROR_WANT_READ:
124             case SSL_ERROR_WANT_WRITE:
125             case SSL_ERROR_WANT_ASYNC:
126             case SSL_ERROR_WANT_ASYNC_JOB:
127                 /* We just do busy waiting. Nothing clever */
128                 continue;
129             }
130             ret = 0;
131         }
132     } while (ret < 0);
133 }
134
135 #ifndef OPENSSL_NO_PSK
136 /* Default PSK identity and key */
137 static char *psk_identity = "Client_identity";
138 /*
139  * char *psk_key=NULL; by default PSK is not used
140  */
141
142 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity,
143                                   unsigned int max_identity_len,
144                                   unsigned char *psk,
145                                   unsigned int max_psk_len)
146 {
147     int ret;
148     long key_len;
149     unsigned char *key;
150
151     if (c_debug)
152         BIO_printf(bio_c_out, "psk_client_cb\n");
153     if (!hint) {
154         /* no ServerKeyExchange message */
155         if (c_debug)
156             BIO_printf(bio_c_out,
157                        "NULL received PSK identity hint, continuing anyway\n");
158     } else if (c_debug)
159         BIO_printf(bio_c_out, "Received PSK identity hint '%s'\n", hint);
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 (key_len > 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 /* This is a context that we pass to callbacks */
201 typedef struct tlsextctx_st {
202     BIO *biodebug;
203     int ack;
204 } tlsextctx;
205
206 static int ssl_servername_cb(SSL *s, int *ad, void *arg)
207 {
208     tlsextctx *p = (tlsextctx *) arg;
209     const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
210     if (SSL_get_servername_type(s) != -1)
211         p->ack = !SSL_session_reused(s) && hn != NULL;
212     else
213         BIO_printf(bio_err, "Can't use SSL_get_servername\n");
214
215     return SSL_TLSEXT_ERR_OK;
216 }
217
218 #ifndef OPENSSL_NO_SRP
219
220 /* This is a context that we pass to all callbacks */
221 typedef struct srp_arg_st {
222     char *srppassin;
223     char *srplogin;
224     int msg;                    /* copy from c_msg */
225     int debug;                  /* copy from c_debug */
226     int amp;                    /* allow more groups */
227     int strength;               /* minimal size for N */
228 } SRP_ARG;
229
230 # define SRP_NUMBER_ITERATIONS_FOR_PRIME 64
231
232 static int srp_Verify_N_and_g(const BIGNUM *N, const BIGNUM *g)
233 {
234     BN_CTX *bn_ctx = BN_CTX_new();
235     BIGNUM *p = BN_new();
236     BIGNUM *r = BN_new();
237     int ret =
238         g != NULL && N != NULL && bn_ctx != NULL && BN_is_odd(N) &&
239         BN_is_prime_ex(N, SRP_NUMBER_ITERATIONS_FOR_PRIME, bn_ctx, NULL) == 1 &&
240         p != NULL && BN_rshift1(p, N) &&
241         /* p = (N-1)/2 */
242         BN_is_prime_ex(p, SRP_NUMBER_ITERATIONS_FOR_PRIME, bn_ctx, NULL) == 1 &&
243         r != NULL &&
244         /* verify g^((N-1)/2) == -1 (mod N) */
245         BN_mod_exp(r, g, p, N, bn_ctx) &&
246         BN_add_word(r, 1) && BN_cmp(r, N) == 0;
247
248     BN_free(r);
249     BN_free(p);
250     BN_CTX_free(bn_ctx);
251     return ret;
252 }
253
254 /*-
255  * This callback is used here for two purposes:
256  * - extended debugging
257  * - making some primality tests for unknown groups
258  * The callback is only called for a non default group.
259  *
260  * An application does not need the call back at all if
261  * only the standard groups are used.  In real life situations,
262  * client and server already share well known groups,
263  * thus there is no need to verify them.
264  * Furthermore, in case that a server actually proposes a group that
265  * is not one of those defined in RFC 5054, it is more appropriate
266  * to add the group to a static list and then compare since
267  * primality tests are rather cpu consuming.
268  */
269
270 static int ssl_srp_verify_param_cb(SSL *s, void *arg)
271 {
272     SRP_ARG *srp_arg = (SRP_ARG *)arg;
273     BIGNUM *N = NULL, *g = NULL;
274
275     if (((N = SSL_get_srp_N(s)) == NULL) || ((g = SSL_get_srp_g(s)) == NULL))
276         return 0;
277     if (srp_arg->debug || srp_arg->msg || srp_arg->amp == 1) {
278         BIO_printf(bio_err, "SRP parameters:\n");
279         BIO_printf(bio_err, "\tN=");
280         BN_print(bio_err, N);
281         BIO_printf(bio_err, "\n\tg=");
282         BN_print(bio_err, g);
283         BIO_printf(bio_err, "\n");
284     }
285
286     if (SRP_check_known_gN_param(g, N))
287         return 1;
288
289     if (srp_arg->amp == 1) {
290         if (srp_arg->debug)
291             BIO_printf(bio_err,
292                        "SRP param N and g are not known params, going to check deeper.\n");
293
294         /*
295          * The srp_moregroups is a real debugging feature. Implementors
296          * should rather add the value to the known ones. The minimal size
297          * has already been tested.
298          */
299         if (BN_num_bits(g) <= BN_BITS && srp_Verify_N_and_g(N, g))
300             return 1;
301     }
302     BIO_printf(bio_err, "SRP param N and g rejected.\n");
303     return 0;
304 }
305
306 # define PWD_STRLEN 1024
307
308 static char *ssl_give_srp_client_pwd_cb(SSL *s, void *arg)
309 {
310     SRP_ARG *srp_arg = (SRP_ARG *)arg;
311     char *pass = app_malloc(PWD_STRLEN + 1, "SRP password buffer");
312     PW_CB_DATA cb_tmp;
313     int l;
314
315     cb_tmp.password = (char *)srp_arg->srppassin;
316     cb_tmp.prompt_info = "SRP user";
317     if ((l = password_callback(pass, PWD_STRLEN, 0, &cb_tmp)) < 0) {
318         BIO_printf(bio_err, "Can't read Password\n");
319         OPENSSL_free(pass);
320         return NULL;
321     }
322     *(pass + l) = '\0';
323
324     return pass;
325 }
326
327 #endif
328
329 static char *srtp_profiles = NULL;
330
331 #ifndef OPENSSL_NO_NEXTPROTONEG
332 /* This the context that we pass to next_proto_cb */
333 typedef struct tlsextnextprotoctx_st {
334     unsigned char *data;
335     size_t len;
336     int status;
337 } tlsextnextprotoctx;
338
339 static tlsextnextprotoctx next_proto;
340
341 static int next_proto_cb(SSL *s, unsigned char **out, unsigned char *outlen,
342                          const unsigned char *in, unsigned int inlen,
343                          void *arg)
344 {
345     tlsextnextprotoctx *ctx = arg;
346
347     if (!c_quiet) {
348         /* We can assume that |in| is syntactically valid. */
349         unsigned i;
350         BIO_printf(bio_c_out, "Protocols advertised by server: ");
351         for (i = 0; i < inlen;) {
352             if (i)
353                 BIO_write(bio_c_out, ", ", 2);
354             BIO_write(bio_c_out, &in[i + 1], in[i]);
355             i += in[i] + 1;
356         }
357         BIO_write(bio_c_out, "\n", 1);
358     }
359
360     ctx->status =
361         SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len);
362     return SSL_TLSEXT_ERR_OK;
363 }
364 #endif                         /* ndef OPENSSL_NO_NEXTPROTONEG */
365
366 static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type,
367                                    const unsigned char *in, size_t inlen,
368                                    int *al, void *arg)
369 {
370     char pem_name[100];
371     unsigned char ext_buf[4 + 65536];
372
373     /* Reconstruct the type/len fields prior to extension data */
374     ext_buf[0] = ext_type >> 8;
375     ext_buf[1] = ext_type & 0xFF;
376     ext_buf[2] = inlen >> 8;
377     ext_buf[3] = inlen & 0xFF;
378     memcpy(ext_buf + 4, in, inlen);
379
380     BIO_snprintf(pem_name, sizeof(pem_name), "SERVERINFO FOR EXTENSION %d",
381                  ext_type);
382     PEM_write_bio(bio_c_out, pem_name, "", ext_buf, 4 + inlen);
383     return 1;
384 }
385
386 /*
387  * Hex decoder that tolerates optional whitespace.  Returns number of bytes
388  * produced, advances inptr to end of input string.
389  */
390 static ossl_ssize_t hexdecode(const char **inptr, void *result)
391 {
392     unsigned char **out = (unsigned char **)result;
393     const char *in = *inptr;
394     unsigned char *ret = app_malloc(strlen(in) / 2, "hexdecode");
395     unsigned char *cp = ret;
396     uint8_t byte;
397     int nibble = 0;
398
399     if (ret == NULL)
400         return -1;
401
402     for (byte = 0; *in; ++in) {
403         int x;
404
405         if (isspace(_UC(*in)))
406             continue;
407         x = OPENSSL_hexchar2int(*in);
408         if (x < 0) {
409             OPENSSL_free(ret);
410             return 0;
411         }
412         byte |= (char)x;
413         if ((nibble ^= 1) == 0) {
414             *cp++ = byte;
415             byte = 0;
416         } else {
417             byte <<= 4;
418         }
419     }
420     if (nibble != 0) {
421         OPENSSL_free(ret);
422         return 0;
423     }
424     *inptr = in;
425
426     return cp - (*out = ret);
427 }
428
429 /*
430  * Decode unsigned 0..255, returns 1 on success, <= 0 on failure. Advances
431  * inptr to next field skipping leading whitespace.
432  */
433 static ossl_ssize_t checked_uint8(const char **inptr, void *out)
434 {
435     uint8_t *result = (uint8_t *)out;
436     const char *in = *inptr;
437     char *endp;
438     long v;
439     int e;
440
441     save_errno();
442     v = strtol(in, &endp, 10);
443     e = restore_errno();
444
445     if (((v == LONG_MIN || v == LONG_MAX) && e == ERANGE) ||
446         endp == in || !isspace(_UC(*endp)) ||
447         v != (*result = (uint8_t) v)) {
448         return -1;
449     }
450     for (in = endp; isspace(_UC(*in)); ++in)
451         continue;
452
453     *inptr = in;
454     return 1;
455 }
456
457 struct tlsa_field {
458     void *var;
459     const char *name;
460     ossl_ssize_t (*parser)(const char **, void *);
461 };
462
463 static int tlsa_import_rr(SSL *con, const char *rrdata)
464 {
465     /* Not necessary to re-init these values; the "parsers" do that. */
466     static uint8_t usage;
467     static uint8_t selector;
468     static uint8_t mtype;
469     static unsigned char *data;
470     static struct tlsa_field tlsa_fields[] = {
471         { &usage, "usage", checked_uint8 },
472         { &selector, "selector", checked_uint8 },
473         { &mtype, "mtype", checked_uint8 },
474         { &data, "data", hexdecode },
475         { NULL, }
476     };
477     struct tlsa_field *f;
478     int ret;
479     const char *cp = rrdata;
480     ossl_ssize_t len = 0;
481
482     for (f = tlsa_fields; f->var; ++f) {
483         /* Returns number of bytes produced, advances cp to next field */
484         if ((len = f->parser(&cp, f->var)) <= 0) {
485             BIO_printf(bio_err, "%s: warning: bad TLSA %s field in: %s\n",
486                        prog, f->name, rrdata);
487             return 0;
488         }
489     }
490     /* The data field is last, so len is its length */
491     ret = SSL_dane_tlsa_add(con, usage, selector, mtype, data, len);
492     OPENSSL_free(data);
493
494     if (ret == 0) {
495         ERR_print_errors(bio_err);
496         BIO_printf(bio_err, "%s: warning: unusable TLSA rrdata: %s\n",
497                    prog, rrdata);
498         return 0;
499     }
500     if (ret < 0) {
501         ERR_print_errors(bio_err);
502         BIO_printf(bio_err, "%s: warning: error loading TLSA rrdata: %s\n",
503                    prog, rrdata);
504         return 0;
505     }
506     return ret;
507 }
508
509 static int tlsa_import_rrset(SSL *con, STACK_OF(OPENSSL_STRING) *rrset)
510 {
511     int num = sk_OPENSSL_STRING_num(rrset);
512     int count = 0;
513     int i;
514
515     for (i = 0; i < num; ++i) {
516         char *rrdata = sk_OPENSSL_STRING_value(rrset, i);
517         if (tlsa_import_rr(con, rrdata) > 0)
518             ++count;
519     }
520     return count > 0;
521 }
522
523 typedef enum OPTION_choice {
524     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
525     OPT_4, OPT_6, OPT_HOST, OPT_PORT, OPT_CONNECT, OPT_UNIX,
526     OPT_XMPPHOST, OPT_VERIFY,
527     OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SESS_OUT, OPT_SESS_IN,
528     OPT_CERTFORM, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET,
529     OPT_BRIEF, OPT_PREXIT, OPT_CRLF, OPT_QUIET, OPT_NBIO,
530     OPT_SSL_CLIENT_ENGINE, OPT_RAND, OPT_IGN_EOF, OPT_NO_IGN_EOF,
531     OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_WDEBUG,
532     OPT_MSG, OPT_MSGFILE, OPT_ENGINE, OPT_TRACE, OPT_SECURITY_DEBUG,
533     OPT_SECURITY_DEBUG_VERBOSE, OPT_SHOWCERTS, OPT_NBIO_TEST, OPT_STATE,
534 #ifndef OPENSSL_NO_PSK
535     OPT_PSK_IDENTITY, OPT_PSK,
536 #endif
537 #ifndef OPENSSL_NO_SRP
538     OPT_SRPUSER, OPT_SRPPASS, OPT_SRP_STRENGTH, OPT_SRP_LATEUSER,
539     OPT_SRP_MOREGROUPS,
540 #endif
541     OPT_SSL3, OPT_SSL_CONFIG,
542     OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1,
543     OPT_DTLS1_2, OPT_TIMEOUT, OPT_MTU, OPT_KEYFORM, OPT_PASS,
544     OPT_CERT_CHAIN, OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH,
545         OPT_VERIFYCAPATH,
546     OPT_KEY, OPT_RECONNECT, OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE,
547     OPT_CHAINCAFILE, OPT_VERIFYCAFILE, OPT_NEXTPROTONEG, OPT_ALPN,
548     OPT_SERVERINFO, OPT_STARTTLS, OPT_SERVERNAME,
549     OPT_USE_SRTP, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_SMTPHOST,
550     OPT_ASYNC, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF,
551     OPT_V_ENUM,
552     OPT_X_ENUM,
553     OPT_S_ENUM,
554     OPT_FALLBACKSCSV, OPT_NOCMDS, OPT_PROXY, OPT_DANE_TLSA_DOMAIN,
555 #ifndef OPENSSL_NO_CT
556     OPT_CT, OPT_NOCT, OPT_CTLOG_FILE,
557 #endif
558     OPT_DANE_TLSA_RRDATA, OPT_DANE_EE_NO_NAME
559 } OPTION_CHOICE;
560
561 const OPTIONS s_client_options[] = {
562     {"help", OPT_HELP, '-', "Display this summary"},
563     {"host", OPT_HOST, 's', "Use -connect instead"},
564     {"port", OPT_PORT, 'p', "Use -connect instead"},
565     {"connect", OPT_CONNECT, 's',
566      "TCP/IP where to connect (default is :" PORT ")"},
567     {"proxy", OPT_PROXY, 's',
568      "Connect to via specified proxy to the real server"},
569 #ifdef AF_UNIX
570     {"unix", OPT_UNIX, 's', "Connect over unix domain sockets"},
571 #endif
572     {"4", OPT_4, '-', "Use IPv4 only"},
573 #ifdef AF_INET6
574     {"6", OPT_6, '-', "Use IPv6 only"},
575 #endif
576     {"verify", OPT_VERIFY, 'p', "Turn on peer certificate verification"},
577     {"cert", OPT_CERT, '<', "Certificate file to use, PEM format assumed"},
578     {"certform", OPT_CERTFORM, 'F',
579      "Certificate format (PEM or DER) PEM default"},
580     {"key", OPT_KEY, 's', "Private key file to use, if not in -cert file"},
581     {"keyform", OPT_KEYFORM, 'E', "Key format (PEM, DER or engine) PEM default"},
582     {"pass", OPT_PASS, 's', "Private key file pass phrase source"},
583     {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"},
584     {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"},
585     {"no-CAfile", OPT_NOCAFILE, '-',
586      "Do not load the default certificates file"},
587     {"no-CApath", OPT_NOCAPATH, '-',
588      "Do not load certificates from the default certificates directory"},
589     {"dane_tlsa_domain", OPT_DANE_TLSA_DOMAIN, 's', "DANE TLSA base domain"},
590     {"dane_tlsa_rrdata", OPT_DANE_TLSA_RRDATA, 's',
591      "DANE TLSA rrdata presentation form"},
592     {"dane_ee_no_namechecks", OPT_DANE_EE_NO_NAME, '-',
593      "Disable name checks when matching DANE-EE(3) TLSA records"},
594     {"reconnect", OPT_RECONNECT, '-',
595      "Drop and re-make the connection with the same Session-ID"},
596     {"showcerts", OPT_SHOWCERTS, '-', "Show all certificates in the chain"},
597     {"debug", OPT_DEBUG, '-', "Extra output"},
598     {"msg", OPT_MSG, '-', "Show protocol messages"},
599     {"msgfile", OPT_MSGFILE, '>',
600      "File to send output of -msg or -trace, instead of stdout"},
601     {"nbio_test", OPT_NBIO_TEST, '-', "More ssl protocol testing"},
602     {"state", OPT_STATE, '-', "Print the ssl states"},
603     {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"},
604     {"quiet", OPT_QUIET, '-', "No s_client output"},
605     {"ign_eof", OPT_IGN_EOF, '-', "Ignore input eof (default when -quiet)"},
606     {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Don't ignore input eof"},
607     {"starttls", OPT_STARTTLS, 's',
608      "Use the appropriate STARTTLS command before starting TLS"},
609     {"xmpphost", OPT_XMPPHOST, 's',
610      "Host to use with \"-starttls xmpp[-server]\""},
611     {"rand", OPT_RAND, 's',
612      "Load the file(s) into the random number generator"},
613     {"sess_out", OPT_SESS_OUT, '>', "File to write SSL session to"},
614     {"sess_in", OPT_SESS_IN, '<', "File to read SSL session from"},
615     {"use_srtp", OPT_USE_SRTP, 's',
616      "Offer SRTP key management with a colon-separated profile list"},
617     {"keymatexport", OPT_KEYMATEXPORT, 's',
618      "Export keying material using label"},
619     {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p',
620      "Export len bytes of keying material (default 20)"},
621     {"fallback_scsv", OPT_FALLBACKSCSV, '-', "Send the fallback SCSV"},
622     {"name", OPT_SMTPHOST, 's', "Hostname to use for \"-starttls smtp\""},
623     {"CRL", OPT_CRL, '<', "CRL file to use"},
624     {"crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRL from distribution points"},
625     {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER) PEM is default"},
626     {"verify_return_error", OPT_VERIFY_RET_ERROR, '-',
627      "Close connection on verification error"},
628     {"verify_quiet", OPT_VERIFY_QUIET, '-', "Restrict verify output to errors"},
629     {"brief", OPT_BRIEF, '-',
630      "Restrict output to brief summary of connection parameters"},
631     {"prexit", OPT_PREXIT, '-',
632      "Print session information when the program exits"},
633     {"security_debug", OPT_SECURITY_DEBUG, '-',
634      "Enable security debug messages"},
635     {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-',
636      "Output more security debug output"},
637     {"cert_chain", OPT_CERT_CHAIN, '<',
638      "Certificate chain file (in PEM format)"},
639     {"chainCApath", OPT_CHAINCAPATH, '/',
640      "Use dir as certificate store path to build CA certificate chain"},
641     {"verifyCApath", OPT_VERIFYCAPATH, '/',
642      "Use dir as certificate store path to verify CA certificate"},
643     {"build_chain", OPT_BUILD_CHAIN, '-', "Build certificate chain"},
644     {"chainCAfile", OPT_CHAINCAFILE, '<',
645      "CA file for certificate chain (PEM format)"},
646     {"verifyCAfile", OPT_VERIFYCAFILE, '<',
647      "CA file for certificate verification (PEM format)"},
648     {"nocommands", OPT_NOCMDS, '-', "Do not use interactive command letters"},
649     {"servername", OPT_SERVERNAME, 's',
650      "Set TLS extension servername in ClientHello"},
651     {"tlsextdebug", OPT_TLSEXTDEBUG, '-',
652      "Hex dump of all TLS extensions received"},
653 #ifndef OPENSSL_NO_OCSP
654     {"status", OPT_STATUS, '-', "Request certificate status from server"},
655 #endif
656     {"serverinfo", OPT_SERVERINFO, 's',
657      "types  Send empty ClientHello extensions (comma-separated numbers)"},
658     {"alpn", OPT_ALPN, 's',
659      "Enable ALPN extension, considering named protocols supported (comma-separated list)"},
660     {"async", OPT_ASYNC, '-', "Support asynchronous operation"},
661     {"ssl_config", OPT_SSL_CONFIG, 's', "Use specified configuration file"},
662     {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'n',
663      "Size used to split data for encrypt pipelines"},
664     {"max_pipelines", OPT_MAX_PIPELINES, 'n',
665      "Maximum number of encrypt/decrypt pipelines to be used"},
666     {"read_buf", OPT_READ_BUF, 'n',
667      "Default read buffer size to be used for connections"},
668     OPT_S_OPTIONS,
669     OPT_V_OPTIONS,
670     OPT_X_OPTIONS,
671 #ifndef OPENSSL_NO_SSL3
672     {"ssl3", OPT_SSL3, '-', "Just use SSLv3"},
673 #endif
674 #ifndef OPENSSL_NO_TLS1
675     {"tls1", OPT_TLS1, '-', "Just use TLSv1"},
676 #endif
677 #ifndef OPENSSL_NO_TLS1_1
678     {"tls1_1", OPT_TLS1_1, '-', "Just use TLSv1.1"},
679 #endif
680 #ifndef OPENSSL_NO_TLS1_2
681     {"tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2"},
682 #endif
683 #ifndef OPENSSL_NO_DTLS
684     {"dtls", OPT_DTLS, '-', "Use any version of DTLS"},
685     {"timeout", OPT_TIMEOUT, '-',
686      "Enable send/receive timeout on DTLS connections"},
687     {"mtu", OPT_MTU, 'p', "Set the link layer MTU"},
688 #endif
689 #ifndef OPENSSL_NO_DTLS1
690     {"dtls1", OPT_DTLS1, '-', "Just use DTLSv1"},
691 #endif
692 #ifndef OPENSSL_NO_DTLS1_2
693     {"dtls1_2", OPT_DTLS1_2, '-', "Just use DTLSv1.2"},
694 #endif
695 #ifndef OPENSSL_NO_SSL_TRACE
696     {"trace", OPT_TRACE, '-', "Show trace output of protocol messages"},
697 #endif
698 #ifdef WATT32
699     {"wdebug", OPT_WDEBUG, '-', "WATT-32 tcp debugging"},
700 #endif
701     {"nbio", OPT_NBIO, '-', "Use non-blocking IO"},
702 #ifndef OPENSSL_NO_PSK
703     {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity"},
704     {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"},
705 #endif
706 #ifndef OPENSSL_NO_SRP
707     {"srpuser", OPT_SRPUSER, 's', "SRP authentication for 'user'"},
708     {"srppass", OPT_SRPPASS, 's', "Password for 'user'"},
709     {"srp_lateuser", OPT_SRP_LATEUSER, '-',
710      "SRP username into second ClientHello message"},
711     {"srp_moregroups", OPT_SRP_MOREGROUPS, '-',
712      "Tolerate other than the known g N values."},
713     {"srp_strength", OPT_SRP_STRENGTH, 'p', "Minimal length in bits for N"},
714 #endif
715 #ifndef OPENSSL_NO_NEXTPROTONEG
716     {"nextprotoneg", OPT_NEXTPROTONEG, 's',
717      "Enable NPN extension, considering named protocols supported (comma-separated list)"},
718 #endif
719 #ifndef OPENSSL_NO_ENGINE
720     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
721     {"ssl_client_engine", OPT_SSL_CLIENT_ENGINE, 's',
722      "Specify engine to be used for client certificate operations"},
723 #endif
724 #ifndef OPENSSL_NO_CT
725     {"ct", OPT_CT, '-', "Request and parse SCTs (also enables OCSP stapling)"},
726     {"noct", OPT_NOCT, '-', "Do not request or parse SCTs (default)"},
727     {"ctlogfile", OPT_CTLOG_FILE, '<', "CT log list CONF file"},
728 #endif
729     {NULL, OPT_EOF, 0x00, NULL}
730 };
731
732 typedef enum PROTOCOL_choice {
733     PROTO_OFF,
734     PROTO_SMTP,
735     PROTO_POP3,
736     PROTO_IMAP,
737     PROTO_FTP,
738     PROTO_TELNET,
739     PROTO_XMPP,
740     PROTO_XMPP_SERVER,
741     PROTO_CONNECT,
742     PROTO_IRC,
743     PROTO_POSTGRES
744 } PROTOCOL_CHOICE;
745
746 static const OPT_PAIR services[] = {
747     {"smtp", PROTO_SMTP},
748     {"pop3", PROTO_POP3},
749     {"imap", PROTO_IMAP},
750     {"ftp", PROTO_FTP},
751     {"xmpp", PROTO_XMPP},
752     {"xmpp-server", PROTO_XMPP_SERVER},
753     {"telnet", PROTO_TELNET},
754     {"irc", PROTO_IRC},
755     {"postgres", PROTO_POSTGRES},
756     {NULL, 0}
757 };
758
759 #define IS_INET_FLAG(o) \
760  (o == OPT_4 || o == OPT_6 || o == OPT_HOST || o == OPT_PORT || o == OPT_CONNECT)
761 #define IS_UNIX_FLAG(o) (o == OPT_UNIX)
762
763 #define IS_PROT_FLAG(o) \
764  (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \
765   || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2)
766
767 /* Free |*dest| and optionally set it to a copy of |source|. */
768 static void freeandcopy(char **dest, const char *source)
769 {
770     OPENSSL_free(*dest);
771     *dest = NULL;
772     if (source != NULL)
773         *dest = OPENSSL_strdup(source);
774 }
775
776 int s_client_main(int argc, char **argv)
777 {
778     BIO *sbio;
779     EVP_PKEY *key = NULL;
780     SSL *con = NULL;
781     SSL_CTX *ctx = NULL;
782     STACK_OF(X509) *chain = NULL;
783     X509 *cert = NULL;
784     X509_VERIFY_PARAM *vpm = NULL;
785     SSL_EXCERT *exc = NULL;
786     SSL_CONF_CTX *cctx = NULL;
787     STACK_OF(OPENSSL_STRING) *ssl_args = NULL;
788     char *dane_tlsa_domain = NULL;
789     STACK_OF(OPENSSL_STRING) *dane_tlsa_rrset = NULL;
790     int dane_ee_no_name = 0;
791     STACK_OF(X509_CRL) *crls = NULL;
792     const SSL_METHOD *meth = TLS_client_method();
793     const char *CApath = NULL, *CAfile = NULL;
794     char *cbuf = NULL, *sbuf = NULL;
795     char *mbuf = NULL, *proxystr = NULL, *connectstr = NULL;
796     char *cert_file = NULL, *key_file = NULL, *chain_file = NULL;
797     char *chCApath = NULL, *chCAfile = NULL, *host = NULL;
798     char *port = OPENSSL_strdup(PORT);
799     char *inrand = NULL;
800     char *passarg = NULL, *pass = NULL, *vfyCApath = NULL, *vfyCAfile = NULL;
801     char *sess_in = NULL, *sess_out = NULL, *crl_file = NULL, *p;
802     char *xmpphost = NULL;
803     const char *ehlo = "mail.example.com";
804     struct timeval timeout, *timeoutp;
805     fd_set readfds, writefds;
806     int noCApath = 0, noCAfile = 0;
807     int build_chain = 0, cbuf_len, cbuf_off, cert_format = FORMAT_PEM;
808     int key_format = FORMAT_PEM, crlf = 0, full_log = 1, mbuf_len = 0;
809     int prexit = 0;
810     int sdebug = 0;
811     int reconnect = 0, verify = SSL_VERIFY_NONE, vpmtouched = 0;
812     int ret = 1, in_init = 1, i, nbio_test = 0, s = -1, k, width, state = 0;
813     int sbuf_len, sbuf_off, cmdletters = 1;
814     int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM;
815     int starttls_proto = PROTO_OFF, crl_format = FORMAT_PEM, crl_download = 0;
816     int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending;
817 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
818     int at_eof = 0;
819 #endif
820     int read_buf_len = 0;
821     int fallback_scsv = 0;
822     long randamt = 0;
823     OPTION_CHOICE o;
824 #ifndef OPENSSL_NO_DTLS
825     int enable_timeouts = 0;
826     long socket_mtu = 0;
827 #endif
828 #ifndef OPENSSL_NO_ENGINE
829     ENGINE *ssl_client_engine = NULL;
830 #endif
831     ENGINE *e = NULL;
832 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
833     struct timeval tv;
834 #endif
835     char *servername = NULL;
836     const char *alpn_in = NULL;
837     tlsextctx tlsextcbp = { NULL, 0 };
838     const char *ssl_config = NULL;
839 #define MAX_SI_TYPES 100
840     unsigned short serverinfo_types[MAX_SI_TYPES];
841     int serverinfo_count = 0, start = 0, len;
842 #ifndef OPENSSL_NO_NEXTPROTONEG
843     const char *next_proto_neg_in = NULL;
844 #endif
845 #ifndef OPENSSL_NO_SRP
846     char *srppass = NULL;
847     int srp_lateuser = 0;
848     SRP_ARG srp_arg = { NULL, NULL, 0, 0, 0, 1024 };
849 #endif
850 #ifndef OPENSSL_NO_CT
851     char *ctlog_file = NULL;
852     int ct_validation = 0;
853 #endif
854     int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0;
855     int async = 0;
856     unsigned int split_send_fragment = 0;
857     unsigned int max_pipelines = 0;
858     enum { use_inet, use_unix, use_unknown } connect_type = use_unknown;
859     int count4or6 = 0;
860     int c_nbio = 0, c_msg = 0, c_ign_eof = 0, c_brief = 0;
861     int c_tlsextdebug = 0;
862 #ifndef OPENSSL_NO_OCSP
863     int c_status_req = 0;
864 #endif
865     BIO *bio_c_msg = NULL;
866
867     FD_ZERO(&readfds);
868     FD_ZERO(&writefds);
869 /* Known false-positive of MemorySanitizer. */
870 #if defined(__has_feature)
871 # if __has_feature(memory_sanitizer)
872     __msan_unpoison(&readfds, sizeof(readfds));
873     __msan_unpoison(&writefds, sizeof(writefds));
874 # endif
875 #endif
876
877     prog = opt_progname(argv[0]);
878     c_quiet = 0;
879     c_debug = 0;
880     c_showcerts = 0;
881     c_nbio = 0;
882     vpm = X509_VERIFY_PARAM_new();
883     cctx = SSL_CONF_CTX_new();
884
885     if (vpm == NULL || cctx == NULL) {
886         BIO_printf(bio_err, "%s: out of memory\n", prog);
887         goto end;
888     }
889
890     cbuf = app_malloc(BUFSIZZ, "cbuf");
891     sbuf = app_malloc(BUFSIZZ, "sbuf");
892     mbuf = app_malloc(BUFSIZZ, "mbuf");
893
894     SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT | SSL_CONF_FLAG_CMDLINE);
895
896     prog = opt_init(argc, argv, s_client_options);
897     while ((o = opt_next()) != OPT_EOF) {
898         /* Check for intermixing flags. */
899         if (connect_type == use_unix && IS_INET_FLAG(o)) {
900             BIO_printf(bio_err,
901                        "%s: Intermixed protocol flags (unix and internet domains)\n",
902                        prog);
903             goto end;
904         }
905         if (connect_type == use_inet && IS_UNIX_FLAG(o)) {
906             BIO_printf(bio_err,
907                        "%s: Intermixed protocol flags (internet and unix domains)\n",
908                        prog);
909             goto end;
910         }
911
912         if (IS_PROT_FLAG(o) && ++prot_opt > 1) {
913             BIO_printf(bio_err, "Cannot supply multiple protocol flags\n");
914             goto end;
915         }
916         if (IS_NO_PROT_FLAG(o))
917             no_prot_opt++;
918         if (prot_opt == 1 && no_prot_opt) {
919             BIO_printf(bio_err,
920                        "Cannot supply both a protocol flag and '-no_<prot>'\n");
921             goto end;
922         }
923
924         switch (o) {
925         case OPT_EOF:
926         case OPT_ERR:
927  opthelp:
928             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
929             goto end;
930         case OPT_HELP:
931             opt_help(s_client_options);
932             ret = 0;
933             goto end;
934         case OPT_4:
935             connect_type = use_inet;
936             socket_family = AF_INET;
937             count4or6++;
938             break;
939 #ifdef AF_INET6
940         case OPT_6:
941             connect_type = use_inet;
942             socket_family = AF_INET6;
943             count4or6++;
944             break;
945 #endif
946         case OPT_HOST:
947             connect_type = use_inet;
948             freeandcopy(&host, opt_arg());
949             break;
950         case OPT_PORT:
951             connect_type = use_inet;
952             freeandcopy(&port, opt_arg());
953             break;
954         case OPT_CONNECT:
955             connect_type = use_inet;
956             freeandcopy(&connectstr, opt_arg());
957             break;
958         case OPT_PROXY:
959             proxystr = opt_arg();
960             starttls_proto = PROTO_CONNECT;
961             break;
962 #ifdef AF_UNIX
963         case OPT_UNIX:
964             connect_type = use_unix;
965             socket_family = AF_UNIX;
966             freeandcopy(&host, opt_arg());
967             break;
968 #endif
969         case OPT_XMPPHOST:
970             xmpphost = opt_arg();
971             break;
972         case OPT_SMTPHOST:
973             ehlo = opt_arg();
974             break;
975         case OPT_VERIFY:
976             verify = SSL_VERIFY_PEER;
977             verify_args.depth = atoi(opt_arg());
978             if (!c_quiet)
979                 BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth);
980             break;
981         case OPT_CERT:
982             cert_file = opt_arg();
983             break;
984         case OPT_CRL:
985             crl_file = opt_arg();
986             break;
987         case OPT_CRL_DOWNLOAD:
988             crl_download = 1;
989             break;
990         case OPT_SESS_OUT:
991             sess_out = opt_arg();
992             break;
993         case OPT_SESS_IN:
994             sess_in = opt_arg();
995             break;
996         case OPT_CERTFORM:
997             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &cert_format))
998                 goto opthelp;
999             break;
1000         case OPT_CRLFORM:
1001             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format))
1002                 goto opthelp;
1003             break;
1004         case OPT_VERIFY_RET_ERROR:
1005             verify_args.return_error = 1;
1006             break;
1007         case OPT_VERIFY_QUIET:
1008             verify_args.quiet = 1;
1009             break;
1010         case OPT_BRIEF:
1011             c_brief = verify_args.quiet = c_quiet = 1;
1012             break;
1013         case OPT_S_CASES:
1014             if (ssl_args == NULL)
1015                 ssl_args = sk_OPENSSL_STRING_new_null();
1016             if (ssl_args == NULL
1017                 || !sk_OPENSSL_STRING_push(ssl_args, opt_flag())
1018                 || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) {
1019                 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1020                 goto end;
1021             }
1022             break;
1023         case OPT_V_CASES:
1024             if (!opt_verify(o, vpm))
1025                 goto end;
1026             vpmtouched++;
1027             break;
1028         case OPT_X_CASES:
1029             if (!args_excert(o, &exc))
1030                 goto end;
1031             break;
1032         case OPT_PREXIT:
1033             prexit = 1;
1034             break;
1035         case OPT_CRLF:
1036             crlf = 1;
1037             break;
1038         case OPT_QUIET:
1039             c_quiet = c_ign_eof = 1;
1040             break;
1041         case OPT_NBIO:
1042             c_nbio = 1;
1043             break;
1044         case OPT_NOCMDS:
1045             cmdletters = 0;
1046             break;
1047         case OPT_ENGINE:
1048             e = setup_engine(opt_arg(), 1);
1049             break;
1050         case OPT_SSL_CLIENT_ENGINE:
1051 #ifndef OPENSSL_NO_ENGINE
1052             ssl_client_engine = ENGINE_by_id(opt_arg());
1053             if (ssl_client_engine == NULL) {
1054                 BIO_printf(bio_err, "Error getting client auth engine\n");
1055                 goto opthelp;
1056             }
1057 #endif
1058             break;
1059         case OPT_RAND:
1060             inrand = opt_arg();
1061             break;
1062         case OPT_IGN_EOF:
1063             c_ign_eof = 1;
1064             break;
1065         case OPT_NO_IGN_EOF:
1066             c_ign_eof = 0;
1067             break;
1068         case OPT_DEBUG:
1069             c_debug = 1;
1070             break;
1071         case OPT_TLSEXTDEBUG:
1072             c_tlsextdebug = 1;
1073             break;
1074         case OPT_STATUS:
1075 #ifndef OPENSSL_NO_OCSP
1076             c_status_req = 1;
1077 #endif
1078             break;
1079         case OPT_WDEBUG:
1080 #ifdef WATT32
1081             dbug_init();
1082 #endif
1083             break;
1084         case OPT_MSG:
1085             c_msg = 1;
1086             break;
1087         case OPT_MSGFILE:
1088             bio_c_msg = BIO_new_file(opt_arg(), "w");
1089             break;
1090         case OPT_TRACE:
1091 #ifndef OPENSSL_NO_SSL_TRACE
1092             c_msg = 2;
1093 #endif
1094             break;
1095         case OPT_SECURITY_DEBUG:
1096             sdebug = 1;
1097             break;
1098         case OPT_SECURITY_DEBUG_VERBOSE:
1099             sdebug = 2;
1100             break;
1101         case OPT_SHOWCERTS:
1102             c_showcerts = 1;
1103             break;
1104         case OPT_NBIO_TEST:
1105             nbio_test = 1;
1106             break;
1107         case OPT_STATE:
1108             state = 1;
1109             break;
1110 #ifndef OPENSSL_NO_PSK
1111         case OPT_PSK_IDENTITY:
1112             psk_identity = opt_arg();
1113             break;
1114         case OPT_PSK:
1115             for (p = psk_key = opt_arg(); *p; p++) {
1116                 if (isxdigit(_UC(*p)))
1117                     continue;
1118                 BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key);
1119                 goto end;
1120             }
1121             break;
1122 #endif
1123 #ifndef OPENSSL_NO_SRP
1124         case OPT_SRPUSER:
1125             srp_arg.srplogin = opt_arg();
1126             if (min_version < TLS1_VERSION)
1127                 min_version = TLS1_VERSION;
1128             break;
1129         case OPT_SRPPASS:
1130             srppass = opt_arg();
1131             if (min_version < TLS1_VERSION)
1132                 min_version = TLS1_VERSION;
1133             break;
1134         case OPT_SRP_STRENGTH:
1135             srp_arg.strength = atoi(opt_arg());
1136             BIO_printf(bio_err, "SRP minimal length for N is %d\n",
1137                        srp_arg.strength);
1138             if (min_version < TLS1_VERSION)
1139                 min_version = TLS1_VERSION;
1140             break;
1141         case OPT_SRP_LATEUSER:
1142             srp_lateuser = 1;
1143             if (min_version < TLS1_VERSION)
1144                 min_version = TLS1_VERSION;
1145             break;
1146         case OPT_SRP_MOREGROUPS:
1147             srp_arg.amp = 1;
1148             if (min_version < TLS1_VERSION)
1149                 min_version = TLS1_VERSION;
1150             break;
1151 #endif
1152         case OPT_SSL_CONFIG:
1153             ssl_config = opt_arg();
1154             break;
1155         case OPT_SSL3:
1156             min_version = SSL3_VERSION;
1157             max_version = SSL3_VERSION;
1158             break;
1159         case OPT_TLS1_2:
1160             min_version = TLS1_2_VERSION;
1161             max_version = TLS1_2_VERSION;
1162             break;
1163         case OPT_TLS1_1:
1164             min_version = TLS1_1_VERSION;
1165             max_version = TLS1_1_VERSION;
1166             break;
1167         case OPT_TLS1:
1168             min_version = TLS1_VERSION;
1169             max_version = TLS1_VERSION;
1170             break;
1171         case OPT_DTLS:
1172 #ifndef OPENSSL_NO_DTLS
1173             meth = DTLS_client_method();
1174             socket_type = SOCK_DGRAM;
1175 #endif
1176             break;
1177         case OPT_DTLS1:
1178 #ifndef OPENSSL_NO_DTLS1
1179             meth = DTLS_client_method();
1180             min_version = DTLS1_VERSION;
1181             max_version = DTLS1_VERSION;
1182             socket_type = SOCK_DGRAM;
1183 #endif
1184             break;
1185         case OPT_DTLS1_2:
1186 #ifndef OPENSSL_NO_DTLS1_2
1187             meth = DTLS_client_method();
1188             min_version = DTLS1_2_VERSION;
1189             max_version = DTLS1_2_VERSION;
1190             socket_type = SOCK_DGRAM;
1191 #endif
1192             break;
1193         case OPT_TIMEOUT:
1194 #ifndef OPENSSL_NO_DTLS
1195             enable_timeouts = 1;
1196 #endif
1197             break;
1198         case OPT_MTU:
1199 #ifndef OPENSSL_NO_DTLS
1200             socket_mtu = atol(opt_arg());
1201 #endif
1202             break;
1203         case OPT_FALLBACKSCSV:
1204             fallback_scsv = 1;
1205             break;
1206         case OPT_KEYFORM:
1207             if (!opt_format(opt_arg(), OPT_FMT_PDE, &key_format))
1208                 goto opthelp;
1209             break;
1210         case OPT_PASS:
1211             passarg = opt_arg();
1212             break;
1213         case OPT_CERT_CHAIN:
1214             chain_file = opt_arg();
1215             break;
1216         case OPT_KEY:
1217             key_file = opt_arg();
1218             break;
1219         case OPT_RECONNECT:
1220             reconnect = 5;
1221             break;
1222         case OPT_CAPATH:
1223             CApath = opt_arg();
1224             break;
1225         case OPT_NOCAPATH:
1226             noCApath = 1;
1227             break;
1228         case OPT_CHAINCAPATH:
1229             chCApath = opt_arg();
1230             break;
1231         case OPT_VERIFYCAPATH:
1232             vfyCApath = opt_arg();
1233             break;
1234         case OPT_BUILD_CHAIN:
1235             build_chain = 1;
1236             break;
1237         case OPT_CAFILE:
1238             CAfile = opt_arg();
1239             break;
1240         case OPT_NOCAFILE:
1241             noCAfile = 1;
1242             break;
1243 #ifndef OPENSSL_NO_CT
1244         case OPT_NOCT:
1245             ct_validation = 0;
1246             break;
1247         case OPT_CT:
1248             ct_validation = 1;
1249             break;
1250         case OPT_CTLOG_FILE:
1251             ctlog_file = opt_arg();
1252             break;
1253 #endif
1254         case OPT_CHAINCAFILE:
1255             chCAfile = opt_arg();
1256             break;
1257         case OPT_VERIFYCAFILE:
1258             vfyCAfile = opt_arg();
1259             break;
1260         case OPT_DANE_TLSA_DOMAIN:
1261             dane_tlsa_domain = opt_arg();
1262             break;
1263         case OPT_DANE_TLSA_RRDATA:
1264             if (dane_tlsa_rrset == NULL)
1265                 dane_tlsa_rrset = sk_OPENSSL_STRING_new_null();
1266             if (dane_tlsa_rrset == NULL ||
1267                 !sk_OPENSSL_STRING_push(dane_tlsa_rrset, opt_arg())) {
1268                 BIO_printf(bio_err, "%s: Memory allocation failure\n", prog);
1269                 goto end;
1270             }
1271             break;
1272         case OPT_DANE_EE_NO_NAME:
1273             dane_ee_no_name = 1;
1274             break;
1275         case OPT_NEXTPROTONEG:
1276 #ifndef OPENSSL_NO_NEXTPROTONEG
1277             next_proto_neg_in = opt_arg();
1278 #endif
1279             break;
1280         case OPT_ALPN:
1281             alpn_in = opt_arg();
1282             break;
1283         case OPT_SERVERINFO:
1284             p = opt_arg();
1285             len = strlen(p);
1286             for (start = 0, i = 0; i <= len; ++i) {
1287                 if (i == len || p[i] == ',') {
1288                     serverinfo_types[serverinfo_count] = atoi(p + start);
1289                     if (++serverinfo_count == MAX_SI_TYPES)
1290                         break;
1291                     start = i + 1;
1292                 }
1293             }
1294             break;
1295         case OPT_STARTTLS:
1296             if (!opt_pair(opt_arg(), services, &starttls_proto))
1297                 goto end;
1298             break;
1299         case OPT_SERVERNAME:
1300             servername = opt_arg();
1301             break;
1302         case OPT_USE_SRTP:
1303             srtp_profiles = opt_arg();
1304             break;
1305         case OPT_KEYMATEXPORT:
1306             keymatexportlabel = opt_arg();
1307             break;
1308         case OPT_KEYMATEXPORTLEN:
1309             keymatexportlen = atoi(opt_arg());
1310             break;
1311         case OPT_ASYNC:
1312             async = 1;
1313             break;
1314         case OPT_SPLIT_SEND_FRAG:
1315             split_send_fragment = atoi(opt_arg());
1316             if (split_send_fragment == 0) {
1317                 /*
1318                  * Not allowed - set to a deliberately bad value so we get an
1319                  * error message below
1320                  */
1321                 split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH + 1;
1322             }
1323             break;
1324         case OPT_MAX_PIPELINES:
1325             max_pipelines = atoi(opt_arg());
1326             break;
1327         case OPT_READ_BUF:
1328             read_buf_len = atoi(opt_arg());
1329             break;
1330         }
1331     }
1332     if (count4or6 >= 2) {
1333         BIO_printf(bio_err, "%s: Can't use both -4 and -6\n", prog);
1334         goto opthelp;
1335     }
1336     argc = opt_num_rest();
1337     if (argc != 0)
1338         goto opthelp;
1339
1340     if (proxystr) {
1341         int res;
1342         char *tmp_host = host, *tmp_port = port;
1343         if (connectstr == NULL) {
1344             BIO_printf(bio_err, "%s: -proxy requires use of -connect\n", prog);
1345             goto opthelp;
1346         }
1347         res = BIO_parse_hostserv(proxystr, &host, &port, BIO_PARSE_PRIO_HOST);
1348         if (tmp_host != host)
1349             OPENSSL_free(tmp_host);
1350         if (tmp_port != port)
1351             OPENSSL_free(tmp_port);
1352         if (!res) {
1353             BIO_printf(bio_err,
1354                        "%s: -proxy argument malformed or ambiguous\n", prog);
1355             goto end;
1356         }
1357     } else {
1358         int res = 1;
1359         char *tmp_host = host, *tmp_port = port;
1360         if (connectstr != NULL)
1361             res = BIO_parse_hostserv(connectstr, &host, &port,
1362                                      BIO_PARSE_PRIO_HOST);
1363         if (tmp_host != host)
1364             OPENSSL_free(tmp_host);
1365         if (tmp_port != port)
1366             OPENSSL_free(tmp_port);
1367         if (!res) {
1368             BIO_printf(bio_err,
1369                        "%s: -connect argument malformed or ambiguous\n",
1370                        prog);
1371             goto end;
1372         }
1373     }
1374
1375     if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) {
1376         BIO_printf(bio_err,
1377                    "Can't use unix sockets and datagrams together\n");
1378         goto end;
1379     }
1380
1381     if (split_send_fragment > SSL3_RT_MAX_PLAIN_LENGTH) {
1382         BIO_printf(bio_err, "Bad split send fragment size\n");
1383         goto end;
1384     }
1385
1386     if (max_pipelines > SSL_MAX_PIPELINES) {
1387         BIO_printf(bio_err, "Bad max pipelines value\n");
1388         goto end;
1389     }
1390
1391 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1392     next_proto.status = -1;
1393     if (next_proto_neg_in) {
1394         next_proto.data =
1395             next_protos_parse(&next_proto.len, next_proto_neg_in);
1396         if (next_proto.data == NULL) {
1397             BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n");
1398             goto end;
1399         }
1400     } else
1401         next_proto.data = NULL;
1402 #endif
1403
1404     if (!app_passwd(passarg, NULL, &pass, NULL)) {
1405         BIO_printf(bio_err, "Error getting password\n");
1406         goto end;
1407     }
1408
1409     if (key_file == NULL)
1410         key_file = cert_file;
1411
1412     if (key_file) {
1413         key = load_key(key_file, key_format, 0, pass, e,
1414                        "client certificate private key file");
1415         if (key == NULL) {
1416             ERR_print_errors(bio_err);
1417             goto end;
1418         }
1419     }
1420
1421     if (cert_file) {
1422         cert = load_cert(cert_file, cert_format, "client certificate file");
1423         if (cert == NULL) {
1424             ERR_print_errors(bio_err);
1425             goto end;
1426         }
1427     }
1428
1429     if (chain_file) {
1430         if (!load_certs(chain_file, &chain, FORMAT_PEM, NULL,
1431                         "client certificate chain"))
1432             goto end;
1433     }
1434
1435     if (crl_file) {
1436         X509_CRL *crl;
1437         crl = load_crl(crl_file, crl_format);
1438         if (crl == NULL) {
1439             BIO_puts(bio_err, "Error loading CRL\n");
1440             ERR_print_errors(bio_err);
1441             goto end;
1442         }
1443         crls = sk_X509_CRL_new_null();
1444         if (crls == NULL || !sk_X509_CRL_push(crls, crl)) {
1445             BIO_puts(bio_err, "Error adding CRL\n");
1446             ERR_print_errors(bio_err);
1447             X509_CRL_free(crl);
1448             goto end;
1449         }
1450     }
1451
1452     if (!load_excert(&exc))
1453         goto end;
1454
1455     if (!app_RAND_load_file(NULL, 1) && inrand == NULL
1456         && !RAND_status()) {
1457         BIO_printf(bio_err,
1458                    "warning, not much extra random data, consider using the -rand option\n");
1459     }
1460     if (inrand != NULL) {
1461         randamt = app_RAND_load_files(inrand);
1462         BIO_printf(bio_err, "%ld semi-random bytes loaded\n", randamt);
1463     }
1464
1465     if (bio_c_out == NULL) {
1466         if (c_quiet && !c_debug) {
1467             bio_c_out = BIO_new(BIO_s_null());
1468             if (c_msg && !bio_c_msg)
1469                 bio_c_msg = dup_bio_out(FORMAT_TEXT);
1470         } else if (bio_c_out == NULL)
1471             bio_c_out = dup_bio_out(FORMAT_TEXT);
1472     }
1473 #ifndef OPENSSL_NO_SRP
1474     if (!app_passwd(srppass, NULL, &srp_arg.srppassin, NULL)) {
1475         BIO_printf(bio_err, "Error getting password\n");
1476         goto end;
1477     }
1478 #endif
1479
1480     ctx = SSL_CTX_new(meth);
1481     if (ctx == NULL) {
1482         ERR_print_errors(bio_err);
1483         goto end;
1484     }
1485
1486     if (sdebug)
1487         ssl_ctx_security_debug(ctx, sdebug);
1488
1489     if (ssl_config) {
1490         if (SSL_CTX_config(ctx, ssl_config) == 0) {
1491             BIO_printf(bio_err, "Error using configuration \"%s\"\n",
1492                        ssl_config);
1493             ERR_print_errors(bio_err);
1494             goto end;
1495         }
1496     }
1497
1498     if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0)
1499         goto end;
1500     if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0)
1501         goto end;
1502
1503     if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) {
1504         BIO_printf(bio_err, "Error setting verify params\n");
1505         ERR_print_errors(bio_err);
1506         goto end;
1507     }
1508
1509     if (async) {
1510         SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC);
1511     }
1512     if (split_send_fragment > 0) {
1513         SSL_CTX_set_split_send_fragment(ctx, split_send_fragment);
1514     }
1515     if (max_pipelines > 0) {
1516         SSL_CTX_set_max_pipelines(ctx, max_pipelines);
1517     }
1518
1519     if (read_buf_len > 0) {
1520         SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len);
1521     }
1522
1523     if (!config_ctx(cctx, ssl_args, ctx))
1524         goto end;
1525
1526     if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile,
1527                          crls, crl_download)) {
1528         BIO_printf(bio_err, "Error loading store locations\n");
1529         ERR_print_errors(bio_err);
1530         goto end;
1531     }
1532 #ifndef OPENSSL_NO_ENGINE
1533     if (ssl_client_engine) {
1534         if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) {
1535             BIO_puts(bio_err, "Error setting client auth engine\n");
1536             ERR_print_errors(bio_err);
1537             ENGINE_free(ssl_client_engine);
1538             goto end;
1539         }
1540         ENGINE_free(ssl_client_engine);
1541     }
1542 #endif
1543
1544 #ifndef OPENSSL_NO_PSK
1545     if (psk_key != NULL) {
1546         if (c_debug)
1547             BIO_printf(bio_c_out, "PSK key given, setting client callback\n");
1548         SSL_CTX_set_psk_client_callback(ctx, psk_client_cb);
1549     }
1550 #endif
1551 #ifndef OPENSSL_NO_SRTP
1552     if (srtp_profiles != NULL) {
1553         /* Returns 0 on success! */
1554         if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) {
1555             BIO_printf(bio_err, "Error setting SRTP profile\n");
1556             ERR_print_errors(bio_err);
1557             goto end;
1558         }
1559     }
1560 #endif
1561
1562     if (exc)
1563         ssl_ctx_set_excert(ctx, exc);
1564
1565 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1566     if (next_proto.data)
1567         SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto);
1568 #endif
1569     if (alpn_in) {
1570         size_t alpn_len;
1571         unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in);
1572
1573         if (alpn == NULL) {
1574             BIO_printf(bio_err, "Error parsing -alpn argument\n");
1575             goto end;
1576         }
1577         /* Returns 0 on success! */
1578         if (SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len) != 0) {
1579             BIO_printf(bio_err, "Error setting ALPN\n");
1580             goto end;
1581         }
1582         OPENSSL_free(alpn);
1583     }
1584
1585     for (i = 0; i < serverinfo_count; i++) {
1586         if (!SSL_CTX_add_client_custom_ext(ctx,
1587                                            serverinfo_types[i],
1588                                            NULL, NULL, NULL,
1589                                            serverinfo_cli_parse_cb, NULL)) {
1590             BIO_printf(bio_err,
1591                        "Warning: Unable to add custom extension %u, skipping\n",
1592                        serverinfo_types[i]);
1593         }
1594     }
1595
1596     if (state)
1597         SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback);
1598
1599 #ifndef OPENSSL_NO_CT
1600     /* Enable SCT processing, without early connection termination */
1601     if (ct_validation &&
1602         !SSL_CTX_enable_ct(ctx, SSL_CT_VALIDATION_PERMISSIVE)) {
1603         ERR_print_errors(bio_err);
1604         goto end;
1605     }
1606
1607     if (!ctx_set_ctlog_list_file(ctx, ctlog_file)) {
1608         if (ct_validation) {
1609             ERR_print_errors(bio_err);
1610             goto end;
1611         }
1612
1613         /*
1614          * If CT validation is not enabled, the log list isn't needed so don't
1615          * show errors or abort. We try to load it regardless because then we
1616          * can show the names of the logs any SCTs came from (SCTs may be seen
1617          * even with validation disabled).
1618          */
1619         ERR_clear_error();
1620     }
1621 #endif
1622
1623     SSL_CTX_set_verify(ctx, verify, verify_callback);
1624
1625     if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) {
1626         ERR_print_errors(bio_err);
1627         goto end;
1628     }
1629
1630     ssl_ctx_add_crls(ctx, crls, crl_download);
1631
1632     if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain))
1633         goto end;
1634
1635     if (servername != NULL) {
1636         tlsextcbp.biodebug = bio_err;
1637         SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
1638         SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
1639     }
1640 # ifndef OPENSSL_NO_SRP
1641     if (srp_arg.srplogin) {
1642         if (!srp_lateuser && !SSL_CTX_set_srp_username(ctx, srp_arg.srplogin)) {
1643             BIO_printf(bio_err, "Unable to set SRP username\n");
1644             goto end;
1645         }
1646         srp_arg.msg = c_msg;
1647         srp_arg.debug = c_debug;
1648         SSL_CTX_set_srp_cb_arg(ctx, &srp_arg);
1649         SSL_CTX_set_srp_client_pwd_callback(ctx, ssl_give_srp_client_pwd_cb);
1650         SSL_CTX_set_srp_strength(ctx, srp_arg.strength);
1651         if (c_msg || c_debug || srp_arg.amp == 0)
1652             SSL_CTX_set_srp_verify_param_callback(ctx,
1653                                                   ssl_srp_verify_param_cb);
1654     }
1655 # endif
1656
1657     if (dane_tlsa_domain != NULL) {
1658         if (SSL_CTX_dane_enable(ctx) <= 0) {
1659             BIO_printf(bio_err,
1660                        "%s: Error enabling DANE TLSA authentication.\n",
1661                        prog);
1662             ERR_print_errors(bio_err);
1663             goto end;
1664         }
1665     }
1666
1667     con = SSL_new(ctx);
1668     if (sess_in) {
1669         SSL_SESSION *sess;
1670         BIO *stmp = BIO_new_file(sess_in, "r");
1671         if (!stmp) {
1672             BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
1673             ERR_print_errors(bio_err);
1674             goto end;
1675         }
1676         sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
1677         BIO_free(stmp);
1678         if (!sess) {
1679             BIO_printf(bio_err, "Can't open session file %s\n", sess_in);
1680             ERR_print_errors(bio_err);
1681             goto end;
1682         }
1683         if (!SSL_set_session(con, sess)) {
1684             BIO_printf(bio_err, "Can't set session\n");
1685             ERR_print_errors(bio_err);
1686             goto end;
1687         }
1688         SSL_SESSION_free(sess);
1689     }
1690
1691     if (fallback_scsv)
1692         SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV);
1693
1694     if (servername != NULL) {
1695         if (!SSL_set_tlsext_host_name(con, servername)) {
1696             BIO_printf(bio_err, "Unable to set TLS servername extension.\n");
1697             ERR_print_errors(bio_err);
1698             goto end;
1699         }
1700     }
1701
1702     if (dane_tlsa_domain != NULL) {
1703         if (SSL_dane_enable(con, dane_tlsa_domain) <= 0) {
1704             BIO_printf(bio_err, "%s: Error enabling DANE TLSA "
1705                        "authentication.\n", prog);
1706             ERR_print_errors(bio_err);
1707             goto end;
1708         }
1709         if (dane_tlsa_rrset == NULL) {
1710             BIO_printf(bio_err, "%s: DANE TLSA authentication requires at "
1711                        "least one -dane_tlsa_rrdata option.\n", prog);
1712             goto end;
1713         }
1714         if (tlsa_import_rrset(con, dane_tlsa_rrset) <= 0) {
1715             BIO_printf(bio_err, "%s: Failed to import any TLSA "
1716                        "records.\n", prog);
1717             goto end;
1718         }
1719         if (dane_ee_no_name)
1720             SSL_dane_set_flags(con, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
1721     } else if (dane_tlsa_rrset != NULL) {
1722         BIO_printf(bio_err, "%s: DANE TLSA authentication requires the "
1723                    "-dane_tlsa_domain option.\n", prog);
1724         goto end;
1725     }
1726
1727  re_start:
1728     if (init_client(&s, host, port, socket_family, socket_type) == 0) {
1729         BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error());
1730         BIO_closesocket(s);
1731         goto end;
1732     }
1733     BIO_printf(bio_c_out, "CONNECTED(%08X)\n", s);
1734
1735     if (c_nbio) {
1736         if (!BIO_socket_nbio(s, 1)) {
1737             ERR_print_errors(bio_err);
1738             goto end;
1739         }
1740         BIO_printf(bio_c_out, "Turned on non blocking io\n");
1741     }
1742 #ifndef OPENSSL_NO_DTLS
1743     if (socket_type == SOCK_DGRAM) {
1744         union BIO_sock_info_u peer_info;
1745
1746         sbio = BIO_new_dgram(s, BIO_NOCLOSE);
1747         if ((peer_info.addr = BIO_ADDR_new()) == NULL) {
1748             BIO_printf(bio_err, "memory allocation failure\n");
1749             BIO_closesocket(s);
1750             goto end;
1751         }
1752         if (!BIO_sock_info(s, BIO_SOCK_INFO_ADDRESS, &peer_info)) {
1753             BIO_printf(bio_err, "getsockname:errno=%d\n",
1754                        get_last_socket_error());
1755             BIO_ADDR_free(peer_info.addr);
1756             BIO_closesocket(s);
1757             goto end;
1758         }
1759
1760         (void)BIO_ctrl_set_connected(sbio, peer_info.addr);
1761         BIO_ADDR_free(peer_info.addr);
1762         peer_info.addr = NULL;
1763
1764         if (enable_timeouts) {
1765             timeout.tv_sec = 0;
1766             timeout.tv_usec = DGRAM_RCV_TIMEOUT;
1767             BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
1768
1769             timeout.tv_sec = 0;
1770             timeout.tv_usec = DGRAM_SND_TIMEOUT;
1771             BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
1772         }
1773
1774         if (socket_mtu) {
1775             if (socket_mtu < DTLS_get_link_min_mtu(con)) {
1776                 BIO_printf(bio_err, "MTU too small. Must be at least %ld\n",
1777                            DTLS_get_link_min_mtu(con));
1778                 BIO_free(sbio);
1779                 goto shut;
1780             }
1781             SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
1782             if (!DTLS_set_link_mtu(con, socket_mtu)) {
1783                 BIO_printf(bio_err, "Failed to set MTU\n");
1784                 BIO_free(sbio);
1785                 goto shut;
1786             }
1787         } else
1788             /* want to do MTU discovery */
1789             BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
1790     } else
1791 #endif /* OPENSSL_NO_DTLS */
1792         sbio = BIO_new_socket(s, BIO_NOCLOSE);
1793
1794     if (nbio_test) {
1795         BIO *test;
1796
1797         test = BIO_new(BIO_f_nbio_test());
1798         sbio = BIO_push(test, sbio);
1799     }
1800
1801     if (c_debug) {
1802         BIO_set_callback(sbio, bio_dump_callback);
1803         BIO_set_callback_arg(sbio, (char *)bio_c_out);
1804     }
1805     if (c_msg) {
1806 #ifndef OPENSSL_NO_SSL_TRACE
1807         if (c_msg == 2)
1808             SSL_set_msg_callback(con, SSL_trace);
1809         else
1810 #endif
1811             SSL_set_msg_callback(con, msg_cb);
1812         SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out);
1813     }
1814
1815     if (c_tlsextdebug) {
1816         SSL_set_tlsext_debug_callback(con, tlsext_cb);
1817         SSL_set_tlsext_debug_arg(con, bio_c_out);
1818     }
1819 #ifndef OPENSSL_NO_OCSP
1820     if (c_status_req) {
1821         SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
1822         SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
1823         SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
1824     }
1825 #endif
1826
1827     SSL_set_bio(con, sbio, sbio);
1828     SSL_set_connect_state(con);
1829
1830     /* ok, lets connect */
1831     if (fileno_stdin() > SSL_get_fd(con))
1832         width = fileno_stdin() + 1;
1833     else
1834         width = SSL_get_fd(con) + 1;
1835
1836     read_tty = 1;
1837     write_tty = 0;
1838     tty_on = 0;
1839     read_ssl = 1;
1840     write_ssl = 1;
1841
1842     cbuf_len = 0;
1843     cbuf_off = 0;
1844     sbuf_len = 0;
1845     sbuf_off = 0;
1846
1847     switch ((PROTOCOL_CHOICE) starttls_proto) {
1848     case PROTO_OFF:
1849         break;
1850     case PROTO_SMTP:
1851         {
1852             /*
1853              * This is an ugly hack that does a lot of assumptions. We do
1854              * have to handle multi-line responses which may come in a single
1855              * packet or not. We therefore have to use BIO_gets() which does
1856              * need a buffering BIO. So during the initial chitchat we do
1857              * push a buffering BIO into the chain that is removed again
1858              * later on to not disturb the rest of the s_client operation.
1859              */
1860             int foundit = 0;
1861             BIO *fbio = BIO_new(BIO_f_buffer());
1862             BIO_push(fbio, sbio);
1863             /* wait for multi-line response to end from SMTP */
1864             do {
1865                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
1866             }
1867             while (mbuf_len > 3 && mbuf[3] == '-');
1868             BIO_printf(fbio, "EHLO %s\r\n", ehlo);
1869             (void)BIO_flush(fbio);
1870             /* wait for multi-line response to end EHLO SMTP response */
1871             do {
1872                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
1873                 if (strstr(mbuf, "STARTTLS"))
1874                     foundit = 1;
1875             }
1876             while (mbuf_len > 3 && mbuf[3] == '-');
1877             (void)BIO_flush(fbio);
1878             BIO_pop(fbio);
1879             BIO_free(fbio);
1880             if (!foundit)
1881                 BIO_printf(bio_err,
1882                            "didn't find starttls in server response,"
1883                            " trying anyway...\n");
1884             BIO_printf(sbio, "STARTTLS\r\n");
1885             BIO_read(sbio, sbuf, BUFSIZZ);
1886         }
1887         break;
1888     case PROTO_POP3:
1889         {
1890             BIO_read(sbio, mbuf, BUFSIZZ);
1891             BIO_printf(sbio, "STLS\r\n");
1892             mbuf_len = BIO_read(sbio, sbuf, BUFSIZZ);
1893             if (mbuf_len < 0) {
1894                 BIO_printf(bio_err, "BIO_read failed\n");
1895                 goto end;
1896             }
1897         }
1898         break;
1899     case PROTO_IMAP:
1900         {
1901             int foundit = 0;
1902             BIO *fbio = BIO_new(BIO_f_buffer());
1903             BIO_push(fbio, sbio);
1904             BIO_gets(fbio, mbuf, BUFSIZZ);
1905             /* STARTTLS command requires CAPABILITY... */
1906             BIO_printf(fbio, ". CAPABILITY\r\n");
1907             (void)BIO_flush(fbio);
1908             /* wait for multi-line CAPABILITY response */
1909             do {
1910                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
1911                 if (strstr(mbuf, "STARTTLS"))
1912                     foundit = 1;
1913             }
1914             while (mbuf_len > 3 && mbuf[0] != '.');
1915             (void)BIO_flush(fbio);
1916             BIO_pop(fbio);
1917             BIO_free(fbio);
1918             if (!foundit)
1919                 BIO_printf(bio_err,
1920                            "didn't find STARTTLS in server response,"
1921                            " trying anyway...\n");
1922             BIO_printf(sbio, ". STARTTLS\r\n");
1923             BIO_read(sbio, sbuf, BUFSIZZ);
1924         }
1925         break;
1926     case PROTO_FTP:
1927         {
1928             BIO *fbio = BIO_new(BIO_f_buffer());
1929             BIO_push(fbio, sbio);
1930             /* wait for multi-line response to end from FTP */
1931             do {
1932                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
1933             }
1934             while (mbuf_len > 3 && mbuf[3] == '-');
1935             (void)BIO_flush(fbio);
1936             BIO_pop(fbio);
1937             BIO_free(fbio);
1938             BIO_printf(sbio, "AUTH TLS\r\n");
1939             BIO_read(sbio, sbuf, BUFSIZZ);
1940         }
1941         break;
1942     case PROTO_XMPP:
1943     case PROTO_XMPP_SERVER:
1944         {
1945             int seen = 0;
1946             BIO_printf(sbio, "<stream:stream "
1947                        "xmlns:stream='http://etherx.jabber.org/streams' "
1948                        "xmlns='jabber:%s' to='%s' version='1.0'>",
1949                        starttls_proto == PROTO_XMPP ? "client" : "server",
1950                        xmpphost ? xmpphost : host);
1951             seen = BIO_read(sbio, mbuf, BUFSIZZ);
1952             mbuf[seen] = 0;
1953             while (!strstr
1954                    (mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'")
1955                    && !strstr(mbuf,
1956                               "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\""))
1957             {
1958                 seen = BIO_read(sbio, mbuf, BUFSIZZ);
1959
1960                 if (seen <= 0)
1961                     goto shut;
1962
1963                 mbuf[seen] = 0;
1964             }
1965             BIO_printf(sbio,
1966                        "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
1967             seen = BIO_read(sbio, sbuf, BUFSIZZ);
1968             sbuf[seen] = 0;
1969             if (!strstr(sbuf, "<proceed"))
1970                 goto shut;
1971             mbuf[0] = 0;
1972         }
1973         break;
1974     case PROTO_TELNET:
1975         {
1976             static const unsigned char tls_do[] = {
1977                 /* IAC    DO   START_TLS */
1978                    255,   253, 46
1979             };
1980             static const unsigned char tls_will[] = {
1981                 /* IAC  WILL START_TLS */
1982                    255, 251, 46
1983             };
1984             static const unsigned char tls_follows[] = {
1985                 /* IAC  SB   START_TLS FOLLOWS IAC  SE */
1986                    255, 250, 46,       1,      255, 240
1987             };
1988             int bytes;
1989
1990             /* Telnet server should demand we issue START_TLS */
1991             bytes = BIO_read(sbio, mbuf, BUFSIZZ);
1992             if (bytes != 3 || memcmp(mbuf, tls_do, 3) != 0)
1993                 goto shut;
1994             /* Agree to issue START_TLS and send the FOLLOWS sub-command */
1995             BIO_write(sbio, tls_will, 3);
1996             BIO_write(sbio, tls_follows, 6);
1997             (void)BIO_flush(sbio);
1998             /* Telnet server also sent the FOLLOWS sub-command */
1999             bytes = BIO_read(sbio, mbuf, BUFSIZZ);
2000             if (bytes != 6 || memcmp(mbuf, tls_follows, 6) != 0)
2001                 goto shut;
2002         }
2003         break;
2004     case PROTO_CONNECT:
2005         {
2006             int foundit = 0;
2007             BIO *fbio = BIO_new(BIO_f_buffer());
2008
2009             BIO_push(fbio, sbio);
2010             BIO_printf(fbio, "CONNECT %s HTTP/1.0\r\n\r\n", connectstr);
2011             (void)BIO_flush(fbio);
2012             /* wait for multi-line response to end CONNECT response */
2013             do {
2014                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2015                 if (strstr(mbuf, "200") != NULL
2016                     && strstr(mbuf, "established") != NULL)
2017                     foundit++;
2018             } while (mbuf_len > 3 && foundit == 0);
2019             (void)BIO_flush(fbio);
2020             BIO_pop(fbio);
2021             BIO_free(fbio);
2022             if (!foundit) {
2023                 BIO_printf(bio_err, "%s: HTTP CONNECT failed\n", prog);
2024                 goto shut;
2025             }
2026         }
2027         break;
2028     case PROTO_IRC:
2029         {
2030             int numeric;
2031             BIO *fbio = BIO_new(BIO_f_buffer());
2032
2033             BIO_push(fbio, sbio);
2034             BIO_printf(fbio, "STARTTLS\r\n");
2035             (void)BIO_flush(fbio);
2036             width = SSL_get_fd(con) + 1;
2037
2038             do {
2039                 numeric = 0;
2040
2041                 FD_ZERO(&readfds);
2042                 openssl_fdset(SSL_get_fd(con), &readfds);
2043                 timeout.tv_sec = S_CLIENT_IRC_READ_TIMEOUT;
2044                 timeout.tv_usec = 0;
2045                 /*
2046                  * If the IRCd doesn't respond within
2047                  * S_CLIENT_IRC_READ_TIMEOUT seconds, assume
2048                  * it doesn't support STARTTLS. Many IRCds
2049                  * will not give _any_ sort of response to a
2050                  * STARTTLS command when it's not supported.
2051                  */
2052                 if (!BIO_get_buffer_num_lines(fbio)
2053                     && !BIO_pending(fbio)
2054                     && !BIO_pending(sbio)
2055                     && select(width, (void *)&readfds, NULL, NULL,
2056                               &timeout) < 1) {
2057                     BIO_printf(bio_err,
2058                                "Timeout waiting for response (%d seconds).\n",
2059                                S_CLIENT_IRC_READ_TIMEOUT);
2060                     break;
2061                 }
2062
2063                 mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ);
2064                 if (mbuf_len < 1 || sscanf(mbuf, "%*s %d", &numeric) != 1)
2065                     break;
2066                 /* :example.net 451 STARTTLS :You have not registered */
2067                 /* :example.net 421 STARTTLS :Unknown command */
2068                 if ((numeric == 451 || numeric == 421)
2069                     && strstr(mbuf, "STARTTLS") != NULL) {
2070                     BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf);
2071                     break;
2072                 }
2073                 if (numeric == 691) {
2074                     BIO_printf(bio_err, "STARTTLS negotiation failed: ");
2075                     ERR_print_errors(bio_err);
2076                     break;
2077                 }
2078             } while (numeric != 670);
2079
2080             (void)BIO_flush(fbio);
2081             BIO_pop(fbio);
2082             BIO_free(fbio);
2083             if (numeric != 670) {
2084                 BIO_printf(bio_err, "Server does not support STARTTLS.\n");
2085                 ret = 1;
2086                 goto shut;
2087             }
2088         }
2089         break;
2090     case PROTO_POSTGRES:
2091         {
2092             static const unsigned char ssl_request[] = {
2093                 /* Length        SSLRequest */
2094                    0, 0, 0, 8,   4, 210, 22, 47
2095             };
2096             int bytes;
2097
2098             /* Send SSLRequest packet */
2099             BIO_write(sbio, ssl_request, 8);
2100             (void)BIO_flush(sbio);
2101
2102             /* Reply will be a single S if SSL is enabled */
2103             bytes = BIO_read(sbio, sbuf, BUFSIZZ);
2104             if (bytes != 1 || sbuf[0] != 'S')
2105                 goto shut;
2106         }
2107         break;
2108     }
2109
2110     for (;;) {
2111         FD_ZERO(&readfds);
2112         FD_ZERO(&writefds);
2113
2114         if ((SSL_version(con) == DTLS1_VERSION) &&
2115             DTLSv1_get_timeout(con, &timeout))
2116             timeoutp = &timeout;
2117         else
2118             timeoutp = NULL;
2119
2120         if (SSL_in_init(con) && !SSL_total_renegotiations(con)) {
2121             in_init = 1;
2122             tty_on = 0;
2123         } else {
2124             tty_on = 1;
2125             if (in_init) {
2126                 in_init = 0;
2127
2128                 if (servername != NULL && !SSL_session_reused(con)) {
2129                     BIO_printf(bio_c_out,
2130                                "Server did %sacknowledge servername extension.\n",
2131                                tlsextcbp.ack ? "" : "not ");
2132                 }
2133
2134                 if (sess_out) {
2135                     BIO *stmp = BIO_new_file(sess_out, "w");
2136                     if (stmp) {
2137                         PEM_write_bio_SSL_SESSION(stmp, SSL_get_session(con));
2138                         BIO_free(stmp);
2139                     } else
2140                         BIO_printf(bio_err, "Error writing session file %s\n",
2141                                    sess_out);
2142                 }
2143                 if (c_brief) {
2144                     BIO_puts(bio_err, "CONNECTION ESTABLISHED\n");
2145                     print_ssl_summary(con);
2146                 }
2147
2148                 print_stuff(bio_c_out, con, full_log);
2149                 if (full_log > 0)
2150                     full_log--;
2151
2152                 if (starttls_proto) {
2153                     BIO_write(bio_err, mbuf, mbuf_len);
2154                     /* We don't need to know any more */
2155                     if (!reconnect)
2156                         starttls_proto = PROTO_OFF;
2157                 }
2158
2159                 if (reconnect) {
2160                     reconnect--;
2161                     BIO_printf(bio_c_out,
2162                                "drop connection and then reconnect\n");
2163                     do_ssl_shutdown(con);
2164                     SSL_set_connect_state(con);
2165                     BIO_closesocket(SSL_get_fd(con));
2166                     goto re_start;
2167                 }
2168             }
2169         }
2170
2171         ssl_pending = read_ssl && SSL_has_pending(con);
2172
2173         if (!ssl_pending) {
2174 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2175             if (tty_on) {
2176                 /*
2177                  * Note that select() returns when read _would not block_,
2178                  * and EOF satisfies that.  To avoid a CPU-hogging loop,
2179                  * set the flag so we exit.
2180                  */
2181                 if (read_tty && !at_eof)
2182                     openssl_fdset(fileno_stdin(), &readfds);
2183 #if !defined(OPENSSL_SYS_VMS)
2184                 if (write_tty)
2185                     openssl_fdset(fileno_stdout(), &writefds);
2186 #endif
2187             }
2188             if (read_ssl)
2189                 openssl_fdset(SSL_get_fd(con), &readfds);
2190             if (write_ssl)
2191                 openssl_fdset(SSL_get_fd(con), &writefds);
2192 #else
2193             if (!tty_on || !write_tty) {
2194                 if (read_ssl)
2195                     openssl_fdset(SSL_get_fd(con), &readfds);
2196                 if (write_ssl)
2197                     openssl_fdset(SSL_get_fd(con), &writefds);
2198             }
2199 #endif
2200
2201             /*
2202              * Note: under VMS with SOCKETSHR the second parameter is
2203              * currently of type (int *) whereas under other systems it is
2204              * (void *) if you don't have a cast it will choke the compiler:
2205              * if you do have a cast then you can either go for (int *) or
2206              * (void *).
2207              */
2208 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
2209             /*
2210              * Under Windows/DOS we make the assumption that we can always
2211              * write to the tty: therefore if we need to write to the tty we
2212              * just fall through. Otherwise we timeout the select every
2213              * second and see if there are any keypresses. Note: this is a
2214              * hack, in a proper Windows application we wouldn't do this.
2215              */
2216             i = 0;
2217             if (!write_tty) {
2218                 if (read_tty) {
2219                     tv.tv_sec = 1;
2220                     tv.tv_usec = 0;
2221                     i = select(width, (void *)&readfds, (void *)&writefds,
2222                                NULL, &tv);
2223                     if (!i && (!has_stdin_waiting() || !read_tty))
2224                         continue;
2225                 } else
2226                     i = select(width, (void *)&readfds, (void *)&writefds,
2227                                NULL, timeoutp);
2228             }
2229 #else
2230             i = select(width, (void *)&readfds, (void *)&writefds,
2231                        NULL, timeoutp);
2232 #endif
2233             if (i < 0) {
2234                 BIO_printf(bio_err, "bad select %d\n",
2235                            get_last_socket_error());
2236                 goto shut;
2237                 /* goto end; */
2238             }
2239         }
2240
2241         if ((SSL_version(con) == DTLS1_VERSION)
2242             && DTLSv1_handle_timeout(con) > 0) {
2243             BIO_printf(bio_err, "TIMEOUT occurred\n");
2244         }
2245
2246         if (!ssl_pending && FD_ISSET(SSL_get_fd(con), &writefds)) {
2247             k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len);
2248             switch (SSL_get_error(con, k)) {
2249             case SSL_ERROR_NONE:
2250                 cbuf_off += k;
2251                 cbuf_len -= k;
2252                 if (k <= 0)
2253                     goto end;
2254                 /* we have done a  write(con,NULL,0); */
2255                 if (cbuf_len <= 0) {
2256                     read_tty = 1;
2257                     write_ssl = 0;
2258                 } else {        /* if (cbuf_len > 0) */
2259
2260                     read_tty = 0;
2261                     write_ssl = 1;
2262                 }
2263                 break;
2264             case SSL_ERROR_WANT_WRITE:
2265                 BIO_printf(bio_c_out, "write W BLOCK\n");
2266                 write_ssl = 1;
2267                 read_tty = 0;
2268                 break;
2269             case SSL_ERROR_WANT_ASYNC:
2270                 BIO_printf(bio_c_out, "write A BLOCK\n");
2271                 wait_for_async(con);
2272                 write_ssl = 1;
2273                 read_tty = 0;
2274                 break;
2275             case SSL_ERROR_WANT_READ:
2276                 BIO_printf(bio_c_out, "write R BLOCK\n");
2277                 write_tty = 0;
2278                 read_ssl = 1;
2279                 write_ssl = 0;
2280                 break;
2281             case SSL_ERROR_WANT_X509_LOOKUP:
2282                 BIO_printf(bio_c_out, "write X BLOCK\n");
2283                 break;
2284             case SSL_ERROR_ZERO_RETURN:
2285                 if (cbuf_len != 0) {
2286                     BIO_printf(bio_c_out, "shutdown\n");
2287                     ret = 0;
2288                     goto shut;
2289                 } else {
2290                     read_tty = 1;
2291                     write_ssl = 0;
2292                     break;
2293                 }
2294
2295             case SSL_ERROR_SYSCALL:
2296                 if ((k != 0) || (cbuf_len != 0)) {
2297                     BIO_printf(bio_err, "write:errno=%d\n",
2298                                get_last_socket_error());
2299                     goto shut;
2300                 } else {
2301                     read_tty = 1;
2302                     write_ssl = 0;
2303                 }
2304                 break;
2305             case SSL_ERROR_WANT_ASYNC_JOB:
2306                 /* This shouldn't ever happen in s_client - treat as an error */
2307             case SSL_ERROR_SSL:
2308                 ERR_print_errors(bio_err);
2309                 goto shut;
2310             }
2311         }
2312 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VMS)
2313         /* Assume Windows/DOS/BeOS can always write */
2314         else if (!ssl_pending && write_tty)
2315 #else
2316         else if (!ssl_pending && FD_ISSET(fileno_stdout(), &writefds))
2317 #endif
2318         {
2319 #ifdef CHARSET_EBCDIC
2320             ascii2ebcdic(&(sbuf[sbuf_off]), &(sbuf[sbuf_off]), sbuf_len);
2321 #endif
2322             i = raw_write_stdout(&(sbuf[sbuf_off]), sbuf_len);
2323
2324             if (i <= 0) {
2325                 BIO_printf(bio_c_out, "DONE\n");
2326                 ret = 0;
2327                 goto shut;
2328                 /* goto end; */
2329             }
2330
2331             sbuf_len -= i;;
2332             sbuf_off += i;
2333             if (sbuf_len <= 0) {
2334                 read_ssl = 1;
2335                 write_tty = 0;
2336             }
2337         } else if (ssl_pending || FD_ISSET(SSL_get_fd(con), &readfds)) {
2338 #ifdef RENEG
2339             {
2340                 static int iiii;
2341                 if (++iiii == 52) {
2342                     SSL_renegotiate(con);
2343                     iiii = 0;
2344                 }
2345             }
2346 #endif
2347             k = SSL_read(con, sbuf, 1024 /* BUFSIZZ */ );
2348
2349             switch (SSL_get_error(con, k)) {
2350             case SSL_ERROR_NONE:
2351                 if (k <= 0)
2352                     goto end;
2353                 sbuf_off = 0;
2354                 sbuf_len = k;
2355
2356                 read_ssl = 0;
2357                 write_tty = 1;
2358                 break;
2359             case SSL_ERROR_WANT_ASYNC:
2360                 BIO_printf(bio_c_out, "read A BLOCK\n");
2361                 wait_for_async(con);
2362                 write_tty = 0;
2363                 read_ssl = 1;
2364                 if ((read_tty == 0) && (write_ssl == 0))
2365                     write_ssl = 1;
2366                 break;
2367             case SSL_ERROR_WANT_WRITE:
2368                 BIO_printf(bio_c_out, "read W BLOCK\n");
2369                 write_ssl = 1;
2370                 read_tty = 0;
2371                 break;
2372             case SSL_ERROR_WANT_READ:
2373                 BIO_printf(bio_c_out, "read R BLOCK\n");
2374                 write_tty = 0;
2375                 read_ssl = 1;
2376                 if ((read_tty == 0) && (write_ssl == 0))
2377                     write_ssl = 1;
2378                 break;
2379             case SSL_ERROR_WANT_X509_LOOKUP:
2380                 BIO_printf(bio_c_out, "read X BLOCK\n");
2381                 break;
2382             case SSL_ERROR_SYSCALL:
2383                 ret = get_last_socket_error();
2384                 if (c_brief)
2385                     BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n");
2386                 else
2387                     BIO_printf(bio_err, "read:errno=%d\n", ret);
2388                 goto shut;
2389             case SSL_ERROR_ZERO_RETURN:
2390                 BIO_printf(bio_c_out, "closed\n");
2391                 ret = 0;
2392                 goto shut;
2393             case SSL_ERROR_WANT_ASYNC_JOB:
2394                 /* This shouldn't ever happen in s_client. Treat as an error */
2395             case SSL_ERROR_SSL:
2396                 ERR_print_errors(bio_err);
2397                 goto shut;
2398                 /* break; */
2399             }
2400         }
2401 /* OPENSSL_SYS_MSDOS includes OPENSSL_SYS_WINDOWS */
2402 #if defined(OPENSSL_SYS_MSDOS)
2403         else if (has_stdin_waiting())
2404 #else
2405         else if (FD_ISSET(fileno_stdin(), &readfds))
2406 #endif
2407         {
2408             if (crlf) {
2409                 int j, lf_num;
2410
2411                 i = raw_read_stdin(cbuf, BUFSIZZ / 2);
2412                 lf_num = 0;
2413                 /* both loops are skipped when i <= 0 */
2414                 for (j = 0; j < i; j++)
2415                     if (cbuf[j] == '\n')
2416                         lf_num++;
2417                 for (j = i - 1; j >= 0; j--) {
2418                     cbuf[j + lf_num] = cbuf[j];
2419                     if (cbuf[j] == '\n') {
2420                         lf_num--;
2421                         i++;
2422                         cbuf[j + lf_num] = '\r';
2423                     }
2424                 }
2425                 assert(lf_num == 0);
2426             } else
2427                 i = raw_read_stdin(cbuf, BUFSIZZ);
2428 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS)
2429             if (i == 0)
2430                 at_eof = 1;
2431 #endif
2432
2433             if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q' && cmdletters))) {
2434                 BIO_printf(bio_err, "DONE\n");
2435                 ret = 0;
2436                 goto shut;
2437             }
2438
2439             if ((!c_ign_eof) && (cbuf[0] == 'R' && cmdletters)) {
2440                 BIO_printf(bio_err, "RENEGOTIATING\n");
2441                 SSL_renegotiate(con);
2442                 cbuf_len = 0;
2443             }
2444 #ifndef OPENSSL_NO_HEARTBEATS
2445             else if ((!c_ign_eof) && (cbuf[0] == 'B' && cmdletters)) {
2446                 BIO_printf(bio_err, "HEARTBEATING\n");
2447                 SSL_heartbeat(con);
2448                 cbuf_len = 0;
2449             }
2450 #endif
2451             else {
2452                 cbuf_len = i;
2453                 cbuf_off = 0;
2454 #ifdef CHARSET_EBCDIC
2455                 ebcdic2ascii(cbuf, cbuf, i);
2456 #endif
2457             }
2458
2459             write_ssl = 1;
2460             read_tty = 0;
2461         }
2462     }
2463
2464     ret = 0;
2465  shut:
2466     if (in_init)
2467         print_stuff(bio_c_out, con, full_log);
2468     do_ssl_shutdown(con);
2469 #if defined(OPENSSL_SYS_WINDOWS)
2470     /*
2471      * Give the socket time to send its last data before we close it.
2472      * No amount of setting SO_LINGER etc on the socket seems to persuade
2473      * Windows to send the data before closing the socket...but sleeping
2474      * for a short time seems to do it (units in ms)
2475      * TODO: Find a better way to do this
2476      */
2477     Sleep(50);
2478 #endif
2479     BIO_closesocket(SSL_get_fd(con));
2480  end:
2481     if (con != NULL) {
2482         if (prexit != 0)
2483             print_stuff(bio_c_out, con, 1);
2484         SSL_free(con);
2485     }
2486 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2487     OPENSSL_free(next_proto.data);
2488 #endif
2489     SSL_CTX_free(ctx);
2490     X509_free(cert);
2491     sk_X509_CRL_pop_free(crls, X509_CRL_free);
2492     EVP_PKEY_free(key);
2493     sk_X509_pop_free(chain, X509_free);
2494     OPENSSL_free(pass);
2495 #ifndef OPENSSL_NO_SRP
2496     OPENSSL_free(srp_arg.srppassin);
2497 #endif
2498     OPENSSL_free(connectstr);
2499     OPENSSL_free(host);
2500     OPENSSL_free(port);
2501     X509_VERIFY_PARAM_free(vpm);
2502     ssl_excert_free(exc);
2503     sk_OPENSSL_STRING_free(ssl_args);
2504     sk_OPENSSL_STRING_free(dane_tlsa_rrset);
2505     SSL_CONF_CTX_free(cctx);
2506     OPENSSL_clear_free(cbuf, BUFSIZZ);
2507     OPENSSL_clear_free(sbuf, BUFSIZZ);
2508     OPENSSL_clear_free(mbuf, BUFSIZZ);
2509     BIO_free(bio_c_out);
2510     bio_c_out = NULL;
2511     BIO_free(bio_c_msg);
2512     bio_c_msg = NULL;
2513     return (ret);
2514 }
2515
2516 static void print_stuff(BIO *bio, SSL *s, int full)
2517 {
2518     X509 *peer = NULL;
2519     char buf[BUFSIZ];
2520     STACK_OF(X509) *sk;
2521     STACK_OF(X509_NAME) *sk2;
2522     const SSL_CIPHER *c;
2523     X509_NAME *xn;
2524     int i;
2525 #ifndef OPENSSL_NO_COMP
2526     const COMP_METHOD *comp, *expansion;
2527 #endif
2528     unsigned char *exportedkeymat;
2529 #ifndef OPENSSL_NO_CT
2530     const SSL_CTX *ctx = SSL_get_SSL_CTX(s);
2531 #endif
2532
2533     if (full) {
2534         int got_a_chain = 0;
2535
2536         sk = SSL_get_peer_cert_chain(s);
2537         if (sk != NULL) {
2538             got_a_chain = 1;
2539
2540             BIO_printf(bio, "---\nCertificate chain\n");
2541             for (i = 0; i < sk_X509_num(sk); i++) {
2542                 X509_NAME_oneline(X509_get_subject_name(sk_X509_value(sk, i)),
2543                                   buf, sizeof buf);
2544                 BIO_printf(bio, "%2d s:%s\n", i, buf);
2545                 X509_NAME_oneline(X509_get_issuer_name(sk_X509_value(sk, i)),
2546                                   buf, sizeof buf);
2547                 BIO_printf(bio, "   i:%s\n", buf);
2548                 if (c_showcerts)
2549                     PEM_write_bio_X509(bio, sk_X509_value(sk, i));
2550             }
2551         }
2552
2553         BIO_printf(bio, "---\n");
2554         peer = SSL_get_peer_certificate(s);
2555         if (peer != NULL) {
2556             BIO_printf(bio, "Server certificate\n");
2557
2558             /* Redundant if we showed the whole chain */
2559             if (!(c_showcerts && got_a_chain))
2560                 PEM_write_bio_X509(bio, peer);
2561             X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
2562             BIO_printf(bio, "subject=%s\n", buf);
2563             X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
2564             BIO_printf(bio, "issuer=%s\n", buf);
2565         } else
2566             BIO_printf(bio, "no peer certificate available\n");
2567
2568         sk2 = SSL_get_client_CA_list(s);
2569         if ((sk2 != NULL) && (sk_X509_NAME_num(sk2) > 0)) {
2570             BIO_printf(bio, "---\nAcceptable client certificate CA names\n");
2571             for (i = 0; i < sk_X509_NAME_num(sk2); i++) {
2572                 xn = sk_X509_NAME_value(sk2, i);
2573                 X509_NAME_oneline(xn, buf, sizeof(buf));
2574                 BIO_write(bio, buf, strlen(buf));
2575                 BIO_write(bio, "\n", 1);
2576             }
2577         } else {
2578             BIO_printf(bio, "---\nNo client certificate CA names sent\n");
2579         }
2580
2581         ssl_print_sigalgs(bio, s);
2582         ssl_print_tmp_key(bio, s);
2583
2584 #ifndef OPENSSL_NO_CT
2585         /*
2586          * When the SSL session is anonymous, or resumed via an abbreviated
2587          * handshake, no SCTs are provided as part of the handshake.  While in
2588          * a resumed session SCTs may be present in the session's certificate,
2589          * no callbacks are invoked to revalidate these, and in any case that
2590          * set of SCTs may be incomplete.  Thus it makes little sense to
2591          * attempt to display SCTs from a resumed session's certificate, and of
2592          * course none are associated with an anonymous peer.
2593          */
2594         if (peer != NULL && !SSL_session_reused(s) && SSL_ct_is_enabled(s)) {
2595             const STACK_OF(SCT) *scts = SSL_get0_peer_scts(s);
2596             int sct_count = scts != NULL ? sk_SCT_num(scts) : 0;
2597
2598             BIO_printf(bio, "---\nSCTs present (%i)\n", sct_count);
2599             if (sct_count > 0) {
2600                 const CTLOG_STORE *log_store = SSL_CTX_get0_ctlog_store(ctx);
2601
2602                 BIO_printf(bio, "---\n");
2603                 for (i = 0; i < sct_count; ++i) {
2604                     SCT *sct = sk_SCT_value(scts, i);
2605
2606                     BIO_printf(bio, "SCT validation status: %s\n",
2607                                SCT_validation_status_string(sct));
2608                     SCT_print(sct, bio, 0, log_store);
2609                     if (i < sct_count - 1)
2610                         BIO_printf(bio, "\n---\n");
2611                 }
2612                 BIO_printf(bio, "\n");
2613             }
2614         }
2615 #endif
2616
2617         BIO_printf(bio,
2618                    "---\nSSL handshake has read %" PRIu64
2619                    " bytes and written %" PRIu64 " bytes\n",
2620                    BIO_number_read(SSL_get_rbio(s)),
2621                    BIO_number_written(SSL_get_wbio(s)));
2622     }
2623     print_verify_detail(s, bio);
2624     BIO_printf(bio, (SSL_session_reused(s) ? "---\nReused, " : "---\nNew, "));
2625     c = SSL_get_current_cipher(s);
2626     BIO_printf(bio, "%s, Cipher is %s\n",
2627                SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c));
2628     if (peer != NULL) {
2629         EVP_PKEY *pktmp;
2630
2631         pktmp = X509_get0_pubkey(peer);
2632         BIO_printf(bio, "Server public key is %d bit\n",
2633                    EVP_PKEY_bits(pktmp));
2634     }
2635     BIO_printf(bio, "Secure Renegotiation IS%s supported\n",
2636                SSL_get_secure_renegotiation_support(s) ? "" : " NOT");
2637 #ifndef OPENSSL_NO_COMP
2638     comp = SSL_get_current_compression(s);
2639     expansion = SSL_get_current_expansion(s);
2640     BIO_printf(bio, "Compression: %s\n",
2641                comp ? SSL_COMP_get_name(comp) : "NONE");
2642     BIO_printf(bio, "Expansion: %s\n",
2643                expansion ? SSL_COMP_get_name(expansion) : "NONE");
2644 #endif
2645
2646 #ifdef SSL_DEBUG
2647     {
2648         /* Print out local port of connection: useful for debugging */
2649         int sock;
2650         union BIO_sock_info_u info;
2651
2652         sock = SSL_get_fd(s);
2653         if ((info.addr = BIO_ADDR_new()) != NULL
2654             && BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &info)) {
2655             BIO_printf(bio_c_out, "LOCAL PORT is %u\n",
2656                        ntohs(BIO_ADDR_rawport(info.addr)));
2657         }
2658         BIO_ADDR_free(info.addr);
2659     }
2660 #endif
2661
2662 #if !defined(OPENSSL_NO_NEXTPROTONEG)
2663     if (next_proto.status != -1) {
2664         const unsigned char *proto;
2665         unsigned int proto_len;
2666         SSL_get0_next_proto_negotiated(s, &proto, &proto_len);
2667         BIO_printf(bio, "Next protocol: (%d) ", next_proto.status);
2668         BIO_write(bio, proto, proto_len);
2669         BIO_write(bio, "\n", 1);
2670     }
2671 #endif
2672     {
2673         const unsigned char *proto;
2674         unsigned int proto_len;
2675         SSL_get0_alpn_selected(s, &proto, &proto_len);
2676         if (proto_len > 0) {
2677             BIO_printf(bio, "ALPN protocol: ");
2678             BIO_write(bio, proto, proto_len);
2679             BIO_write(bio, "\n", 1);
2680         } else
2681             BIO_printf(bio, "No ALPN negotiated\n");
2682     }
2683
2684 #ifndef OPENSSL_NO_SRTP
2685     {
2686         SRTP_PROTECTION_PROFILE *srtp_profile =
2687             SSL_get_selected_srtp_profile(s);
2688
2689         if (srtp_profile)
2690             BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n",
2691                        srtp_profile->name);
2692     }
2693 #endif
2694
2695     SSL_SESSION_print(bio, SSL_get_session(s));
2696     if (SSL_get_session(s) != NULL && keymatexportlabel != NULL) {
2697         BIO_printf(bio, "Keying material exporter:\n");
2698         BIO_printf(bio, "    Label: '%s'\n", keymatexportlabel);
2699         BIO_printf(bio, "    Length: %i bytes\n", keymatexportlen);
2700         exportedkeymat = app_malloc(keymatexportlen, "export key");
2701         if (!SSL_export_keying_material(s, exportedkeymat,
2702                                         keymatexportlen,
2703                                         keymatexportlabel,
2704                                         strlen(keymatexportlabel),
2705                                         NULL, 0, 0)) {
2706             BIO_printf(bio, "    Error\n");
2707         } else {
2708             BIO_printf(bio, "    Keying material: ");
2709             for (i = 0; i < keymatexportlen; i++)
2710                 BIO_printf(bio, "%02X", exportedkeymat[i]);
2711             BIO_printf(bio, "\n");
2712         }
2713         OPENSSL_free(exportedkeymat);
2714     }
2715     BIO_printf(bio, "---\n");
2716     X509_free(peer);
2717     /* flush, or debugging output gets mixed with http response */
2718     (void)BIO_flush(bio);
2719 }
2720
2721 # ifndef OPENSSL_NO_OCSP
2722 static int ocsp_resp_cb(SSL *s, void *arg)
2723 {
2724     const unsigned char *p;
2725     int len;
2726     OCSP_RESPONSE *rsp;
2727     len = SSL_get_tlsext_status_ocsp_resp(s, &p);
2728     BIO_puts(arg, "OCSP response: ");
2729     if (!p) {
2730         BIO_puts(arg, "no response sent\n");
2731         return 1;
2732     }
2733     rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
2734     if (!rsp) {
2735         BIO_puts(arg, "response parse error\n");
2736         BIO_dump_indent(arg, (char *)p, len, 4);
2737         return 0;
2738     }
2739     BIO_puts(arg, "\n======================================\n");
2740     OCSP_RESPONSE_print(arg, rsp, 0);
2741     BIO_puts(arg, "======================================\n");
2742     OCSP_RESPONSE_free(rsp);
2743     return 1;
2744 }
2745 # endif
2746
2747 #endif                          /* OPENSSL_NO_SOCK */