231915160e49ec5aa698fee521c7029a95dd59ee
[openssl.git] / apps / s_client.c
1 /* apps/s_client.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer. 
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2005 Nokia. All rights reserved.
113  *
114  * The portions of the attached software ("Contribution") is developed by
115  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
116  * license.
117  *
118  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
119  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
120  * support (see RFC 4279) to OpenSSL.
121  *
122  * No patent licenses or other rights except those expressly stated in
123  * the OpenSSL open source license shall be deemed granted or received
124  * expressly, by implication, estoppel, or otherwise.
125  *
126  * No assurances are provided by Nokia that the Contribution does not
127  * infringe the patent or other intellectual property rights of any third
128  * party or that the license provides you with all the necessary rights
129  * to make use of the Contribution.
130  *
131  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
132  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
133  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
134  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
135  * OTHERWISE.
136  */
137
138 #include <assert.h>
139 #include <ctype.h>
140 #include <stdio.h>
141 #include <stdlib.h>
142 #include <string.h>
143 #include <openssl/e_os2.h>
144 #ifdef OPENSSL_NO_STDIO
145 #define APPS_WIN16
146 #endif
147
148 /* With IPv6, it looks like Digital has mixed up the proper order of
149    recursive header file inclusion, resulting in the compiler complaining
150    that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which
151    is needed to have fileno() declared correctly...  So let's define u_int */
152 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
153 #define __U_INT
154 typedef unsigned int u_int;
155 #endif
156
157 #define USE_SOCKETS
158 #include "apps.h"
159 #include <openssl/x509.h>
160 #include <openssl/ssl.h>
161 #include <openssl/err.h>
162 #include <openssl/pem.h>
163 #include <openssl/rand.h>
164 #include <openssl/ocsp.h>
165 #include <openssl/bn.h>
166 #include "s_apps.h"
167 #include "timeouts.h"
168
169 #if (defined(OPENSSL_SYS_VMS) && __VMS_VER < 70000000)
170 /* FIONBIO used as a switch to enable ioctl, and that isn't in VMS < 7.0 */
171 #undef FIONBIO
172 #endif
173
174 #if defined(OPENSSL_SYS_BEOS_R5)
175 #include <fcntl.h>
176 #endif
177
178 #undef PROG
179 #define PROG    s_client_main
180
181 /*#define SSL_HOST_NAME "www.netscape.com" */
182 /*#define SSL_HOST_NAME "193.118.187.102" */
183 #define SSL_HOST_NAME   "localhost"
184
185 /*#define TEST_CERT "client.pem" */ /* no default cert. */
186
187 #undef BUFSIZZ
188 #define BUFSIZZ 1024*8
189
190 extern int verify_depth;
191 extern int verify_error;
192 extern int verify_return_error;
193
194 #ifdef FIONBIO
195 static int c_nbio=0;
196 #endif
197 static int c_Pause=0;
198 static int c_debug=0;
199 #ifndef OPENSSL_NO_TLSEXT
200 static int c_tlsextdebug=0;
201 static int c_status_req=0;
202 #endif
203 static int c_msg=0;
204 static int c_showcerts=0;
205
206 static void sc_usage(void);
207 static void print_stuff(BIO *berr,SSL *con,int full);
208 #ifndef OPENSSL_NO_TLSEXT
209 static int ocsp_resp_cb(SSL *s, void *arg);
210 #endif
211 static BIO *bio_c_out=NULL;
212 static int c_quiet=0;
213 static int c_ign_eof=0;
214
215 #ifndef OPENSSL_NO_PSK
216 /* Default PSK identity and key */
217 static char *psk_identity="Client_identity";
218 static char *psk_key=NULL; /* by default PSK is not used */
219
220 static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity,
221         unsigned int max_identity_len, unsigned char *psk,
222         unsigned int max_psk_len)
223         {
224         unsigned int psk_len = 0;
225         int ret;
226         BIGNUM *bn=NULL;
227
228         if (c_debug)
229                 BIO_printf(bio_c_out, "psk_client_cb\n");
230         if (!hint)
231                 {
232                 /* no ServerKeyExchange message*/
233                 if (c_debug)
234                         BIO_printf(bio_c_out,"NULL received PSK identity hint, continuing anyway\n");
235                 }
236         else if (c_debug)
237                 BIO_printf(bio_c_out, "Received PSK identity hint '%s'\n", hint);
238
239         /* lookup PSK identity and PSK key based on the given identity hint here */
240         ret = BIO_snprintf(identity, max_identity_len, psk_identity);
241         if (ret < 0 || (unsigned int)ret > max_identity_len)
242                 goto out_err;
243         if (c_debug)
244                 BIO_printf(bio_c_out, "created identity '%s' len=%d\n", identity, ret);
245         ret=BN_hex2bn(&bn, psk_key);
246         if (!ret)
247                 {
248                 BIO_printf(bio_err,"Could not convert PSK key '%s' to BIGNUM\n", psk_key);
249                 if (bn)
250                         BN_free(bn);
251                 return 0;
252                 }
253
254         if ((unsigned int)BN_num_bytes(bn) > max_psk_len)
255                 {
256                 BIO_printf(bio_err,"psk buffer of callback is too small (%d) for key (%d)\n",
257                         max_psk_len, BN_num_bytes(bn));
258                 BN_free(bn);
259                 return 0;
260                 }
261
262         psk_len=BN_bn2bin(bn, psk);
263         BN_free(bn);
264         if (psk_len == 0)
265                 goto out_err;
266
267         if (c_debug)
268                 BIO_printf(bio_c_out, "created PSK len=%d\n", psk_len);
269
270         return psk_len;
271  out_err:
272         if (c_debug)
273                 BIO_printf(bio_err, "Error in PSK client callback\n");
274         return 0;
275         }
276 #endif
277
278 static void sc_usage(void)
279         {
280         BIO_printf(bio_err,"usage: s_client args\n");
281         BIO_printf(bio_err,"\n");
282         BIO_printf(bio_err," -host host     - use -connect instead\n");
283         BIO_printf(bio_err," -port port     - use -connect instead\n");
284         BIO_printf(bio_err," -connect host:port - who to connect to (default is %s:%s)\n",SSL_HOST_NAME,PORT_STR);
285
286         BIO_printf(bio_err," -verify arg   - turn on peer certificate verification\n");
287         BIO_printf(bio_err," -cert arg     - certificate file to use, PEM format assumed\n");
288         BIO_printf(bio_err," -certform arg - certificate format (PEM or DER) PEM default\n");
289         BIO_printf(bio_err," -key arg      - Private key file to use, in cert file if\n");
290         BIO_printf(bio_err,"                 not specified but cert file is.\n");
291         BIO_printf(bio_err," -keyform arg  - key format (PEM or DER) PEM default\n");
292         BIO_printf(bio_err," -pass arg     - private key file pass phrase source\n");
293         BIO_printf(bio_err," -CApath arg   - PEM format directory of CA's\n");
294         BIO_printf(bio_err," -CAfile arg   - PEM format file of CA's\n");
295         BIO_printf(bio_err," -reconnect    - Drop and re-make the connection with the same Session-ID\n");
296         BIO_printf(bio_err," -pause        - sleep(1) after each read(2) and write(2) system call\n");
297         BIO_printf(bio_err," -showcerts    - show all certificates in the chain\n");
298         BIO_printf(bio_err," -debug        - extra output\n");
299 #ifdef WATT32
300         BIO_printf(bio_err," -wdebug       - WATT-32 tcp debugging\n");
301 #endif
302         BIO_printf(bio_err," -msg          - Show protocol messages\n");
303         BIO_printf(bio_err," -nbio_test    - more ssl protocol testing\n");
304         BIO_printf(bio_err," -state        - print the 'ssl' states\n");
305 #ifdef FIONBIO
306         BIO_printf(bio_err," -nbio         - Run with non-blocking IO\n");
307 #endif
308         BIO_printf(bio_err," -crlf         - convert LF from terminal into CRLF\n");
309         BIO_printf(bio_err," -quiet        - no s_client output\n");
310         BIO_printf(bio_err," -ign_eof      - ignore input eof (default when -quiet)\n");
311         BIO_printf(bio_err," -no_ign_eof   - don't ignore input eof\n");
312 #ifndef OPENSSL_NO_PSK
313         BIO_printf(bio_err," -psk_identity arg - PSK identity\n");
314         BIO_printf(bio_err," -psk arg      - PSK in hex (without 0x)\n");
315 #endif
316         BIO_printf(bio_err," -ssl2         - just use SSLv2\n");
317         BIO_printf(bio_err," -ssl3         - just use SSLv3\n");
318         BIO_printf(bio_err," -tls1         - just use TLSv1\n");
319         BIO_printf(bio_err," -dtls1        - just use DTLSv1\n");    
320         BIO_printf(bio_err," -mtu          - set the MTU\n");
321         BIO_printf(bio_err," -no_tls1/-no_ssl3/-no_ssl2 - turn off that protocol\n");
322         BIO_printf(bio_err," -bugs         - Switch on all SSL implementation bug workarounds\n");
323         BIO_printf(bio_err," -serverpref   - Use server's cipher preferences (only SSLv2)\n");
324         BIO_printf(bio_err," -cipher       - preferred cipher to use, use the 'openssl ciphers'\n");
325         BIO_printf(bio_err,"                 command to see what is available\n");
326         BIO_printf(bio_err," -starttls prot - use the STARTTLS command before starting TLS\n");
327         BIO_printf(bio_err,"                 for those protocols that support it, where\n");
328         BIO_printf(bio_err,"                 'prot' defines which one to assume.  Currently,\n");
329         BIO_printf(bio_err,"                 only \"smtp\", \"pop3\", \"imap\", \"ftp\" and \"xmpp\"\n");
330         BIO_printf(bio_err,"                 are supported.\n");
331 #ifndef OPENSSL_NO_ENGINE
332         BIO_printf(bio_err," -engine id    - Initialise and use the specified engine\n");
333 #endif
334         BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
335         BIO_printf(bio_err," -sess_out arg - file to write SSL session to\n");
336         BIO_printf(bio_err," -sess_in arg  - file to read SSL session from\n");
337 #ifndef OPENSSL_NO_TLSEXT
338         BIO_printf(bio_err," -servername host  - Set TLS extension servername in ClientHello\n");
339         BIO_printf(bio_err," -tlsextdebug      - hex dump of all TLS extensions received\n");
340         BIO_printf(bio_err," -status           - request certificate status from server\n");
341         BIO_printf(bio_err," -no_ticket        - disable use of RFC4507bis session tickets\n");
342 #endif
343         }
344
345 #ifndef OPENSSL_NO_TLSEXT
346
347 /* This is a context that we pass to callbacks */
348 typedef struct tlsextctx_st {
349    BIO * biodebug;
350    int ack;
351 } tlsextctx;
352
353
354 static int MS_CALLBACK ssl_servername_cb(SSL *s, int *ad, void *arg)
355         {
356         tlsextctx * p = (tlsextctx *) arg;
357         const char * hn= SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
358         if (SSL_get_servername_type(s) != -1) 
359                 p->ack = !SSL_session_reused(s) && hn != NULL;
360         else 
361                 BIO_printf(bio_err,"Can't use SSL_get_servername\n");
362         
363         return SSL_TLSEXT_ERR_OK;
364         }
365 #endif
366
367 enum
368 {
369         PROTO_OFF       = 0,
370         PROTO_SMTP,
371         PROTO_POP3,
372         PROTO_IMAP,
373         PROTO_FTP,
374         PROTO_XMPP
375 };
376
377 int MAIN(int, char **);
378
379 int MAIN(int argc, char **argv)
380         {
381         int off=0;
382         SSL *con=NULL;
383         X509_STORE *store = NULL;
384         int s,k,width,state=0;
385         char *cbuf=NULL,*sbuf=NULL,*mbuf=NULL;
386         int cbuf_len,cbuf_off;
387         int sbuf_len,sbuf_off;
388         fd_set readfds,writefds;
389         short port=PORT;
390         int full_log=1;
391         char *host=SSL_HOST_NAME;
392         char *cert_file=NULL,*key_file=NULL;
393         int cert_format = FORMAT_PEM, key_format = FORMAT_PEM;
394         char *passarg = NULL, *pass = NULL;
395         X509 *cert = NULL;
396         EVP_PKEY *key = NULL;
397         char *CApath=NULL,*CAfile=NULL,*cipher=NULL;
398         int reconnect=0,badop=0,verify=SSL_VERIFY_NONE,bugs=0;
399         int crlf=0;
400         int write_tty,read_tty,write_ssl,read_ssl,tty_on,ssl_pending;
401         SSL_CTX *ctx=NULL;
402         int ret=1,in_init=1,i,nbio_test=0;
403         int starttls_proto = PROTO_OFF;
404         int prexit = 0, vflags = 0;
405         const SSL_METHOD *meth=NULL;
406         int socket_type=SOCK_STREAM;
407         BIO *sbio;
408         char *inrand=NULL;
409         int mbuf_len=0;
410 #ifndef OPENSSL_NO_ENGINE
411         char *engine_id=NULL;
412         char *ssl_client_engine_id=NULL;
413         ENGINE *e=NULL, *ssl_client_engine=NULL;
414 #endif
415 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_BEOS_R5)
416         struct timeval tv;
417 #if defined(OPENSSL_SYS_BEOS_R5)
418         int stdin_set = 0;
419 #endif
420 #endif
421 #ifndef OPENSSL_NO_TLSEXT
422         char *servername = NULL; 
423         tlsextctx tlsextcbp = 
424         {NULL,0};
425 #endif
426         char *sess_in = NULL;
427         char *sess_out = NULL;
428         struct sockaddr peer;
429         int peerlen = sizeof(peer);
430         int enable_timeouts = 0 ;
431         long socket_mtu = 0;
432 #ifdef OPENSSL_EXPERIMENTAL_JPAKE
433         char *jpake_secret = NULL;
434 #endif
435
436 #if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3)
437         meth=SSLv23_client_method();
438 #elif !defined(OPENSSL_NO_SSL3)
439         meth=SSLv3_client_method();
440 #elif !defined(OPENSSL_NO_SSL2)
441         meth=SSLv2_client_method();
442 #endif
443
444         apps_startup();
445         c_Pause=0;
446         c_quiet=0;
447         c_ign_eof=0;
448         c_debug=0;
449         c_msg=0;
450         c_showcerts=0;
451
452         if (bio_err == NULL)
453                 bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
454
455         if (!load_config(bio_err, NULL))
456                 goto end;
457
458         if (    ((cbuf=OPENSSL_malloc(BUFSIZZ)) == NULL) ||
459                 ((sbuf=OPENSSL_malloc(BUFSIZZ)) == NULL) ||
460                 ((mbuf=OPENSSL_malloc(BUFSIZZ)) == NULL))
461                 {
462                 BIO_printf(bio_err,"out of memory\n");
463                 goto end;
464                 }
465
466         verify_depth=0;
467         verify_error=X509_V_OK;
468 #ifdef FIONBIO
469         c_nbio=0;
470 #endif
471
472         argc--;
473         argv++;
474         while (argc >= 1)
475                 {
476                 if      (strcmp(*argv,"-host") == 0)
477                         {
478                         if (--argc < 1) goto bad;
479                         host= *(++argv);
480                         }
481                 else if (strcmp(*argv,"-port") == 0)
482                         {
483                         if (--argc < 1) goto bad;
484                         port=atoi(*(++argv));
485                         if (port == 0) goto bad;
486                         }
487                 else if (strcmp(*argv,"-connect") == 0)
488                         {
489                         if (--argc < 1) goto bad;
490                         if (!extract_host_port(*(++argv),&host,NULL,&port))
491                                 goto bad;
492                         }
493                 else if (strcmp(*argv,"-verify") == 0)
494                         {
495                         verify=SSL_VERIFY_PEER;
496                         if (--argc < 1) goto bad;
497                         verify_depth=atoi(*(++argv));
498                         BIO_printf(bio_err,"verify depth is %d\n",verify_depth);
499                         }
500                 else if (strcmp(*argv,"-cert") == 0)
501                         {
502                         if (--argc < 1) goto bad;
503                         cert_file= *(++argv);
504                         }
505                 else if (strcmp(*argv,"-sess_out") == 0)
506                         {
507                         if (--argc < 1) goto bad;
508                         sess_out = *(++argv);
509                         }
510                 else if (strcmp(*argv,"-sess_in") == 0)
511                         {
512                         if (--argc < 1) goto bad;
513                         sess_in = *(++argv);
514                         }
515                 else if (strcmp(*argv,"-certform") == 0)
516                         {
517                         if (--argc < 1) goto bad;
518                         cert_format = str2fmt(*(++argv));
519                         }
520                 else if (strcmp(*argv,"-crl_check") == 0)
521                         vflags |= X509_V_FLAG_CRL_CHECK;
522                 else if (strcmp(*argv,"-crl_check_all") == 0)
523                         vflags |= X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL;
524                 else if (strcmp(*argv,"-verify_return_error") == 0)
525                         verify_return_error = 1;
526                 else if (strcmp(*argv,"-prexit") == 0)
527                         prexit=1;
528                 else if (strcmp(*argv,"-crlf") == 0)
529                         crlf=1;
530                 else if (strcmp(*argv,"-quiet") == 0)
531                         {
532                         c_quiet=1;
533                         c_ign_eof=1;
534                         }
535                 else if (strcmp(*argv,"-ign_eof") == 0)
536                         c_ign_eof=1;
537                 else if (strcmp(*argv,"-no_ign_eof") == 0)
538                         c_ign_eof=0;
539                 else if (strcmp(*argv,"-pause") == 0)
540                         c_Pause=1;
541                 else if (strcmp(*argv,"-debug") == 0)
542                         c_debug=1;
543 #ifndef OPENSSL_NO_TLSEXT
544                 else if (strcmp(*argv,"-tlsextdebug") == 0)
545                         c_tlsextdebug=1;
546                 else if (strcmp(*argv,"-status") == 0)
547                         c_status_req=1;
548 #endif
549 #ifdef WATT32
550                 else if (strcmp(*argv,"-wdebug") == 0)
551                         dbug_init();
552 #endif
553                 else if (strcmp(*argv,"-msg") == 0)
554                         c_msg=1;
555                 else if (strcmp(*argv,"-showcerts") == 0)
556                         c_showcerts=1;
557                 else if (strcmp(*argv,"-nbio_test") == 0)
558                         nbio_test=1;
559                 else if (strcmp(*argv,"-state") == 0)
560                         state=1;
561 #ifndef OPENSSL_NO_PSK
562                 else if (strcmp(*argv,"-psk_identity") == 0)
563                         {
564                         if (--argc < 1) goto bad;
565                         psk_identity=*(++argv);
566                         }
567                 else if (strcmp(*argv,"-psk") == 0)
568                         {
569                         size_t j;
570
571                         if (--argc < 1) goto bad;
572                         psk_key=*(++argv);
573                         for (j = 0; j < strlen(psk_key); j++)
574                                 {
575                                 if (isxdigit((int)psk_key[j]))
576                                         continue;
577                                 BIO_printf(bio_err,"Not a hex number '%s'\n",*argv);
578                                 goto bad;
579                                 }
580                         }
581 #endif
582 #ifndef OPENSSL_NO_SSL2
583                 else if (strcmp(*argv,"-ssl2") == 0)
584                         meth=SSLv2_client_method();
585 #endif
586 #ifndef OPENSSL_NO_SSL3
587                 else if (strcmp(*argv,"-ssl3") == 0)
588                         meth=SSLv3_client_method();
589 #endif
590 #ifndef OPENSSL_NO_TLS1
591                 else if (strcmp(*argv,"-tls1") == 0)
592                         meth=TLSv1_client_method();
593 #endif
594 #ifndef OPENSSL_NO_DTLS1
595                 else if (strcmp(*argv,"-dtls1") == 0)
596                         {
597                         meth=DTLSv1_client_method();
598                         socket_type=SOCK_DGRAM;
599                         }
600                 else if (strcmp(*argv,"-timeout") == 0)
601                         enable_timeouts=1;
602                 else if (strcmp(*argv,"-mtu") == 0)
603                         {
604                         if (--argc < 1) goto bad;
605                         socket_mtu = atol(*(++argv));
606                         }
607 #endif
608                 else if (strcmp(*argv,"-bugs") == 0)
609                         bugs=1;
610                 else if (strcmp(*argv,"-keyform") == 0)
611                         {
612                         if (--argc < 1) goto bad;
613                         key_format = str2fmt(*(++argv));
614                         }
615                 else if (strcmp(*argv,"-pass") == 0)
616                         {
617                         if (--argc < 1) goto bad;
618                         passarg = *(++argv);
619                         }
620                 else if (strcmp(*argv,"-key") == 0)
621                         {
622                         if (--argc < 1) goto bad;
623                         key_file= *(++argv);
624                         }
625                 else if (strcmp(*argv,"-reconnect") == 0)
626                         {
627                         reconnect=5;
628                         }
629                 else if (strcmp(*argv,"-CApath") == 0)
630                         {
631                         if (--argc < 1) goto bad;
632                         CApath= *(++argv);
633                         }
634                 else if (strcmp(*argv,"-CAfile") == 0)
635                         {
636                         if (--argc < 1) goto bad;
637                         CAfile= *(++argv);
638                         }
639                 else if (strcmp(*argv,"-no_tls1") == 0)
640                         off|=SSL_OP_NO_TLSv1;
641                 else if (strcmp(*argv,"-no_ssl3") == 0)
642                         off|=SSL_OP_NO_SSLv3;
643                 else if (strcmp(*argv,"-no_ssl2") == 0)
644                         off|=SSL_OP_NO_SSLv2;
645                 else if (strcmp(*argv,"-no_comp") == 0)
646                         { off|=SSL_OP_NO_COMPRESSION; }
647 #ifndef OPENSSL_NO_TLSEXT
648                 else if (strcmp(*argv,"-no_ticket") == 0)
649                         { off|=SSL_OP_NO_TICKET; }
650 #endif
651                 else if (strcmp(*argv,"-serverpref") == 0)
652                         off|=SSL_OP_CIPHER_SERVER_PREFERENCE;
653                 else if (strcmp(*argv,"-cipher") == 0)
654                         {
655                         if (--argc < 1) goto bad;
656                         cipher= *(++argv);
657                         }
658 #ifdef FIONBIO
659                 else if (strcmp(*argv,"-nbio") == 0)
660                         { c_nbio=1; }
661 #endif
662                 else if (strcmp(*argv,"-starttls") == 0)
663                         {
664                         if (--argc < 1) goto bad;
665                         ++argv;
666                         if (strcmp(*argv,"smtp") == 0)
667                                 starttls_proto = PROTO_SMTP;
668                         else if (strcmp(*argv,"pop3") == 0)
669                                 starttls_proto = PROTO_POP3;
670                         else if (strcmp(*argv,"imap") == 0)
671                                 starttls_proto = PROTO_IMAP;
672                         else if (strcmp(*argv,"ftp") == 0)
673                                 starttls_proto = PROTO_FTP;
674                         else if (strcmp(*argv, "xmpp") == 0)
675                                 starttls_proto = PROTO_XMPP;
676                         else
677                                 goto bad;
678                         }
679 #ifndef OPENSSL_NO_ENGINE
680                 else if (strcmp(*argv,"-engine") == 0)
681                         {
682                         if (--argc < 1) goto bad;
683                         engine_id = *(++argv);
684                         }
685                 else if (strcmp(*argv,"-ssl_client_engine") == 0)
686                         {
687                         if (--argc < 1) goto bad;
688                         ssl_client_engine_id = *(++argv);
689                         }
690 #endif
691                 else if (strcmp(*argv,"-rand") == 0)
692                         {
693                         if (--argc < 1) goto bad;
694                         inrand= *(++argv);
695                         }
696 #ifndef OPENSSL_NO_TLSEXT
697                 else if (strcmp(*argv,"-servername") == 0)
698                         {
699                         if (--argc < 1) goto bad;
700                         servername= *(++argv);
701                         /* meth=TLSv1_client_method(); */
702                         }
703 #endif
704 #ifdef OPENSSL_EXPERIMENTAL_JPAKE
705                 else if (strcmp(*argv,"-jpake") == 0)
706                         {
707                         if (--argc < 1) goto bad;
708                         jpake_secret = *++argv;
709                         }
710 #endif
711                 else
712                         {
713                         BIO_printf(bio_err,"unknown option %s\n",*argv);
714                         badop=1;
715                         break;
716                         }
717                 argc--;
718                 argv++;
719                 }
720         if (badop)
721                 {
722 bad:
723                 sc_usage();
724                 goto end;
725                 }
726
727         OpenSSL_add_ssl_algorithms();
728         SSL_load_error_strings();
729
730 #ifndef OPENSSL_NO_ENGINE
731         e = setup_engine(bio_err, engine_id, 1);
732         if (ssl_client_engine_id)
733                 {
734                 ssl_client_engine = ENGINE_by_id(ssl_client_engine_id);
735                 if (!ssl_client_engine)
736                         {
737                         BIO_printf(bio_err,
738                                         "Error getting client auth engine\n");
739                         goto end;
740                         }
741                 }
742
743 #endif
744         if (!app_passwd(bio_err, passarg, NULL, &pass, NULL))
745                 {
746                 BIO_printf(bio_err, "Error getting password\n");
747                 goto end;
748                 }
749
750         if (key_file == NULL)
751                 key_file = cert_file;
752
753
754         if (key_file)
755
756                 {
757
758                 key = load_key(bio_err, key_file, key_format, 0, pass, e,
759                                "client certificate private key file");
760                 if (!key)
761                         {
762                         ERR_print_errors(bio_err);
763                         goto end;
764                         }
765
766                 }
767
768         if (cert_file)
769
770                 {
771                 cert = load_cert(bio_err,cert_file,cert_format,
772                                 NULL, e, "client certificate file");
773
774                 if (!cert)
775                         {
776                         ERR_print_errors(bio_err);
777                         goto end;
778                         }
779                 }
780
781         if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL
782                 && !RAND_status())
783                 {
784                 BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n");
785                 }
786         if (inrand != NULL)
787                 BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
788                         app_RAND_load_files(inrand));
789
790         if (bio_c_out == NULL)
791                 {
792                 if (c_quiet && !c_debug && !c_msg)
793                         {
794                         bio_c_out=BIO_new(BIO_s_null());
795                         }
796                 else
797                         {
798                         if (bio_c_out == NULL)
799                                 bio_c_out=BIO_new_fp(stdout,BIO_NOCLOSE);
800                         }
801                 }
802
803         ctx=SSL_CTX_new(meth);
804         if (ctx == NULL)
805                 {
806                 ERR_print_errors(bio_err);
807                 goto end;
808                 }
809
810 #ifndef OPENSSL_NO_ENGINE
811         if (ssl_client_engine)
812                 {
813                 if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine))
814                         {
815                         BIO_puts(bio_err, "Error setting client auth engine\n");
816                         ERR_print_errors(bio_err);
817                         ENGINE_free(ssl_client_engine);
818                         goto end;
819                         }
820                 ENGINE_free(ssl_client_engine);
821                 }
822 #endif
823
824 #ifndef OPENSSL_NO_PSK
825         if (psk_key != NULL)
826                 {
827                 if (c_debug)
828                         BIO_printf(bio_c_out, "PSK key given, setting client callback\n");
829                 SSL_CTX_set_psk_client_callback(ctx, psk_client_cb);
830                 }
831 #endif
832         if (bugs)
833                 SSL_CTX_set_options(ctx,SSL_OP_ALL|off);
834         else
835                 SSL_CTX_set_options(ctx,off);
836         /* DTLS: partial reads end up discarding unread UDP bytes :-( 
837          * Setting read ahead solves this problem.
838          */
839         if (socket_type == SOCK_DGRAM) SSL_CTX_set_read_ahead(ctx, 1);
840
841         if (state) SSL_CTX_set_info_callback(ctx,apps_ssl_info_callback);
842         if (cipher != NULL)
843                 if(!SSL_CTX_set_cipher_list(ctx,cipher)) {
844                 BIO_printf(bio_err,"error setting cipher list\n");
845                 ERR_print_errors(bio_err);
846                 goto end;
847         }
848 #if 0
849         else
850                 SSL_CTX_set_cipher_list(ctx,getenv("SSL_CIPHER"));
851 #endif
852
853         SSL_CTX_set_verify(ctx,verify,verify_callback);
854         if (!set_cert_key_stuff(ctx,cert,key))
855                 goto end;
856
857         if ((!SSL_CTX_load_verify_locations(ctx,CAfile,CApath)) ||
858                 (!SSL_CTX_set_default_verify_paths(ctx)))
859                 {
860                 /* BIO_printf(bio_err,"error setting default verify locations\n"); */
861                 ERR_print_errors(bio_err);
862                 /* goto end; */
863                 }
864
865         store = SSL_CTX_get_cert_store(ctx);
866         X509_STORE_set_flags(store, vflags);
867 #ifndef OPENSSL_NO_TLSEXT
868         if (servername != NULL)
869                 {
870                 tlsextcbp.biodebug = bio_err;
871                 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
872                 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
873                 }
874 #endif
875
876         con=SSL_new(ctx);
877         if (sess_in)
878                 {
879                 SSL_SESSION *sess;
880                 BIO *stmp = BIO_new_file(sess_in, "r");
881                 if (!stmp)
882                         {
883                         BIO_printf(bio_err, "Can't open session file %s\n",
884                                                 sess_in);
885                         ERR_print_errors(bio_err);
886                         goto end;
887                         }
888                 sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
889                 BIO_free(stmp);
890                 if (!sess)
891                         {
892                         BIO_printf(bio_err, "Can't open session file %s\n",
893                                                 sess_in);
894                         ERR_print_errors(bio_err);
895                         goto end;
896                         }
897                 SSL_set_session(con, sess);
898                 SSL_SESSION_free(sess);
899                 }
900 #ifndef OPENSSL_NO_TLSEXT
901         if (servername != NULL)
902                 {
903                 if (!SSL_set_tlsext_host_name(con,servername))
904                         {
905                         BIO_printf(bio_err,"Unable to set TLS servername extension.\n");
906                         ERR_print_errors(bio_err);
907                         goto end;
908                         }
909                 }
910 #endif
911 #ifndef OPENSSL_NO_KRB5
912         if (con  &&  (con->kssl_ctx = kssl_ctx_new()) != NULL)
913                 {
914                 kssl_ctx_setstring(con->kssl_ctx, KSSL_SERVER, host);
915                 }
916 #endif  /* OPENSSL_NO_KRB5  */
917 /*      SSL_set_cipher_list(con,"RC4-MD5"); */
918 #if 0
919 #ifdef TLSEXT_TYPE_opaque_prf_input
920         SSL_set_tlsext_opaque_prf_input(con, "Test client", 11);
921 #endif
922 #endif
923
924 re_start:
925
926         if (init_client(&s,host,port,socket_type) == 0)
927                 {
928                 BIO_printf(bio_err,"connect:errno=%d\n",get_last_socket_error());
929                 SHUTDOWN(s);
930                 goto end;
931                 }
932         BIO_printf(bio_c_out,"CONNECTED(%08X)\n",s);
933
934 #ifdef FIONBIO
935         if (c_nbio)
936                 {
937                 unsigned long l=1;
938                 BIO_printf(bio_c_out,"turning on non blocking io\n");
939                 if (BIO_socket_ioctl(s,FIONBIO,&l) < 0)
940                         {
941                         ERR_print_errors(bio_err);
942                         goto end;
943                         }
944                 }
945 #endif                                              
946         if (c_Pause & 0x01) con->debug=1;
947
948         if ( SSL_version(con) == DTLS1_VERSION)
949                 {
950                 struct timeval timeout;
951
952                 sbio=BIO_new_dgram(s,BIO_NOCLOSE);
953                 if (getsockname(s, &peer, (void *)&peerlen) < 0)
954                         {
955                         BIO_printf(bio_err, "getsockname:errno=%d\n",
956                                 get_last_socket_error());
957                         SHUTDOWN(s);
958                         goto end;
959                         }
960
961                 (void)BIO_ctrl_set_connected(sbio, 1, &peer);
962
963                 if (enable_timeouts)
964                         {
965                         timeout.tv_sec = 0;
966                         timeout.tv_usec = DGRAM_RCV_TIMEOUT;
967                         BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
968                         
969                         timeout.tv_sec = 0;
970                         timeout.tv_usec = DGRAM_SND_TIMEOUT;
971                         BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
972                         }
973
974                 if (socket_mtu > 0)
975                         {
976                         SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
977                         SSL_set_mtu(con, socket_mtu);
978                         }
979                 else
980                         /* want to do MTU discovery */
981                         BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
982                 }
983         else
984                 sbio=BIO_new_socket(s,BIO_NOCLOSE);
985
986         if (nbio_test)
987                 {
988                 BIO *test;
989
990                 test=BIO_new(BIO_f_nbio_test());
991                 sbio=BIO_push(test,sbio);
992                 }
993
994         if (c_debug)
995                 {
996                 con->debug=1;
997                 BIO_set_callback(sbio,bio_dump_callback);
998                 BIO_set_callback_arg(sbio,(char *)bio_c_out);
999                 }
1000         if (c_msg)
1001                 {
1002                 SSL_set_msg_callback(con, msg_cb);
1003                 SSL_set_msg_callback_arg(con, bio_c_out);
1004                 }
1005 #ifndef OPENSSL_NO_TLSEXT
1006         if (c_tlsextdebug)
1007                 {
1008                 SSL_set_tlsext_debug_callback(con, tlsext_cb);
1009                 SSL_set_tlsext_debug_arg(con, bio_c_out);
1010                 }
1011         if (c_status_req)
1012                 {
1013                 SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
1014                 SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
1015                 SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
1016 #if 0
1017 {
1018 STACK_OF(OCSP_RESPID) *ids = sk_OCSP_RESPID_new_null();
1019 OCSP_RESPID *id = OCSP_RESPID_new();
1020 id->value.byKey = ASN1_OCTET_STRING_new();
1021 id->type = V_OCSP_RESPID_KEY;
1022 ASN1_STRING_set(id->value.byKey, "Hello World", -1);
1023 sk_OCSP_RESPID_push(ids, id);
1024 SSL_set_tlsext_status_ids(con, ids);
1025 }
1026 #endif
1027                 }
1028 #endif
1029 #ifdef OPENSSL_EXPERIMENTAL_JPAKE
1030         if (jpake_secret)
1031                 jpake_client_auth(bio_c_out, sbio, jpake_secret);
1032 #endif
1033
1034         SSL_set_bio(con,sbio,sbio);
1035         SSL_set_connect_state(con);
1036
1037         /* ok, lets connect */
1038         width=SSL_get_fd(con)+1;
1039
1040         read_tty=1;
1041         write_tty=0;
1042         tty_on=0;
1043         read_ssl=1;
1044         write_ssl=1;
1045         
1046         cbuf_len=0;
1047         cbuf_off=0;
1048         sbuf_len=0;
1049         sbuf_off=0;
1050
1051         /* This is an ugly hack that does a lot of assumptions */
1052         /* We do have to handle multi-line responses which may come
1053            in a single packet or not. We therefore have to use
1054            BIO_gets() which does need a buffering BIO. So during
1055            the initial chitchat we do push a buffering BIO into the
1056            chain that is removed again later on to not disturb the
1057            rest of the s_client operation. */
1058         if (starttls_proto == PROTO_SMTP)
1059                 {
1060                 int foundit=0;
1061                 BIO *fbio = BIO_new(BIO_f_buffer());
1062                 BIO_push(fbio, sbio);
1063                 /* wait for multi-line response to end from SMTP */
1064                 do
1065                         {
1066                         mbuf_len = BIO_gets(fbio,mbuf,BUFSIZZ);
1067                         }
1068                 while (mbuf_len>3 && mbuf[3]=='-');
1069                 /* STARTTLS command requires EHLO... */
1070                 BIO_printf(fbio,"EHLO openssl.client.net\r\n");
1071                 (void)BIO_flush(fbio);
1072                 /* wait for multi-line response to end EHLO SMTP response */
1073                 do
1074                         {
1075                         mbuf_len = BIO_gets(fbio,mbuf,BUFSIZZ);
1076                         if (strstr(mbuf,"STARTTLS"))
1077                                 foundit=1;
1078                         }
1079                 while (mbuf_len>3 && mbuf[3]=='-');
1080                 (void)BIO_flush(fbio);
1081                 BIO_pop(fbio);
1082                 BIO_free(fbio);
1083                 if (!foundit)
1084                         BIO_printf(bio_err,
1085                                    "didn't found starttls in server response,"
1086                                    " try anyway...\n");
1087                 BIO_printf(sbio,"STARTTLS\r\n");
1088                 BIO_read(sbio,sbuf,BUFSIZZ);
1089                 }
1090         else if (starttls_proto == PROTO_POP3)
1091                 {
1092                 BIO_read(sbio,mbuf,BUFSIZZ);
1093                 BIO_printf(sbio,"STLS\r\n");
1094                 BIO_read(sbio,sbuf,BUFSIZZ);
1095                 }
1096         else if (starttls_proto == PROTO_IMAP)
1097                 {
1098                 int foundit=0;
1099                 BIO *fbio = BIO_new(BIO_f_buffer());
1100                 BIO_push(fbio, sbio);
1101                 BIO_gets(fbio,mbuf,BUFSIZZ);
1102                 /* STARTTLS command requires CAPABILITY... */
1103                 BIO_printf(fbio,". CAPABILITY\r\n");
1104                 (void)BIO_flush(fbio);
1105                 /* wait for multi-line CAPABILITY response */
1106                 do
1107                         {
1108                         mbuf_len = BIO_gets(fbio,mbuf,BUFSIZZ);
1109                         if (strstr(mbuf,"STARTTLS"))
1110                                 foundit=1;
1111                         }
1112                 while (mbuf_len>3 && mbuf[0]!='.');
1113                 (void)BIO_flush(fbio);
1114                 BIO_pop(fbio);
1115                 BIO_free(fbio);
1116                 if (!foundit)
1117                         BIO_printf(bio_err,
1118                                    "didn't found STARTTLS in server response,"
1119                                    " try anyway...\n");
1120                 BIO_printf(sbio,". STARTTLS\r\n");
1121                 BIO_read(sbio,sbuf,BUFSIZZ);
1122                 }
1123         else if (starttls_proto == PROTO_FTP)
1124                 {
1125                 BIO *fbio = BIO_new(BIO_f_buffer());
1126                 BIO_push(fbio, sbio);
1127                 /* wait for multi-line response to end from FTP */
1128                 do
1129                         {
1130                         mbuf_len = BIO_gets(fbio,mbuf,BUFSIZZ);
1131                         }
1132                 while (mbuf_len>3 && mbuf[3]=='-');
1133                 (void)BIO_flush(fbio);
1134                 BIO_pop(fbio);
1135                 BIO_free(fbio);
1136                 BIO_printf(sbio,"AUTH TLS\r\n");
1137                 BIO_read(sbio,sbuf,BUFSIZZ);
1138                 }
1139         if (starttls_proto == PROTO_XMPP)
1140                 {
1141                 int seen = 0;
1142                 BIO_printf(sbio,"<stream:stream "
1143                     "xmlns:stream='http://etherx.jabber.org/streams' "
1144                     "xmlns='jabber:client' to='%s' version='1.0'>", host);
1145                 seen = BIO_read(sbio,mbuf,BUFSIZZ);
1146                 mbuf[seen] = 0;
1147                 while (!strstr(mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'"))
1148                         {
1149                         if (strstr(mbuf, "/stream:features>"))
1150                                 goto shut;
1151                         seen = BIO_read(sbio,mbuf,BUFSIZZ);
1152                         mbuf[seen] = 0;
1153                         }
1154                 BIO_printf(sbio, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
1155                 seen = BIO_read(sbio,sbuf,BUFSIZZ);
1156                 sbuf[seen] = 0;
1157                 if (!strstr(sbuf, "<proceed"))
1158                         goto shut;
1159                 mbuf[0] = 0;
1160                 }
1161
1162         for (;;)
1163                 {
1164                 FD_ZERO(&readfds);
1165                 FD_ZERO(&writefds);
1166
1167                 if (SSL_in_init(con) && !SSL_total_renegotiations(con))
1168                         {
1169                         in_init=1;
1170                         tty_on=0;
1171                         }
1172                 else
1173                         {
1174                         tty_on=1;
1175                         if (in_init)
1176                                 {
1177                                 in_init=0;
1178 #if 0 /* This test doesn't really work as intended (needs to be fixed) */
1179 #ifndef OPENSSL_NO_TLSEXT
1180                                 if (servername != NULL && !SSL_session_reused(con))
1181                                         {
1182                                         BIO_printf(bio_c_out,"Server did %sacknowledge servername extension.\n",tlsextcbp.ack?"":"not ");
1183                                         }
1184 #endif
1185 #endif
1186                                 if (sess_out)
1187                                         {
1188                                         BIO *stmp = BIO_new_file(sess_out, "w");
1189                                         if (stmp)
1190                                                 {
1191                                                 PEM_write_bio_SSL_SESSION(stmp, SSL_get_session(con));
1192                                                 BIO_free(stmp);
1193                                                 }
1194                                         else 
1195                                                 BIO_printf(bio_err, "Error writing session file %s\n", sess_out);
1196                                         }
1197                                 print_stuff(bio_c_out,con,full_log);
1198                                 if (full_log > 0) full_log--;
1199
1200                                 if (starttls_proto)
1201                                         {
1202                                         BIO_printf(bio_err,"%s",mbuf);
1203                                         /* We don't need to know any more */
1204                                         starttls_proto = PROTO_OFF;
1205                                         }
1206
1207                                 if (reconnect)
1208                                         {
1209                                         reconnect--;
1210                                         BIO_printf(bio_c_out,"drop connection and then reconnect\n");
1211                                         SSL_shutdown(con);
1212                                         SSL_set_connect_state(con);
1213                                         SHUTDOWN(SSL_get_fd(con));
1214                                         goto re_start;
1215                                         }
1216                                 }
1217                         }
1218
1219                 ssl_pending = read_ssl && SSL_pending(con);
1220
1221                 if (!ssl_pending)
1222                         {
1223 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_NETWARE) && !defined (OPENSSL_SYS_BEOS_R5)
1224                         if (tty_on)
1225                                 {
1226                                 if (read_tty)  openssl_fdset(fileno(stdin),&readfds);
1227                                 if (write_tty) openssl_fdset(fileno(stdout),&writefds);
1228                                 }
1229                         if (read_ssl)
1230                                 openssl_fdset(SSL_get_fd(con),&readfds);
1231                         if (write_ssl)
1232                                 openssl_fdset(SSL_get_fd(con),&writefds);
1233 #else
1234                         if(!tty_on || !write_tty) {
1235                                 if (read_ssl)
1236                                         openssl_fdset(SSL_get_fd(con),&readfds);
1237                                 if (write_ssl)
1238                                         openssl_fdset(SSL_get_fd(con),&writefds);
1239                         }
1240 #endif
1241 /*                      printf("mode tty(%d %d%d) ssl(%d%d)\n",
1242                                 tty_on,read_tty,write_tty,read_ssl,write_ssl);*/
1243
1244                         /* Note: under VMS with SOCKETSHR the second parameter
1245                          * is currently of type (int *) whereas under other
1246                          * systems it is (void *) if you don't have a cast it
1247                          * will choke the compiler: if you do have a cast then
1248                          * you can either go for (int *) or (void *).
1249                          */
1250 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
1251                         /* Under Windows/DOS we make the assumption that we can
1252                          * always write to the tty: therefore if we need to
1253                          * write to the tty we just fall through. Otherwise
1254                          * we timeout the select every second and see if there
1255                          * are any keypresses. Note: this is a hack, in a proper
1256                          * Windows application we wouldn't do this.
1257                          */
1258                         i=0;
1259                         if(!write_tty) {
1260                                 if(read_tty) {
1261                                         tv.tv_sec = 1;
1262                                         tv.tv_usec = 0;
1263                                         i=select(width,(void *)&readfds,(void *)&writefds,
1264                                                  NULL,&tv);
1265 #if defined(OPENSSL_SYS_WINCE) || defined(OPENSSL_SYS_MSDOS)
1266                                         if(!i && (!_kbhit() || !read_tty) ) continue;
1267 #else
1268                                         if(!i && (!((_kbhit()) || (WAIT_OBJECT_0 == WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 0))) || !read_tty) ) continue;
1269 #endif
1270                                 } else  i=select(width,(void *)&readfds,(void *)&writefds,
1271                                          NULL,NULL);
1272                         }
1273 #elif defined(OPENSSL_SYS_NETWARE)
1274                         if(!write_tty) {
1275                                 if(read_tty) {
1276                                         tv.tv_sec = 1;
1277                                         tv.tv_usec = 0;
1278                                         i=select(width,(void *)&readfds,(void *)&writefds,
1279                                                 NULL,&tv);
1280                                 } else  i=select(width,(void *)&readfds,(void *)&writefds,
1281                                         NULL,NULL);
1282                         }
1283 #elif defined(OPENSSL_SYS_BEOS_R5)
1284                         /* Under BeOS-R5 the situation is similar to DOS */
1285                         i=0;
1286                         stdin_set = 0;
1287                         (void)fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
1288                         if(!write_tty) {
1289                                 if(read_tty) {
1290                                         tv.tv_sec = 1;
1291                                         tv.tv_usec = 0;
1292                                         i=select(width,(void *)&readfds,(void *)&writefds,
1293                                                  NULL,&tv);
1294                                         if (read(fileno(stdin), sbuf, 0) >= 0)
1295                                                 stdin_set = 1;
1296                                         if (!i && (stdin_set != 1 || !read_tty))
1297                                                 continue;
1298                                 } else  i=select(width,(void *)&readfds,(void *)&writefds,
1299                                          NULL,NULL);
1300                         }
1301                         (void)fcntl(fileno(stdin), F_SETFL, 0);
1302 #else
1303                         i=select(width,(void *)&readfds,(void *)&writefds,
1304                                  NULL,NULL);
1305 #endif
1306                         if ( i < 0)
1307                                 {
1308                                 BIO_printf(bio_err,"bad select %d\n",
1309                                 get_last_socket_error());
1310                                 goto shut;
1311                                 /* goto end; */
1312                                 }
1313                         }
1314
1315                 if (!ssl_pending && FD_ISSET(SSL_get_fd(con),&writefds))
1316                         {
1317                         k=SSL_write(con,&(cbuf[cbuf_off]),
1318                                 (unsigned int)cbuf_len);
1319                         switch (SSL_get_error(con,k))
1320                                 {
1321                         case SSL_ERROR_NONE:
1322                                 cbuf_off+=k;
1323                                 cbuf_len-=k;
1324                                 if (k <= 0) goto end;
1325                                 /* we have done a  write(con,NULL,0); */
1326                                 if (cbuf_len <= 0)
1327                                         {
1328                                         read_tty=1;
1329                                         write_ssl=0;
1330                                         }
1331                                 else /* if (cbuf_len > 0) */
1332                                         {
1333                                         read_tty=0;
1334                                         write_ssl=1;
1335                                         }
1336                                 break;
1337                         case SSL_ERROR_WANT_WRITE:
1338                                 BIO_printf(bio_c_out,"write W BLOCK\n");
1339                                 write_ssl=1;
1340                                 read_tty=0;
1341                                 break;
1342                         case SSL_ERROR_WANT_READ:
1343                                 BIO_printf(bio_c_out,"write R BLOCK\n");
1344                                 write_tty=0;
1345                                 read_ssl=1;
1346                                 write_ssl=0;
1347                                 break;
1348                         case SSL_ERROR_WANT_X509_LOOKUP:
1349                                 BIO_printf(bio_c_out,"write X BLOCK\n");
1350                                 break;
1351                         case SSL_ERROR_ZERO_RETURN:
1352                                 if (cbuf_len != 0)
1353                                         {
1354                                         BIO_printf(bio_c_out,"shutdown\n");
1355                                         ret = 0;
1356                                         goto shut;
1357                                         }
1358                                 else
1359                                         {
1360                                         read_tty=1;
1361                                         write_ssl=0;
1362                                         break;
1363                                         }
1364                                 
1365                         case SSL_ERROR_SYSCALL:
1366                                 if ((k != 0) || (cbuf_len != 0))
1367                                         {
1368                                         BIO_printf(bio_err,"write:errno=%d\n",
1369                                                 get_last_socket_error());
1370                                         goto shut;
1371                                         }
1372                                 else
1373                                         {
1374                                         read_tty=1;
1375                                         write_ssl=0;
1376                                         }
1377                                 break;
1378                         case SSL_ERROR_SSL:
1379                                 ERR_print_errors(bio_err);
1380                                 goto shut;
1381                                 }
1382                         }
1383 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_BEOS_R5)
1384                 /* Assume Windows/DOS/BeOS can always write */
1385                 else if (!ssl_pending && write_tty)
1386 #else
1387                 else if (!ssl_pending && FD_ISSET(fileno(stdout),&writefds))
1388 #endif
1389                         {
1390 #ifdef CHARSET_EBCDIC
1391                         ascii2ebcdic(&(sbuf[sbuf_off]),&(sbuf[sbuf_off]),sbuf_len);
1392 #endif
1393                         i=raw_write_stdout(&(sbuf[sbuf_off]),sbuf_len);
1394
1395                         if (i <= 0)
1396                                 {
1397                                 BIO_printf(bio_c_out,"DONE\n");
1398                                 ret = 0;
1399                                 goto shut;
1400                                 /* goto end; */
1401                                 }
1402
1403                         sbuf_len-=i;;
1404                         sbuf_off+=i;
1405                         if (sbuf_len <= 0)
1406                                 {
1407                                 read_ssl=1;
1408                                 write_tty=0;
1409                                 }
1410                         }
1411                 else if (ssl_pending || FD_ISSET(SSL_get_fd(con),&readfds))
1412                         {
1413 #ifdef RENEG
1414 { static int iiii; if (++iiii == 52) { SSL_renegotiate(con); iiii=0; } }
1415 #endif
1416 #if 1
1417                         k=SSL_read(con,sbuf,1024 /* BUFSIZZ */ );
1418 #else
1419 /* Demo for pending and peek :-) */
1420                         k=SSL_read(con,sbuf,16);
1421 { char zbuf[10240]; 
1422 printf("read=%d pending=%d peek=%d\n",k,SSL_pending(con),SSL_peek(con,zbuf,10240));
1423 }
1424 #endif
1425
1426                         switch (SSL_get_error(con,k))
1427                                 {
1428                         case SSL_ERROR_NONE:
1429                                 if (k <= 0)
1430                                         goto end;
1431                                 sbuf_off=0;
1432                                 sbuf_len=k;
1433
1434                                 read_ssl=0;
1435                                 write_tty=1;
1436                                 break;
1437                         case SSL_ERROR_WANT_WRITE:
1438                                 BIO_printf(bio_c_out,"read W BLOCK\n");
1439                                 write_ssl=1;
1440                                 read_tty=0;
1441                                 break;
1442                         case SSL_ERROR_WANT_READ:
1443                                 BIO_printf(bio_c_out,"read R BLOCK\n");
1444                                 write_tty=0;
1445                                 read_ssl=1;
1446                                 if ((read_tty == 0) && (write_ssl == 0))
1447                                         write_ssl=1;
1448                                 break;
1449                         case SSL_ERROR_WANT_X509_LOOKUP:
1450                                 BIO_printf(bio_c_out,"read X BLOCK\n");
1451                                 break;
1452                         case SSL_ERROR_SYSCALL:
1453                                 ret=get_last_socket_error();
1454                                 BIO_printf(bio_err,"read:errno=%d\n",ret);
1455                                 goto shut;
1456                         case SSL_ERROR_ZERO_RETURN:
1457                                 BIO_printf(bio_c_out,"closed\n");
1458                                 ret=0;
1459                                 goto shut;
1460                         case SSL_ERROR_SSL:
1461                                 ERR_print_errors(bio_err);
1462                                 goto shut;
1463                                 /* break; */
1464                                 }
1465                         }
1466
1467 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
1468 #if defined(OPENSSL_SYS_WINCE) || defined(OPENSSL_SYS_MSDOS)
1469                 else if (_kbhit())
1470 #else
1471                 else if ((_kbhit()) || (WAIT_OBJECT_0 == WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 0)))
1472 #endif
1473 #elif defined (OPENSSL_SYS_NETWARE)
1474                 else if (_kbhit())
1475 #elif defined(OPENSSL_SYS_BEOS_R5)
1476                 else if (stdin_set)
1477 #else
1478                 else if (FD_ISSET(fileno(stdin),&readfds))
1479 #endif
1480                         {
1481                         if (crlf)
1482                                 {
1483                                 int j, lf_num;
1484
1485                                 i=raw_read_stdin(cbuf,BUFSIZZ/2);
1486                                 lf_num = 0;
1487                                 /* both loops are skipped when i <= 0 */
1488                                 for (j = 0; j < i; j++)
1489                                         if (cbuf[j] == '\n')
1490                                                 lf_num++;
1491                                 for (j = i-1; j >= 0; j--)
1492                                         {
1493                                         cbuf[j+lf_num] = cbuf[j];
1494                                         if (cbuf[j] == '\n')
1495                                                 {
1496                                                 lf_num--;
1497                                                 i++;
1498                                                 cbuf[j+lf_num] = '\r';
1499                                                 }
1500                                         }
1501                                 assert(lf_num == 0);
1502                                 }
1503                         else
1504                                 i=raw_read_stdin(cbuf,BUFSIZZ);
1505
1506                         if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q')))
1507                                 {
1508                                 BIO_printf(bio_err,"DONE\n");
1509                                 ret=0;
1510                                 goto shut;
1511                                 }
1512
1513                         if ((!c_ign_eof) && (cbuf[0] == 'R'))
1514                                 {
1515                                 BIO_printf(bio_err,"RENEGOTIATING\n");
1516                                 SSL_renegotiate(con);
1517                                 cbuf_len=0;
1518                                 }
1519                         else
1520                                 {
1521                                 cbuf_len=i;
1522                                 cbuf_off=0;
1523 #ifdef CHARSET_EBCDIC
1524                                 ebcdic2ascii(cbuf, cbuf, i);
1525 #endif
1526                                 }
1527
1528                         write_ssl=1;
1529                         read_tty=0;
1530                         }
1531                 }
1532
1533         ret=0;
1534 shut:
1535         if (in_init)
1536                 print_stuff(bio_c_out,con,full_log);
1537         SSL_shutdown(con);
1538         SHUTDOWN(SSL_get_fd(con));
1539 end:
1540         if (con != NULL)
1541                 {
1542                 if (prexit != 0)
1543                         print_stuff(bio_c_out,con,1);
1544                 SSL_free(con);
1545                 }
1546         if (ctx != NULL) SSL_CTX_free(ctx);
1547         if (cert)
1548                 X509_free(cert);
1549         if (key)
1550                 EVP_PKEY_free(key);
1551         if (pass)
1552                 OPENSSL_free(pass);
1553         if (cbuf != NULL) { OPENSSL_cleanse(cbuf,BUFSIZZ); OPENSSL_free(cbuf); }
1554         if (sbuf != NULL) { OPENSSL_cleanse(sbuf,BUFSIZZ); OPENSSL_free(sbuf); }
1555         if (mbuf != NULL) { OPENSSL_cleanse(mbuf,BUFSIZZ); OPENSSL_free(mbuf); }
1556         if (bio_c_out != NULL)
1557                 {
1558                 BIO_free(bio_c_out);
1559                 bio_c_out=NULL;
1560                 }
1561         apps_shutdown();
1562         OPENSSL_EXIT(ret);
1563         }
1564
1565
1566 static void print_stuff(BIO *bio, SSL *s, int full)
1567         {
1568         X509 *peer=NULL;
1569         char *p;
1570         static const char *space="                ";
1571         char buf[BUFSIZ];
1572         STACK_OF(X509) *sk;
1573         STACK_OF(X509_NAME) *sk2;
1574         const SSL_CIPHER *c;
1575         X509_NAME *xn;
1576         int j,i;
1577 #ifndef OPENSSL_NO_COMP
1578         const COMP_METHOD *comp, *expansion;
1579 #endif
1580
1581         if (full)
1582                 {
1583                 int got_a_chain = 0;
1584
1585                 sk=SSL_get_peer_cert_chain(s);
1586                 if (sk != NULL)
1587                         {
1588                         got_a_chain = 1; /* we don't have it for SSL2 (yet) */
1589
1590                         BIO_printf(bio,"---\nCertificate chain\n");
1591                         for (i=0; i<sk_X509_num(sk); i++)
1592                                 {
1593                                 X509_NAME_oneline(X509_get_subject_name(
1594                                         sk_X509_value(sk,i)),buf,sizeof buf);
1595                                 BIO_printf(bio,"%2d s:%s\n",i,buf);
1596                                 X509_NAME_oneline(X509_get_issuer_name(
1597                                         sk_X509_value(sk,i)),buf,sizeof buf);
1598                                 BIO_printf(bio,"   i:%s\n",buf);
1599                                 if (c_showcerts)
1600                                         PEM_write_bio_X509(bio,sk_X509_value(sk,i));
1601                                 }
1602                         }
1603
1604                 BIO_printf(bio,"---\n");
1605                 peer=SSL_get_peer_certificate(s);
1606                 if (peer != NULL)
1607                         {
1608                         BIO_printf(bio,"Server certificate\n");
1609                         if (!(c_showcerts && got_a_chain)) /* Redundant if we showed the whole chain */
1610                                 PEM_write_bio_X509(bio,peer);
1611                         X509_NAME_oneline(X509_get_subject_name(peer),
1612                                 buf,sizeof buf);
1613                         BIO_printf(bio,"subject=%s\n",buf);
1614                         X509_NAME_oneline(X509_get_issuer_name(peer),
1615                                 buf,sizeof buf);
1616                         BIO_printf(bio,"issuer=%s\n",buf);
1617                         }
1618                 else
1619                         BIO_printf(bio,"no peer certificate available\n");
1620
1621                 sk2=SSL_get_client_CA_list(s);
1622                 if ((sk2 != NULL) && (sk_X509_NAME_num(sk2) > 0))
1623                         {
1624                         BIO_printf(bio,"---\nAcceptable client certificate CA names\n");
1625                         for (i=0; i<sk_X509_NAME_num(sk2); i++)
1626                                 {
1627                                 xn=sk_X509_NAME_value(sk2,i);
1628                                 X509_NAME_oneline(xn,buf,sizeof(buf));
1629                                 BIO_write(bio,buf,strlen(buf));
1630                                 BIO_write(bio,"\n",1);
1631                                 }
1632                         }
1633                 else
1634                         {
1635                         BIO_printf(bio,"---\nNo client certificate CA names sent\n");
1636                         }
1637                 p=SSL_get_shared_ciphers(s,buf,sizeof buf);
1638                 if (p != NULL)
1639                         {
1640                         /* This works only for SSL 2.  In later protocol
1641                          * versions, the client does not know what other
1642                          * ciphers (in addition to the one to be used
1643                          * in the current connection) the server supports. */
1644
1645                         BIO_printf(bio,"---\nCiphers common between both SSL endpoints:\n");
1646                         j=i=0;
1647                         while (*p)
1648                                 {
1649                                 if (*p == ':')
1650                                         {
1651                                         BIO_write(bio,space,15-j%25);
1652                                         i++;
1653                                         j=0;
1654                                         BIO_write(bio,((i%3)?" ":"\n"),1);
1655                                         }
1656                                 else
1657                                         {
1658                                         BIO_write(bio,p,1);
1659                                         j++;
1660                                         }
1661                                 p++;
1662                                 }
1663                         BIO_write(bio,"\n",1);
1664                         }
1665
1666                 BIO_printf(bio,"---\nSSL handshake has read %ld bytes and written %ld bytes\n",
1667                         BIO_number_read(SSL_get_rbio(s)),
1668                         BIO_number_written(SSL_get_wbio(s)));
1669                 }
1670         BIO_printf(bio,((s->hit)?"---\nReused, ":"---\nNew, "));
1671         c=SSL_get_current_cipher(s);
1672         BIO_printf(bio,"%s, Cipher is %s\n",
1673                 SSL_CIPHER_get_version(c),
1674                 SSL_CIPHER_get_name(c));
1675         if (peer != NULL) {
1676                 EVP_PKEY *pktmp;
1677                 pktmp = X509_get_pubkey(peer);
1678                 BIO_printf(bio,"Server public key is %d bit\n",
1679                                                          EVP_PKEY_bits(pktmp));
1680                 EVP_PKEY_free(pktmp);
1681         }
1682 #ifndef OPENSSL_NO_COMP
1683         comp=SSL_get_current_compression(s);
1684         expansion=SSL_get_current_expansion(s);
1685         BIO_printf(bio,"Compression: %s\n",
1686                 comp ? SSL_COMP_get_name(comp) : "NONE");
1687         BIO_printf(bio,"Expansion: %s\n",
1688                 expansion ? SSL_COMP_get_name(expansion) : "NONE");
1689 #endif
1690         SSL_SESSION_print(bio,SSL_get_session(s));
1691         BIO_printf(bio,"---\n");
1692         if (peer != NULL)
1693                 X509_free(peer);
1694         /* flush, or debugging output gets mixed with http response */
1695         (void)BIO_flush(bio);
1696         }
1697
1698 #ifndef OPENSSL_NO_TLSEXT
1699
1700 static int ocsp_resp_cb(SSL *s, void *arg)
1701         {
1702         const unsigned char *p;
1703         int len;
1704         OCSP_RESPONSE *rsp;
1705         len = SSL_get_tlsext_status_ocsp_resp(s, &p);
1706         BIO_puts(arg, "OCSP response: ");
1707         if (!p)
1708                 {
1709                 BIO_puts(arg, "no response sent\n");
1710                 return 1;
1711                 }
1712         rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
1713         if (!rsp)
1714                 {
1715                 BIO_puts(arg, "response parse error\n");
1716                 BIO_dump_indent(arg, (char *)p, len, 4);
1717                 return 0;
1718                 }
1719         BIO_puts(arg, "\n======================================\n");
1720         OCSP_RESPONSE_print(arg, rsp, 0);
1721         BIO_puts(arg, "======================================\n");
1722         OCSP_RESPONSE_free(rsp);
1723         return 1;
1724         }
1725
1726 #endif