Fix Warning...
[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 #ifndef OPENSSL_NO_PSK
312         BIO_printf(bio_err," -psk_identity arg - PSK identity\n");
313         BIO_printf(bio_err," -psk arg      - PSK in hex (without 0x)\n");
314 #endif
315         BIO_printf(bio_err," -ssl2         - just use SSLv2\n");
316         BIO_printf(bio_err," -ssl3         - just use SSLv3\n");
317         BIO_printf(bio_err," -tls1         - just use TLSv1\n");
318         BIO_printf(bio_err," -dtls1        - just use DTLSv1\n");    
319         BIO_printf(bio_err," -mtu          - set the MTU\n");
320         BIO_printf(bio_err," -no_tls1/-no_ssl3/-no_ssl2 - turn off that protocol\n");
321         BIO_printf(bio_err," -bugs         - Switch on all SSL implementation bug workarounds\n");
322         BIO_printf(bio_err," -serverpref   - Use server's cipher preferences (only SSLv2)\n");
323         BIO_printf(bio_err," -cipher       - preferred cipher to use, use the 'openssl ciphers'\n");
324         BIO_printf(bio_err,"                 command to see what is available\n");
325         BIO_printf(bio_err," -starttls prot - use the STARTTLS command before starting TLS\n");
326         BIO_printf(bio_err,"                 for those protocols that support it, where\n");
327         BIO_printf(bio_err,"                 'prot' defines which one to assume.  Currently,\n");
328         BIO_printf(bio_err,"                 only \"smtp\", \"pop3\", \"imap\", \"ftp\" and \"xmpp\"\n");
329         BIO_printf(bio_err,"                 are supported.\n");
330 #ifndef OPENSSL_NO_ENGINE
331         BIO_printf(bio_err," -engine id    - Initialise and use the specified engine\n");
332 #endif
333         BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
334         BIO_printf(bio_err," -sess_out arg - file to write SSL session to\n");
335         BIO_printf(bio_err," -sess_in arg  - file to read SSL session from\n");
336 #ifndef OPENSSL_NO_TLSEXT
337         BIO_printf(bio_err," -servername host  - Set TLS extension servername in ClientHello\n");
338         BIO_printf(bio_err," -tlsextdebug      - hex dump of all TLS extensions received\n");
339         BIO_printf(bio_err," -status           - request certificate status from server\n");
340         BIO_printf(bio_err," -no_ticket        - disable use of RFC4507bis session tickets\n");
341 #endif
342         }
343
344 #ifndef OPENSSL_NO_TLSEXT
345
346 /* This is a context that we pass to callbacks */
347 typedef struct tlsextctx_st {
348    BIO * biodebug;
349    int ack;
350 } tlsextctx;
351
352
353 static int MS_CALLBACK ssl_servername_cb(SSL *s, int *ad, void *arg)
354         {
355         tlsextctx * p = (tlsextctx *) arg;
356         const char * hn= SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
357         if (SSL_get_servername_type(s) != -1) 
358                 p->ack = !SSL_session_reused(s) && hn != NULL;
359         else 
360                 BIO_printf(bio_err,"Can't use SSL_get_servername\n");
361         
362         return SSL_TLSEXT_ERR_OK;
363         }
364 #endif
365
366 enum
367 {
368         PROTO_OFF       = 0,
369         PROTO_SMTP,
370         PROTO_POP3,
371         PROTO_IMAP,
372         PROTO_FTP,
373         PROTO_XMPP
374 };
375
376 int MAIN(int, char **);
377
378 int MAIN(int argc, char **argv)
379         {
380         int off=0;
381         SSL *con=NULL;
382         X509_STORE *store = NULL;
383         int s,k,width,state=0;
384         char *cbuf=NULL,*sbuf=NULL,*mbuf=NULL;
385         int cbuf_len,cbuf_off;
386         int sbuf_len,sbuf_off;
387         fd_set readfds,writefds;
388         short port=PORT;
389         int full_log=1;
390         char *host=SSL_HOST_NAME;
391         char *cert_file=NULL,*key_file=NULL;
392         int cert_format = FORMAT_PEM, key_format = FORMAT_PEM;
393         char *passarg = NULL, *pass = NULL;
394         X509 *cert = NULL;
395         EVP_PKEY *key = NULL;
396         char *CApath=NULL,*CAfile=NULL,*cipher=NULL;
397         int reconnect=0,badop=0,verify=SSL_VERIFY_NONE,bugs=0;
398         int crlf=0;
399         int write_tty,read_tty,write_ssl,read_ssl,tty_on,ssl_pending;
400         SSL_CTX *ctx=NULL;
401         int ret=1,in_init=1,i,nbio_test=0;
402         int starttls_proto = PROTO_OFF;
403         int prexit = 0, vflags = 0;
404         const SSL_METHOD *meth=NULL;
405         int socket_type=SOCK_STREAM;
406         BIO *sbio;
407         char *inrand=NULL;
408         int mbuf_len=0;
409 #ifndef OPENSSL_NO_ENGINE
410         char *engine_id=NULL;
411         char *ssl_client_engine_id=NULL;
412         ENGINE *e=NULL, *ssl_client_engine=NULL;
413 #endif
414 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_BEOS_R5)
415         struct timeval tv;
416 #if defined(OPENSSL_SYS_BEOS_R5)
417         int stdin_set = 0;
418 #endif
419 #endif
420
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
433 #if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3)
434         meth=SSLv23_client_method();
435 #elif !defined(OPENSSL_NO_SSL3)
436         meth=SSLv3_client_method();
437 #elif !defined(OPENSSL_NO_SSL2)
438         meth=SSLv2_client_method();
439 #endif
440
441         apps_startup();
442         c_Pause=0;
443         c_quiet=0;
444         c_ign_eof=0;
445         c_debug=0;
446         c_msg=0;
447         c_showcerts=0;
448
449         if (bio_err == NULL)
450                 bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
451
452         if (!load_config(bio_err, NULL))
453                 goto end;
454
455         if (    ((cbuf=OPENSSL_malloc(BUFSIZZ)) == NULL) ||
456                 ((sbuf=OPENSSL_malloc(BUFSIZZ)) == NULL) ||
457                 ((mbuf=OPENSSL_malloc(BUFSIZZ)) == NULL))
458                 {
459                 BIO_printf(bio_err,"out of memory\n");
460                 goto end;
461                 }
462
463         verify_depth=0;
464         verify_error=X509_V_OK;
465 #ifdef FIONBIO
466         c_nbio=0;
467 #endif
468
469         argc--;
470         argv++;
471         while (argc >= 1)
472                 {
473                 if      (strcmp(*argv,"-host") == 0)
474                         {
475                         if (--argc < 1) goto bad;
476                         host= *(++argv);
477                         }
478                 else if (strcmp(*argv,"-port") == 0)
479                         {
480                         if (--argc < 1) goto bad;
481                         port=atoi(*(++argv));
482                         if (port == 0) goto bad;
483                         }
484                 else if (strcmp(*argv,"-connect") == 0)
485                         {
486                         if (--argc < 1) goto bad;
487                         if (!extract_host_port(*(++argv),&host,NULL,&port))
488                                 goto bad;
489                         }
490                 else if (strcmp(*argv,"-verify") == 0)
491                         {
492                         verify=SSL_VERIFY_PEER;
493                         if (--argc < 1) goto bad;
494                         verify_depth=atoi(*(++argv));
495                         BIO_printf(bio_err,"verify depth is %d\n",verify_depth);
496                         }
497                 else if (strcmp(*argv,"-cert") == 0)
498                         {
499                         if (--argc < 1) goto bad;
500                         cert_file= *(++argv);
501                         }
502                 else if (strcmp(*argv,"-sess_out") == 0)
503                         {
504                         if (--argc < 1) goto bad;
505                         sess_out = *(++argv);
506                         }
507                 else if (strcmp(*argv,"-sess_in") == 0)
508                         {
509                         if (--argc < 1) goto bad;
510                         sess_in = *(++argv);
511                         }
512                 else if (strcmp(*argv,"-certform") == 0)
513                         {
514                         if (--argc < 1) goto bad;
515                         cert_format = str2fmt(*(++argv));
516                         }
517                 else if (strcmp(*argv,"-crl_check") == 0)
518                         vflags |= X509_V_FLAG_CRL_CHECK;
519                 else if (strcmp(*argv,"-crl_check_all") == 0)
520                         vflags |= X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL;
521                 else if (strcmp(*argv,"-verify_return_error") == 0)
522                         verify_return_error = 1;
523                 else if (strcmp(*argv,"-prexit") == 0)
524                         prexit=1;
525                 else if (strcmp(*argv,"-crlf") == 0)
526                         crlf=1;
527                 else if (strcmp(*argv,"-quiet") == 0)
528                         {
529                         c_quiet=1;
530                         c_ign_eof=1;
531                         }
532                 else if (strcmp(*argv,"-ign_eof") == 0)
533                         c_ign_eof=1;
534                 else if (strcmp(*argv,"-pause") == 0)
535                         c_Pause=1;
536                 else if (strcmp(*argv,"-debug") == 0)
537                         c_debug=1;
538 #ifndef OPENSSL_NO_TLSEXT
539                 else if (strcmp(*argv,"-tlsextdebug") == 0)
540                         c_tlsextdebug=1;
541                 else if (strcmp(*argv,"-status") == 0)
542                         c_status_req=1;
543 #endif
544 #ifdef WATT32
545                 else if (strcmp(*argv,"-wdebug") == 0)
546                         dbug_init();
547 #endif
548                 else if (strcmp(*argv,"-msg") == 0)
549                         c_msg=1;
550                 else if (strcmp(*argv,"-showcerts") == 0)
551                         c_showcerts=1;
552                 else if (strcmp(*argv,"-nbio_test") == 0)
553                         nbio_test=1;
554                 else if (strcmp(*argv,"-state") == 0)
555                         state=1;
556 #ifndef OPENSSL_NO_PSK
557                 else if (strcmp(*argv,"-psk_identity") == 0)
558                         {
559                         if (--argc < 1) goto bad;
560                         psk_identity=*(++argv);
561                         }
562                 else if (strcmp(*argv,"-psk") == 0)
563                         {
564                         size_t j;
565
566                         if (--argc < 1) goto bad;
567                         psk_key=*(++argv);
568                         for (j = 0; j < strlen(psk_key); j++)
569                                 {
570                                 if (isxdigit((int)psk_key[j]))
571                                         continue;
572                                 BIO_printf(bio_err,"Not a hex number '%s'\n",*argv);
573                                 goto bad;
574                                 }
575                         }
576 #endif
577 #ifndef OPENSSL_NO_SSL2
578                 else if (strcmp(*argv,"-ssl2") == 0)
579                         meth=SSLv2_client_method();
580 #endif
581 #ifndef OPENSSL_NO_SSL3
582                 else if (strcmp(*argv,"-ssl3") == 0)
583                         meth=SSLv3_client_method();
584 #endif
585 #ifndef OPENSSL_NO_TLS1
586                 else if (strcmp(*argv,"-tls1") == 0)
587                         meth=TLSv1_client_method();
588 #endif
589 #ifndef OPENSSL_NO_DTLS1
590                 else if (strcmp(*argv,"-dtls1") == 0)
591                         {
592                         meth=DTLSv1_client_method();
593                         socket_type=SOCK_DGRAM;
594                         }
595                 else if (strcmp(*argv,"-timeout") == 0)
596                         enable_timeouts=1;
597                 else if (strcmp(*argv,"-mtu") == 0)
598                         {
599                         if (--argc < 1) goto bad;
600                         socket_mtu = atol(*(++argv));
601                         }
602 #endif
603                 else if (strcmp(*argv,"-bugs") == 0)
604                         bugs=1;
605                 else if (strcmp(*argv,"-keyform") == 0)
606                         {
607                         if (--argc < 1) goto bad;
608                         key_format = str2fmt(*(++argv));
609                         }
610                 else if (strcmp(*argv,"-pass") == 0)
611                         {
612                         if (--argc < 1) goto bad;
613                         passarg = *(++argv);
614                         }
615                 else if (strcmp(*argv,"-key") == 0)
616                         {
617                         if (--argc < 1) goto bad;
618                         key_file= *(++argv);
619                         }
620                 else if (strcmp(*argv,"-reconnect") == 0)
621                         {
622                         reconnect=5;
623                         }
624                 else if (strcmp(*argv,"-CApath") == 0)
625                         {
626                         if (--argc < 1) goto bad;
627                         CApath= *(++argv);
628                         }
629                 else if (strcmp(*argv,"-CAfile") == 0)
630                         {
631                         if (--argc < 1) goto bad;
632                         CAfile= *(++argv);
633                         }
634                 else if (strcmp(*argv,"-no_tls1") == 0)
635                         off|=SSL_OP_NO_TLSv1;
636                 else if (strcmp(*argv,"-no_ssl3") == 0)
637                         off|=SSL_OP_NO_SSLv3;
638                 else if (strcmp(*argv,"-no_ssl2") == 0)
639                         off|=SSL_OP_NO_SSLv2;
640                 else if (strcmp(*argv,"-no_comp") == 0)
641                         { off|=SSL_OP_NO_COMPRESSION; }
642 #ifndef OPENSSL_NO_TLSEXT
643                 else if (strcmp(*argv,"-no_ticket") == 0)
644                         { off|=SSL_OP_NO_TICKET; }
645 #endif
646                 else if (strcmp(*argv,"-serverpref") == 0)
647                         off|=SSL_OP_CIPHER_SERVER_PREFERENCE;
648                 else if (strcmp(*argv,"-cipher") == 0)
649                         {
650                         if (--argc < 1) goto bad;
651                         cipher= *(++argv);
652                         }
653 #ifdef FIONBIO
654                 else if (strcmp(*argv,"-nbio") == 0)
655                         { c_nbio=1; }
656 #endif
657                 else if (strcmp(*argv,"-starttls") == 0)
658                         {
659                         if (--argc < 1) goto bad;
660                         ++argv;
661                         if (strcmp(*argv,"smtp") == 0)
662                                 starttls_proto = PROTO_SMTP;
663                         else if (strcmp(*argv,"pop3") == 0)
664                                 starttls_proto = PROTO_POP3;
665                         else if (strcmp(*argv,"imap") == 0)
666                                 starttls_proto = PROTO_IMAP;
667                         else if (strcmp(*argv,"ftp") == 0)
668                                 starttls_proto = PROTO_FTP;
669                         else if (strcmp(*argv, "xmpp") == 0)
670                                 starttls_proto = PROTO_XMPP;
671                         else
672                                 goto bad;
673                         }
674 #ifndef OPENSSL_NO_ENGINE
675                 else if (strcmp(*argv,"-engine") == 0)
676                         {
677                         if (--argc < 1) goto bad;
678                         engine_id = *(++argv);
679                         }
680                 else if (strcmp(*argv,"-ssl_client_engine") == 0)
681                         {
682                         if (--argc < 1) goto bad;
683                         ssl_client_engine_id = *(++argv);
684                         }
685 #endif
686                 else if (strcmp(*argv,"-rand") == 0)
687                         {
688                         if (--argc < 1) goto bad;
689                         inrand= *(++argv);
690                         }
691 #ifndef OPENSSL_NO_TLSEXT
692                 else if (strcmp(*argv,"-servername") == 0)
693                         {
694                         if (--argc < 1) goto bad;
695                         servername= *(++argv);
696                         /* meth=TLSv1_client_method(); */
697                         }
698 #endif
699                 else
700                         {
701                         BIO_printf(bio_err,"unknown option %s\n",*argv);
702                         badop=1;
703                         break;
704                         }
705                 argc--;
706                 argv++;
707                 }
708         if (badop)
709                 {
710 bad:
711                 sc_usage();
712                 goto end;
713                 }
714
715         OpenSSL_add_ssl_algorithms();
716         SSL_load_error_strings();
717
718 #ifndef OPENSSL_NO_ENGINE
719         e = setup_engine(bio_err, engine_id, 1);
720         if (ssl_client_engine_id)
721                 {
722                 ssl_client_engine = ENGINE_by_id(ssl_client_engine_id);
723                 if (!ssl_client_engine)
724                         {
725                         BIO_printf(bio_err,
726                                         "Error getting client auth engine\n");
727                         goto end;
728                         }
729                 }
730
731 #endif
732         if (!app_passwd(bio_err, passarg, NULL, &pass, NULL))
733                 {
734                 BIO_printf(bio_err, "Error getting password\n");
735                 goto end;
736                 }
737
738         if (key_file == NULL)
739                 key_file = cert_file;
740
741
742         if (key_file)
743
744                 {
745
746                 key = load_key(bio_err, key_file, key_format, 0, pass, e,
747                                "client certificate private key file");
748                 if (!key)
749                         {
750                         ERR_print_errors(bio_err);
751                         goto end;
752                         }
753
754                 }
755
756         if (cert_file)
757
758                 {
759                 cert = load_cert(bio_err,cert_file,cert_format,
760                                 NULL, e, "client certificate file");
761
762                 if (!cert)
763                         {
764                         ERR_print_errors(bio_err);
765                         goto end;
766                         }
767                 }
768
769         if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL
770                 && !RAND_status())
771                 {
772                 BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n");
773                 }
774         if (inrand != NULL)
775                 BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
776                         app_RAND_load_files(inrand));
777
778         if (bio_c_out == NULL)
779                 {
780                 if (c_quiet && !c_debug && !c_msg)
781                         {
782                         bio_c_out=BIO_new(BIO_s_null());
783                         }
784                 else
785                         {
786                         if (bio_c_out == NULL)
787                                 bio_c_out=BIO_new_fp(stdout,BIO_NOCLOSE);
788                         }
789                 }
790
791         ctx=SSL_CTX_new(meth);
792         if (ctx == NULL)
793                 {
794                 ERR_print_errors(bio_err);
795                 goto end;
796                 }
797
798 #ifndef OPENSSL_NO_ENGINE
799         if (ssl_client_engine)
800                 {
801                 if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine))
802                         {
803                         BIO_puts(bio_err, "Error setting client auth engine\n");
804                         ERR_print_errors(bio_err);
805                         ENGINE_free(ssl_client_engine);
806                         goto end;
807                         }
808                 ENGINE_free(ssl_client_engine);
809                 }
810 #endif
811
812 #ifndef OPENSSL_NO_PSK
813         if (psk_key != NULL)
814                 {
815                 if (c_debug)
816                         BIO_printf(bio_c_out, "PSK key given, setting client callback\n");
817                 SSL_CTX_set_psk_client_callback(ctx, psk_client_cb);
818                 }
819 #endif
820         if (bugs)
821                 SSL_CTX_set_options(ctx,SSL_OP_ALL|off);
822         else
823                 SSL_CTX_set_options(ctx,off);
824         /* DTLS: partial reads end up discarding unread UDP bytes :-( 
825          * Setting read ahead solves this problem.
826          */
827         if (socket_type == SOCK_DGRAM) SSL_CTX_set_read_ahead(ctx, 1);
828
829         if (state) SSL_CTX_set_info_callback(ctx,apps_ssl_info_callback);
830         if (cipher != NULL)
831                 if(!SSL_CTX_set_cipher_list(ctx,cipher)) {
832                 BIO_printf(bio_err,"error setting cipher list\n");
833                 ERR_print_errors(bio_err);
834                 goto end;
835         }
836 #if 0
837         else
838                 SSL_CTX_set_cipher_list(ctx,getenv("SSL_CIPHER"));
839 #endif
840
841         SSL_CTX_set_verify(ctx,verify,verify_callback);
842         if (!set_cert_key_stuff(ctx,cert,key))
843                 goto end;
844
845         if ((!SSL_CTX_load_verify_locations(ctx,CAfile,CApath)) ||
846                 (!SSL_CTX_set_default_verify_paths(ctx)))
847                 {
848                 /* BIO_printf(bio_err,"error setting default verify locations\n"); */
849                 ERR_print_errors(bio_err);
850                 /* goto end; */
851                 }
852
853         store = SSL_CTX_get_cert_store(ctx);
854         X509_STORE_set_flags(store, vflags);
855 #ifndef OPENSSL_NO_TLSEXT
856         if (servername != NULL)
857                 {
858                 tlsextcbp.biodebug = bio_err;
859                 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
860                 SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp);
861                 }
862 #endif
863
864         con=SSL_new(ctx);
865         if (sess_in)
866                 {
867                 SSL_SESSION *sess;
868                 BIO *stmp = BIO_new_file(sess_in, "r");
869                 if (!stmp)
870                         {
871                         BIO_printf(bio_err, "Can't open session file %s\n",
872                                                 sess_in);
873                         ERR_print_errors(bio_err);
874                         goto end;
875                         }
876                 sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL);
877                 BIO_free(stmp);
878                 if (!sess)
879                         {
880                         BIO_printf(bio_err, "Can't open session file %s\n",
881                                                 sess_in);
882                         ERR_print_errors(bio_err);
883                         goto end;
884                         }
885                 SSL_set_session(con, sess);
886                 SSL_SESSION_free(sess);
887                 }
888 #ifndef OPENSSL_NO_TLSEXT
889         if (servername != NULL)
890                 {
891                 if (!SSL_set_tlsext_host_name(con,servername))
892                         {
893                         BIO_printf(bio_err,"Unable to set TLS servername extension.\n");
894                         ERR_print_errors(bio_err);
895                         goto end;
896                         }
897                 }
898 #endif
899 #ifndef OPENSSL_NO_KRB5
900         if (con  &&  (con->kssl_ctx = kssl_ctx_new()) != NULL)
901                 {
902                 kssl_ctx_setstring(con->kssl_ctx, KSSL_SERVER, host);
903                 }
904 #endif  /* OPENSSL_NO_KRB5  */
905 /*      SSL_set_cipher_list(con,"RC4-MD5"); */
906 #if 0
907 #ifdef TLSEXT_TYPE_opaque_prf_input
908         SSL_set_tlsext_opaque_prf_input(con, "Test client", 11);
909 #endif
910 #endif
911
912 re_start:
913
914         if (init_client(&s,host,port,socket_type) == 0)
915                 {
916                 BIO_printf(bio_err,"connect:errno=%d\n",get_last_socket_error());
917                 SHUTDOWN(s);
918                 goto end;
919                 }
920         BIO_printf(bio_c_out,"CONNECTED(%08X)\n",s);
921
922 #ifdef FIONBIO
923         if (c_nbio)
924                 {
925                 unsigned long l=1;
926                 BIO_printf(bio_c_out,"turning on non blocking io\n");
927                 if (BIO_socket_ioctl(s,FIONBIO,&l) < 0)
928                         {
929                         ERR_print_errors(bio_err);
930                         goto end;
931                         }
932                 }
933 #endif                                              
934         if (c_Pause & 0x01) con->debug=1;
935
936         if ( SSL_version(con) == DTLS1_VERSION)
937                 {
938                 struct timeval timeout;
939
940                 sbio=BIO_new_dgram(s,BIO_NOCLOSE);
941                 if (getsockname(s, &peer, (void *)&peerlen) < 0)
942                         {
943                         BIO_printf(bio_err, "getsockname:errno=%d\n",
944                                 get_last_socket_error());
945                         SHUTDOWN(s);
946                         goto end;
947                         }
948
949                 (void)BIO_ctrl_set_connected(sbio, 1, &peer);
950
951                 if (enable_timeouts)
952                         {
953                         timeout.tv_sec = 0;
954                         timeout.tv_usec = DGRAM_RCV_TIMEOUT;
955                         BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);
956                         
957                         timeout.tv_sec = 0;
958                         timeout.tv_usec = DGRAM_SND_TIMEOUT;
959                         BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
960                         }
961
962                 if (socket_mtu > 0)
963                         {
964                         SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
965                         SSL_set_mtu(con, socket_mtu);
966                         }
967                 else
968                         /* want to do MTU discovery */
969                         BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
970                 }
971         else
972                 sbio=BIO_new_socket(s,BIO_NOCLOSE);
973
974
975
976         if (nbio_test)
977                 {
978                 BIO *test;
979
980                 test=BIO_new(BIO_f_nbio_test());
981                 sbio=BIO_push(test,sbio);
982                 }
983
984         if (c_debug)
985                 {
986                 con->debug=1;
987                 BIO_set_callback(sbio,bio_dump_callback);
988                 BIO_set_callback_arg(sbio,(char *)bio_c_out);
989                 }
990         if (c_msg)
991                 {
992                 SSL_set_msg_callback(con, msg_cb);
993                 SSL_set_msg_callback_arg(con, bio_c_out);
994                 }
995 #ifndef OPENSSL_NO_TLSEXT
996         if (c_tlsextdebug)
997                 {
998                 SSL_set_tlsext_debug_callback(con, tlsext_cb);
999                 SSL_set_tlsext_debug_arg(con, bio_c_out);
1000                 }
1001         if (c_status_req)
1002                 {
1003                 SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp);
1004                 SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb);
1005                 SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out);
1006 #if 0
1007 {
1008 STACK_OF(OCSP_RESPID) *ids = sk_OCSP_RESPID_new_null();
1009 OCSP_RESPID *id = OCSP_RESPID_new();
1010 id->value.byKey = ASN1_OCTET_STRING_new();
1011 id->type = V_OCSP_RESPID_KEY;
1012 ASN1_STRING_set(id->value.byKey, "Hello World", -1);
1013 sk_OCSP_RESPID_push(ids, id);
1014 SSL_set_tlsext_status_ids(con, ids);
1015 }
1016 #endif
1017                 }
1018 #endif
1019
1020         SSL_set_bio(con,sbio,sbio);
1021         SSL_set_connect_state(con);
1022
1023         /* ok, lets connect */
1024         width=SSL_get_fd(con)+1;
1025
1026         read_tty=1;
1027         write_tty=0;
1028         tty_on=0;
1029         read_ssl=1;
1030         write_ssl=1;
1031         
1032         cbuf_len=0;
1033         cbuf_off=0;
1034         sbuf_len=0;
1035         sbuf_off=0;
1036
1037         /* This is an ugly hack that does a lot of assumptions */
1038         /* We do have to handle multi-line responses which may come
1039            in a single packet or not. We therefore have to use
1040            BIO_gets() which does need a buffering BIO. So during
1041            the initial chitchat we do push a buffering BIO into the
1042            chain that is removed again later on to not disturb the
1043            rest of the s_client operation. */
1044         if (starttls_proto == PROTO_SMTP)
1045                 {
1046                 int foundit=0;
1047                 BIO *fbio = BIO_new(BIO_f_buffer());
1048                 BIO_push(fbio, sbio);
1049                 /* wait for multi-line response to end from SMTP */
1050                 do
1051                         {
1052                         mbuf_len = BIO_gets(fbio,mbuf,BUFSIZZ);
1053                         }
1054                 while (mbuf_len>3 && mbuf[3]=='-');
1055                 /* STARTTLS command requires EHLO... */
1056                 BIO_printf(fbio,"EHLO openssl.client.net\r\n");
1057                 (void)BIO_flush(fbio);
1058                 /* wait for multi-line response to end EHLO SMTP response */
1059                 do
1060                         {
1061                         mbuf_len = BIO_gets(fbio,mbuf,BUFSIZZ);
1062                         if (strstr(mbuf,"STARTTLS"))
1063                                 foundit=1;
1064                         }
1065                 while (mbuf_len>3 && mbuf[3]=='-');
1066                 (void)BIO_flush(fbio);
1067                 BIO_pop(fbio);
1068                 BIO_free(fbio);
1069                 if (!foundit)
1070                         BIO_printf(bio_err,
1071                                    "didn't found starttls in server response,"
1072                                    " try anyway...\n");
1073                 BIO_printf(sbio,"STARTTLS\r\n");
1074                 BIO_read(sbio,sbuf,BUFSIZZ);
1075                 }
1076         else if (starttls_proto == PROTO_POP3)
1077                 {
1078                 BIO_read(sbio,mbuf,BUFSIZZ);
1079                 BIO_printf(sbio,"STLS\r\n");
1080                 BIO_read(sbio,sbuf,BUFSIZZ);
1081                 }
1082         else if (starttls_proto == PROTO_IMAP)
1083                 {
1084                 int foundit=0;
1085                 BIO *fbio = BIO_new(BIO_f_buffer());
1086                 BIO_push(fbio, sbio);
1087                 BIO_gets(fbio,mbuf,BUFSIZZ);
1088                 /* STARTTLS command requires CAPABILITY... */
1089                 BIO_printf(fbio,". CAPABILITY\r\n");
1090                 (void)BIO_flush(fbio);
1091                 /* wait for multi-line CAPABILITY response */
1092                 do
1093                         {
1094                         mbuf_len = BIO_gets(fbio,mbuf,BUFSIZZ);
1095                         if (strstr(mbuf,"STARTTLS"))
1096                                 foundit=1;
1097                         }
1098                 while (mbuf_len>3 && mbuf[0]!='.');
1099                 (void)BIO_flush(fbio);
1100                 BIO_pop(fbio);
1101                 BIO_free(fbio);
1102                 if (!foundit)
1103                         BIO_printf(bio_err,
1104                                    "didn't found STARTTLS in server response,"
1105                                    " try anyway...\n");
1106                 BIO_printf(sbio,". STARTTLS\r\n");
1107                 BIO_read(sbio,sbuf,BUFSIZZ);
1108                 }
1109         else if (starttls_proto == PROTO_FTP)
1110                 {
1111                 BIO *fbio = BIO_new(BIO_f_buffer());
1112                 BIO_push(fbio, sbio);
1113                 /* wait for multi-line response to end from FTP */
1114                 do
1115                         {
1116                         mbuf_len = BIO_gets(fbio,mbuf,BUFSIZZ);
1117                         }
1118                 while (mbuf_len>3 && mbuf[3]=='-');
1119                 (void)BIO_flush(fbio);
1120                 BIO_pop(fbio);
1121                 BIO_free(fbio);
1122                 BIO_printf(sbio,"AUTH TLS\r\n");
1123                 BIO_read(sbio,sbuf,BUFSIZZ);
1124                 }
1125         if (starttls_proto == PROTO_XMPP)
1126                 {
1127                 int seen = 0;
1128                 BIO_printf(sbio,"<stream:stream "
1129                     "xmlns:stream='http://etherx.jabber.org/streams' "
1130                     "xmlns='jabber:client' to='%s' version='1.0'>", host);
1131                 seen = BIO_read(sbio,mbuf,BUFSIZZ);
1132                 mbuf[seen] = 0;
1133                 while (!strstr(mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'"))
1134                         {
1135                         if (strstr(mbuf, "/stream:features>"))
1136                                 goto shut;
1137                         seen = BIO_read(sbio,mbuf,BUFSIZZ);
1138                         mbuf[seen] = 0;
1139                         }
1140                 BIO_printf(sbio, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
1141                 seen = BIO_read(sbio,sbuf,BUFSIZZ);
1142                 sbuf[seen] = 0;
1143                 if (!strstr(sbuf, "<proceed"))
1144                         goto shut;
1145                 mbuf[0] = 0;
1146                 }
1147
1148         for (;;)
1149                 {
1150                 FD_ZERO(&readfds);
1151                 FD_ZERO(&writefds);
1152
1153                 if (SSL_in_init(con) && !SSL_total_renegotiations(con))
1154                         {
1155                         in_init=1;
1156                         tty_on=0;
1157                         }
1158                 else
1159                         {
1160                         tty_on=1;
1161                         if (in_init)
1162                                 {
1163                                 in_init=0;
1164 #if 0 /* This test doesn't really work as intended (needs to be fixed) */
1165 #ifndef OPENSSL_NO_TLSEXT
1166                                 if (servername != NULL && !SSL_session_reused(con))
1167                                         {
1168                                         BIO_printf(bio_c_out,"Server did %sacknowledge servername extension.\n",tlsextcbp.ack?"":"not ");
1169                                         }
1170 #endif
1171 #endif
1172                                 if (sess_out)
1173                                         {
1174                                         BIO *stmp = BIO_new_file(sess_out, "w");
1175                                         if (stmp)
1176                                                 {
1177                                                 PEM_write_bio_SSL_SESSION(stmp, SSL_get_session(con));
1178                                                 BIO_free(stmp);
1179                                                 }
1180                                         else 
1181                                                 BIO_printf(bio_err, "Error writing session file %s\n", sess_out);
1182                                         }
1183                                 print_stuff(bio_c_out,con,full_log);
1184                                 if (full_log > 0) full_log--;
1185
1186                                 if (starttls_proto)
1187                                         {
1188                                         BIO_printf(bio_err,"%s",mbuf);
1189                                         /* We don't need to know any more */
1190                                         starttls_proto = PROTO_OFF;
1191                                         }
1192
1193                                 if (reconnect)
1194                                         {
1195                                         reconnect--;
1196                                         BIO_printf(bio_c_out,"drop connection and then reconnect\n");
1197                                         SSL_shutdown(con);
1198                                         SSL_set_connect_state(con);
1199                                         SHUTDOWN(SSL_get_fd(con));
1200                                         goto re_start;
1201                                         }
1202                                 }
1203                         }
1204
1205                 ssl_pending = read_ssl && SSL_pending(con);
1206
1207                 if (!ssl_pending)
1208                         {
1209 #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_NETWARE) && !defined (OPENSSL_SYS_BEOS_R5)
1210                         if (tty_on)
1211                                 {
1212                                 if (read_tty)  openssl_fdset(fileno(stdin),&readfds);
1213                                 if (write_tty) openssl_fdset(fileno(stdout),&writefds);
1214                                 }
1215                         if (read_ssl)
1216                                 openssl_fdset(SSL_get_fd(con),&readfds);
1217                         if (write_ssl)
1218                                 openssl_fdset(SSL_get_fd(con),&writefds);
1219 #else
1220                         if(!tty_on || !write_tty) {
1221                                 if (read_ssl)
1222                                         openssl_fdset(SSL_get_fd(con),&readfds);
1223                                 if (write_ssl)
1224                                         openssl_fdset(SSL_get_fd(con),&writefds);
1225                         }
1226 #endif
1227 /*                      printf("mode tty(%d %d%d) ssl(%d%d)\n",
1228                                 tty_on,read_tty,write_tty,read_ssl,write_ssl);*/
1229
1230                         /* Note: under VMS with SOCKETSHR the second parameter
1231                          * is currently of type (int *) whereas under other
1232                          * systems it is (void *) if you don't have a cast it
1233                          * will choke the compiler: if you do have a cast then
1234                          * you can either go for (int *) or (void *).
1235                          */
1236 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
1237                         /* Under Windows/DOS we make the assumption that we can
1238                          * always write to the tty: therefore if we need to
1239                          * write to the tty we just fall through. Otherwise
1240                          * we timeout the select every second and see if there
1241                          * are any keypresses. Note: this is a hack, in a proper
1242                          * Windows application we wouldn't do this.
1243                          */
1244                         i=0;
1245                         if(!write_tty) {
1246                                 if(read_tty) {
1247                                         tv.tv_sec = 1;
1248                                         tv.tv_usec = 0;
1249                                         i=select(width,(void *)&readfds,(void *)&writefds,
1250                                                  NULL,&tv);
1251 #if defined(OPENSSL_SYS_WINCE) || defined(OPENSSL_SYS_MSDOS)
1252                                         if(!i && (!_kbhit() || !read_tty) ) continue;
1253 #else
1254                                         if(!i && (!((_kbhit()) || (WAIT_OBJECT_0 == WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 0))) || !read_tty) ) continue;
1255 #endif
1256                                 } else  i=select(width,(void *)&readfds,(void *)&writefds,
1257                                          NULL,NULL);
1258                         }
1259 #elif defined(OPENSSL_SYS_NETWARE)
1260                         if(!write_tty) {
1261                                 if(read_tty) {
1262                                         tv.tv_sec = 1;
1263                                         tv.tv_usec = 0;
1264                                         i=select(width,(void *)&readfds,(void *)&writefds,
1265                                                 NULL,&tv);
1266                                 } else  i=select(width,(void *)&readfds,(void *)&writefds,
1267                                         NULL,NULL);
1268                         }
1269 #elif defined(OPENSSL_SYS_BEOS_R5)
1270                         /* Under BeOS-R5 the situation is similar to DOS */
1271                         i=0;
1272                         stdin_set = 0;
1273                         (void)fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
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                                         if (read(fileno(stdin), sbuf, 0) >= 0)
1281                                                 stdin_set = 1;
1282                                         if (!i && (stdin_set != 1 || !read_tty))
1283                                                 continue;
1284                                 } else  i=select(width,(void *)&readfds,(void *)&writefds,
1285                                          NULL,NULL);
1286                         }
1287                         (void)fcntl(fileno(stdin), F_SETFL, 0);
1288 #else
1289                         i=select(width,(void *)&readfds,(void *)&writefds,
1290                                  NULL,NULL);
1291 #endif
1292                         if ( i < 0)
1293                                 {
1294                                 BIO_printf(bio_err,"bad select %d\n",
1295                                 get_last_socket_error());
1296                                 goto shut;
1297                                 /* goto end; */
1298                                 }
1299                         }
1300
1301                 if (!ssl_pending && FD_ISSET(SSL_get_fd(con),&writefds))
1302                         {
1303                         k=SSL_write(con,&(cbuf[cbuf_off]),
1304                                 (unsigned int)cbuf_len);
1305                         switch (SSL_get_error(con,k))
1306                                 {
1307                         case SSL_ERROR_NONE:
1308                                 cbuf_off+=k;
1309                                 cbuf_len-=k;
1310                                 if (k <= 0) goto end;
1311                                 /* we have done a  write(con,NULL,0); */
1312                                 if (cbuf_len <= 0)
1313                                         {
1314                                         read_tty=1;
1315                                         write_ssl=0;
1316                                         }
1317                                 else /* if (cbuf_len > 0) */
1318                                         {
1319                                         read_tty=0;
1320                                         write_ssl=1;
1321                                         }
1322                                 break;
1323                         case SSL_ERROR_WANT_WRITE:
1324                                 BIO_printf(bio_c_out,"write W BLOCK\n");
1325                                 write_ssl=1;
1326                                 read_tty=0;
1327                                 break;
1328                         case SSL_ERROR_WANT_READ:
1329                                 BIO_printf(bio_c_out,"write R BLOCK\n");
1330                                 write_tty=0;
1331                                 read_ssl=1;
1332                                 write_ssl=0;
1333                                 break;
1334                         case SSL_ERROR_WANT_X509_LOOKUP:
1335                                 BIO_printf(bio_c_out,"write X BLOCK\n");
1336                                 break;
1337                         case SSL_ERROR_ZERO_RETURN:
1338                                 if (cbuf_len != 0)
1339                                         {
1340                                         BIO_printf(bio_c_out,"shutdown\n");
1341                                         ret = 0;
1342                                         goto shut;
1343                                         }
1344                                 else
1345                                         {
1346                                         read_tty=1;
1347                                         write_ssl=0;
1348                                         break;
1349                                         }
1350                                 
1351                         case SSL_ERROR_SYSCALL:
1352                                 if ((k != 0) || (cbuf_len != 0))
1353                                         {
1354                                         BIO_printf(bio_err,"write:errno=%d\n",
1355                                                 get_last_socket_error());
1356                                         goto shut;
1357                                         }
1358                                 else
1359                                         {
1360                                         read_tty=1;
1361                                         write_ssl=0;
1362                                         }
1363                                 break;
1364                         case SSL_ERROR_SSL:
1365                                 ERR_print_errors(bio_err);
1366                                 goto shut;
1367                                 }
1368                         }
1369 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_BEOS_R5)
1370                 /* Assume Windows/DOS/BeOS can always write */
1371                 else if (!ssl_pending && write_tty)
1372 #else
1373                 else if (!ssl_pending && FD_ISSET(fileno(stdout),&writefds))
1374 #endif
1375                         {
1376 #ifdef CHARSET_EBCDIC
1377                         ascii2ebcdic(&(sbuf[sbuf_off]),&(sbuf[sbuf_off]),sbuf_len);
1378 #endif
1379                         i=raw_write_stdout(&(sbuf[sbuf_off]),sbuf_len);
1380
1381                         if (i <= 0)
1382                                 {
1383                                 BIO_printf(bio_c_out,"DONE\n");
1384                                 ret = 0;
1385                                 goto shut;
1386                                 /* goto end; */
1387                                 }
1388
1389                         sbuf_len-=i;;
1390                         sbuf_off+=i;
1391                         if (sbuf_len <= 0)
1392                                 {
1393                                 read_ssl=1;
1394                                 write_tty=0;
1395                                 }
1396                         }
1397                 else if (ssl_pending || FD_ISSET(SSL_get_fd(con),&readfds))
1398                         {
1399 #ifdef RENEG
1400 { static int iiii; if (++iiii == 52) { SSL_renegotiate(con); iiii=0; } }
1401 #endif
1402 #if 1
1403                         k=SSL_read(con,sbuf,1024 /* BUFSIZZ */ );
1404 #else
1405 /* Demo for pending and peek :-) */
1406                         k=SSL_read(con,sbuf,16);
1407 { char zbuf[10240]; 
1408 printf("read=%d pending=%d peek=%d\n",k,SSL_pending(con),SSL_peek(con,zbuf,10240));
1409 }
1410 #endif
1411
1412                         switch (SSL_get_error(con,k))
1413                                 {
1414                         case SSL_ERROR_NONE:
1415                                 if (k <= 0)
1416                                         goto end;
1417                                 sbuf_off=0;
1418                                 sbuf_len=k;
1419
1420                                 read_ssl=0;
1421                                 write_tty=1;
1422                                 break;
1423                         case SSL_ERROR_WANT_WRITE:
1424                                 BIO_printf(bio_c_out,"read W BLOCK\n");
1425                                 write_ssl=1;
1426                                 read_tty=0;
1427                                 break;
1428                         case SSL_ERROR_WANT_READ:
1429                                 BIO_printf(bio_c_out,"read R BLOCK\n");
1430                                 write_tty=0;
1431                                 read_ssl=1;
1432                                 if ((read_tty == 0) && (write_ssl == 0))
1433                                         write_ssl=1;
1434                                 break;
1435                         case SSL_ERROR_WANT_X509_LOOKUP:
1436                                 BIO_printf(bio_c_out,"read X BLOCK\n");
1437                                 break;
1438                         case SSL_ERROR_SYSCALL:
1439                                 ret=get_last_socket_error();
1440                                 BIO_printf(bio_err,"read:errno=%d\n",ret);
1441                                 goto shut;
1442                         case SSL_ERROR_ZERO_RETURN:
1443                                 BIO_printf(bio_c_out,"closed\n");
1444                                 ret=0;
1445                                 goto shut;
1446                         case SSL_ERROR_SSL:
1447                                 ERR_print_errors(bio_err);
1448                                 goto shut;
1449                                 /* break; */
1450                                 }
1451                         }
1452
1453 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
1454 #if defined(OPENSSL_SYS_WINCE) || defined(OPENSSL_SYS_MSDOS)
1455                 else if (_kbhit())
1456 #else
1457                 else if ((_kbhit()) || (WAIT_OBJECT_0 == WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 0)))
1458 #endif
1459 #elif defined (OPENSSL_SYS_NETWARE)
1460                 else if (_kbhit())
1461 #elif defined(OPENSSL_SYS_BEOS_R5)
1462                 else if (stdin_set)
1463 #else
1464                 else if (FD_ISSET(fileno(stdin),&readfds))
1465 #endif
1466                         {
1467                         if (crlf)
1468                                 {
1469                                 int j, lf_num;
1470
1471                                 i=raw_read_stdin(cbuf,BUFSIZZ/2);
1472                                 lf_num = 0;
1473                                 /* both loops are skipped when i <= 0 */
1474                                 for (j = 0; j < i; j++)
1475                                         if (cbuf[j] == '\n')
1476                                                 lf_num++;
1477                                 for (j = i-1; j >= 0; j--)
1478                                         {
1479                                         cbuf[j+lf_num] = cbuf[j];
1480                                         if (cbuf[j] == '\n')
1481                                                 {
1482                                                 lf_num--;
1483                                                 i++;
1484                                                 cbuf[j+lf_num] = '\r';
1485                                                 }
1486                                         }
1487                                 assert(lf_num == 0);
1488                                 }
1489                         else
1490                                 i=raw_read_stdin(cbuf,BUFSIZZ);
1491
1492                         if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q')))
1493                                 {
1494                                 BIO_printf(bio_err,"DONE\n");
1495                                 ret=0;
1496                                 goto shut;
1497                                 }
1498
1499                         if ((!c_ign_eof) && (cbuf[0] == 'R'))
1500                                 {
1501                                 BIO_printf(bio_err,"RENEGOTIATING\n");
1502                                 SSL_renegotiate(con);
1503                                 cbuf_len=0;
1504                                 }
1505                         else
1506                                 {
1507                                 cbuf_len=i;
1508                                 cbuf_off=0;
1509 #ifdef CHARSET_EBCDIC
1510                                 ebcdic2ascii(cbuf, cbuf, i);
1511 #endif
1512                                 }
1513
1514                         write_ssl=1;
1515                         read_tty=0;
1516                         }
1517                 }
1518
1519         ret=0;
1520 shut:
1521         if (in_init)
1522                 print_stuff(bio_c_out,con,full_log);
1523         SSL_shutdown(con);
1524         SHUTDOWN(SSL_get_fd(con));
1525 end:
1526         if (con != NULL)
1527                 {
1528                 if (prexit != 0)
1529                         print_stuff(bio_c_out,con,1);
1530                 SSL_free(con);
1531                 }
1532         if (ctx != NULL) SSL_CTX_free(ctx);
1533         if (cert)
1534                 X509_free(cert);
1535         if (key)
1536                 EVP_PKEY_free(key);
1537         if (pass)
1538                 OPENSSL_free(pass);
1539         if (cbuf != NULL) { OPENSSL_cleanse(cbuf,BUFSIZZ); OPENSSL_free(cbuf); }
1540         if (sbuf != NULL) { OPENSSL_cleanse(sbuf,BUFSIZZ); OPENSSL_free(sbuf); }
1541         if (mbuf != NULL) { OPENSSL_cleanse(mbuf,BUFSIZZ); OPENSSL_free(mbuf); }
1542         if (bio_c_out != NULL)
1543                 {
1544                 BIO_free(bio_c_out);
1545                 bio_c_out=NULL;
1546                 }
1547         apps_shutdown();
1548         OPENSSL_EXIT(ret);
1549         }
1550
1551
1552 static void print_stuff(BIO *bio, SSL *s, int full)
1553         {
1554         X509 *peer=NULL;
1555         char *p;
1556         static const char *space="                ";
1557         char buf[BUFSIZ];
1558         STACK_OF(X509) *sk;
1559         STACK_OF(X509_NAME) *sk2;
1560         const SSL_CIPHER *c;
1561         X509_NAME *xn;
1562         int j,i;
1563 #ifndef OPENSSL_NO_COMP
1564         const COMP_METHOD *comp, *expansion;
1565 #endif
1566
1567         if (full)
1568                 {
1569                 int got_a_chain = 0;
1570
1571                 sk=SSL_get_peer_cert_chain(s);
1572                 if (sk != NULL)
1573                         {
1574                         got_a_chain = 1; /* we don't have it for SSL2 (yet) */
1575
1576                         BIO_printf(bio,"---\nCertificate chain\n");
1577                         for (i=0; i<sk_X509_num(sk); i++)
1578                                 {
1579                                 X509_NAME_oneline(X509_get_subject_name(
1580                                         sk_X509_value(sk,i)),buf,sizeof buf);
1581                                 BIO_printf(bio,"%2d s:%s\n",i,buf);
1582                                 X509_NAME_oneline(X509_get_issuer_name(
1583                                         sk_X509_value(sk,i)),buf,sizeof buf);
1584                                 BIO_printf(bio,"   i:%s\n",buf);
1585                                 if (c_showcerts)
1586                                         PEM_write_bio_X509(bio,sk_X509_value(sk,i));
1587                                 }
1588                         }
1589
1590                 BIO_printf(bio,"---\n");
1591                 peer=SSL_get_peer_certificate(s);
1592                 if (peer != NULL)
1593                         {
1594                         BIO_printf(bio,"Server certificate\n");
1595                         if (!(c_showcerts && got_a_chain)) /* Redundant if we showed the whole chain */
1596                                 PEM_write_bio_X509(bio,peer);
1597                         X509_NAME_oneline(X509_get_subject_name(peer),
1598                                 buf,sizeof buf);
1599                         BIO_printf(bio,"subject=%s\n",buf);
1600                         X509_NAME_oneline(X509_get_issuer_name(peer),
1601                                 buf,sizeof buf);
1602                         BIO_printf(bio,"issuer=%s\n",buf);
1603                         }
1604                 else
1605                         BIO_printf(bio,"no peer certificate available\n");
1606
1607                 sk2=SSL_get_client_CA_list(s);
1608                 if ((sk2 != NULL) && (sk_X509_NAME_num(sk2) > 0))
1609                         {
1610                         BIO_printf(bio,"---\nAcceptable client certificate CA names\n");
1611                         for (i=0; i<sk_X509_NAME_num(sk2); i++)
1612                                 {
1613                                 xn=sk_X509_NAME_value(sk2,i);
1614                                 X509_NAME_oneline(xn,buf,sizeof(buf));
1615                                 BIO_write(bio,buf,strlen(buf));
1616                                 BIO_write(bio,"\n",1);
1617                                 }
1618                         }
1619                 else
1620                         {
1621                         BIO_printf(bio,"---\nNo client certificate CA names sent\n");
1622                         }
1623                 p=SSL_get_shared_ciphers(s,buf,sizeof buf);
1624                 if (p != NULL)
1625                         {
1626                         /* This works only for SSL 2.  In later protocol
1627                          * versions, the client does not know what other
1628                          * ciphers (in addition to the one to be used
1629                          * in the current connection) the server supports. */
1630
1631                         BIO_printf(bio,"---\nCiphers common between both SSL endpoints:\n");
1632                         j=i=0;
1633                         while (*p)
1634                                 {
1635                                 if (*p == ':')
1636                                         {
1637                                         BIO_write(bio,space,15-j%25);
1638                                         i++;
1639                                         j=0;
1640                                         BIO_write(bio,((i%3)?" ":"\n"),1);
1641                                         }
1642                                 else
1643                                         {
1644                                         BIO_write(bio,p,1);
1645                                         j++;
1646                                         }
1647                                 p++;
1648                                 }
1649                         BIO_write(bio,"\n",1);
1650                         }
1651
1652                 BIO_printf(bio,"---\nSSL handshake has read %ld bytes and written %ld bytes\n",
1653                         BIO_number_read(SSL_get_rbio(s)),
1654                         BIO_number_written(SSL_get_wbio(s)));
1655                 }
1656         BIO_printf(bio,((s->hit)?"---\nReused, ":"---\nNew, "));
1657         c=SSL_get_current_cipher(s);
1658         BIO_printf(bio,"%s, Cipher is %s\n",
1659                 SSL_CIPHER_get_version(c),
1660                 SSL_CIPHER_get_name(c));
1661         if (peer != NULL) {
1662                 EVP_PKEY *pktmp;
1663                 pktmp = X509_get_pubkey(peer);
1664                 BIO_printf(bio,"Server public key is %d bit\n",
1665                                                          EVP_PKEY_bits(pktmp));
1666                 EVP_PKEY_free(pktmp);
1667         }
1668 #ifndef OPENSSL_NO_COMP
1669         comp=SSL_get_current_compression(s);
1670         expansion=SSL_get_current_expansion(s);
1671         BIO_printf(bio,"Compression: %s\n",
1672                 comp ? SSL_COMP_get_name(comp) : "NONE");
1673         BIO_printf(bio,"Expansion: %s\n",
1674                 expansion ? SSL_COMP_get_name(expansion) : "NONE");
1675 #endif
1676         SSL_SESSION_print(bio,SSL_get_session(s));
1677         BIO_printf(bio,"---\n");
1678         if (peer != NULL)
1679                 X509_free(peer);
1680         /* flush, or debugging output gets mixed with http response */
1681         (void)BIO_flush(bio);
1682         }
1683
1684 #ifndef OPENSSL_NO_TLSEXT
1685
1686 static int ocsp_resp_cb(SSL *s, void *arg)
1687         {
1688         const unsigned char *p;
1689         int len;
1690         OCSP_RESPONSE *rsp;
1691         len = SSL_get_tlsext_status_ocsp_resp(s, &p);
1692         BIO_puts(arg, "OCSP response: ");
1693         if (!p)
1694                 {
1695                 BIO_puts(arg, "no response sent\n");
1696                 return 1;
1697                 }
1698         rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
1699         if (!rsp)
1700                 {
1701                 BIO_puts(arg, "response parse error\n");
1702                 BIO_dump_indent(arg, (char *)p, len, 4);
1703                 return 0;
1704                 }
1705         BIO_puts(arg, "\n======================================\n");
1706         OCSP_RESPONSE_print(arg, rsp, 0);
1707         BIO_puts(arg, "======================================\n");
1708         OCSP_RESPONSE_free(rsp);
1709         return 1;
1710         }
1711
1712 #endif