Add minimum POP3 STLS hack to s_client.c (as was provided for STARTTLS before)
[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-2001 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 #include <assert.h>
113 #include <stdio.h>
114 #include <stdlib.h>
115 #include <string.h>
116 #include <openssl/e_os2.h>
117 #ifdef OPENSSL_NO_STDIO
118 #define APPS_WIN16
119 #endif
120
121 /* With IPv6, it looks like Digital has mixed up the proper order of
122    recursive header file inclusion, resulting in the compiler complaining
123    that u_int isn't defined, but only if _POSIX_C_SOURCE is defined, which
124    is needed to have fileno() declared correctly...  So let's define u_int */
125 #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT)
126 #define __U_INT
127 typedef unsigned int u_int;
128 #endif
129
130 #define USE_SOCKETS
131 #include "apps.h"
132 #include <openssl/x509.h>
133 #include <openssl/ssl.h>
134 #include <openssl/err.h>
135 #include <openssl/pem.h>
136 #include <openssl/rand.h>
137 #include "s_apps.h"
138
139 #ifdef OPENSSL_SYS_WINDOWS
140 #include <conio.h>
141 #endif
142
143 #ifdef OPENSSL_SYS_WINCE
144 /* Windows CE incorrectly defines fileno as returning void*, so to avoid problems below... */
145 #ifdef fileno
146 #undef fileno
147 #endif
148 #define fileno(a) (int)_fileno(a)
149 #endif
150
151
152 #if (defined(OPENSSL_SYS_VMS) && __VMS_VER < 70000000)
153 /* FIONBIO used as a switch to enable ioctl, and that isn't in VMS < 7.0 */
154 #undef FIONBIO
155 #endif
156
157 #undef PROG
158 #define PROG    s_client_main
159
160 /*#define SSL_HOST_NAME "www.netscape.com" */
161 /*#define SSL_HOST_NAME "193.118.187.102" */
162 #define SSL_HOST_NAME   "localhost"
163
164 /*#define TEST_CERT "client.pem" */ /* no default cert. */
165
166 #undef BUFSIZZ
167 #define BUFSIZZ 1024*8
168
169 extern int verify_depth;
170 extern int verify_error;
171
172 #ifdef FIONBIO
173 static int c_nbio=0;
174 #endif
175 static int c_Pause=0;
176 static int c_debug=0;
177 static int c_msg=0;
178 static int c_showcerts=0;
179
180 static void sc_usage(void);
181 static void print_stuff(BIO *berr,SSL *con,int full);
182 static BIO *bio_c_out=NULL;
183 static int c_quiet=0;
184 static int c_ign_eof=0;
185
186 static void sc_usage(void)
187         {
188         BIO_printf(bio_err,"usage: s_client args\n");
189         BIO_printf(bio_err,"\n");
190         BIO_printf(bio_err," -host host     - use -connect instead\n");
191         BIO_printf(bio_err," -port port     - use -connect instead\n");
192         BIO_printf(bio_err," -connect host:port - who to connect to (default is %s:%s)\n",SSL_HOST_NAME,PORT_STR);
193
194         BIO_printf(bio_err," -verify arg   - turn on peer certificate verification\n");
195         BIO_printf(bio_err," -cert arg     - certificate file to use, PEM format assumed\n");
196         BIO_printf(bio_err," -key arg      - Private key file to use, PEM format assumed, in cert file if\n");
197         BIO_printf(bio_err,"                 not specified but cert file is.\n");
198         BIO_printf(bio_err," -CApath arg   - PEM format directory of CA's\n");
199         BIO_printf(bio_err," -CAfile arg   - PEM format file of CA's\n");
200         BIO_printf(bio_err," -reconnect    - Drop and re-make the connection with the same Session-ID\n");
201         BIO_printf(bio_err," -pause        - sleep(1) after each read(2) and write(2) system call\n");
202         BIO_printf(bio_err," -showcerts    - show all certificates in the chain\n");
203         BIO_printf(bio_err," -debug        - extra output\n");
204         BIO_printf(bio_err," -msg          - Show protocol messages\n");
205         BIO_printf(bio_err," -nbio_test    - more ssl protocol testing\n");
206         BIO_printf(bio_err," -state        - print the 'ssl' states\n");
207 #ifdef FIONBIO
208         BIO_printf(bio_err," -nbio         - Run with non-blocking IO\n");
209 #endif
210         BIO_printf(bio_err," -crlf         - convert LF from terminal into CRLF\n");
211         BIO_printf(bio_err," -quiet        - no s_client output\n");
212         BIO_printf(bio_err," -ign_eof      - ignore input eof (default when -quiet)\n");
213         BIO_printf(bio_err," -ssl2         - just use SSLv2\n");
214         BIO_printf(bio_err," -ssl3         - just use SSLv3\n");
215         BIO_printf(bio_err," -tls1         - just use TLSv1\n");
216         BIO_printf(bio_err," -no_tls1/-no_ssl3/-no_ssl2 - turn off that protocol\n");
217         BIO_printf(bio_err," -bugs         - Switch on all SSL implementation bug workarounds\n");
218         BIO_printf(bio_err," -serverpref   - Use server's cipher preferences (only SSLv2)\n");
219         BIO_printf(bio_err," -cipher       - preferred cipher to use, use the 'openssl ciphers'\n");
220         BIO_printf(bio_err,"                 command to see what is available\n");
221         BIO_printf(bio_err," -starttls prot - use the STARTTLS command before starting TLS\n");
222         BIO_printf(bio_err,"                 for those protocols that support it, where\n");
223         BIO_printf(bio_err,"                 'prot' defines which one to assume.  Currently,\n");
224         BIO_printf(bio_err,"                 only \"smtp\" and \"pop3\" are supported.\n");
225 #ifndef OPENSSL_NO_ENGINE
226         BIO_printf(bio_err," -engine id    - Initialise and use the specified engine\n");
227 #endif
228         BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
229
230         }
231
232 int MAIN(int, char **);
233
234 int MAIN(int argc, char **argv)
235         {
236         int off=0;
237         SSL *con=NULL,*con2=NULL;
238         X509_STORE *store = NULL;
239         int s,k,width,state=0;
240         char *cbuf=NULL,*sbuf=NULL,*mbuf=NULL;
241         int cbuf_len,cbuf_off;
242         int sbuf_len,sbuf_off;
243         fd_set readfds,writefds;
244         short port=PORT;
245         int full_log=1;
246         char *host=SSL_HOST_NAME;
247         char *cert_file=NULL,*key_file=NULL;
248         char *CApath=NULL,*CAfile=NULL,*cipher=NULL;
249         int reconnect=0,badop=0,verify=SSL_VERIFY_NONE,bugs=0;
250         int crlf=0;
251         int write_tty,read_tty,write_ssl,read_ssl,tty_on,ssl_pending;
252         SSL_CTX *ctx=NULL;
253         int ret=1,in_init=1,i,nbio_test=0;
254         int starttls_proto = 0;
255         int prexit = 0, vflags = 0;
256         SSL_METHOD *meth=NULL;
257         BIO *sbio;
258         char *inrand=NULL;
259 #ifndef OPENSSL_NO_ENGINE
260         char *engine_id=NULL;
261         ENGINE *e=NULL;
262 #endif
263 #ifdef OPENSSL_SYS_WINDOWS
264         struct timeval tv;
265 #endif
266
267 #if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3)
268         meth=SSLv23_client_method();
269 #elif !defined(OPENSSL_NO_SSL3)
270         meth=SSLv3_client_method();
271 #elif !defined(OPENSSL_NO_SSL2)
272         meth=SSLv2_client_method();
273 #endif
274
275         apps_startup();
276         c_Pause=0;
277         c_quiet=0;
278         c_ign_eof=0;
279         c_debug=0;
280         c_msg=0;
281         c_showcerts=0;
282
283         if (bio_err == NULL)
284                 bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
285
286         if (!load_config(bio_err, NULL))
287                 goto end;
288
289         if (    ((cbuf=OPENSSL_malloc(BUFSIZZ)) == NULL) ||
290                 ((sbuf=OPENSSL_malloc(BUFSIZZ)) == NULL) ||
291                 ((mbuf=OPENSSL_malloc(BUFSIZZ)) == NULL))
292                 {
293                 BIO_printf(bio_err,"out of memory\n");
294                 goto end;
295                 }
296
297         verify_depth=0;
298         verify_error=X509_V_OK;
299 #ifdef FIONBIO
300         c_nbio=0;
301 #endif
302
303         argc--;
304         argv++;
305         while (argc >= 1)
306                 {
307                 if      (strcmp(*argv,"-host") == 0)
308                         {
309                         if (--argc < 1) goto bad;
310                         host= *(++argv);
311                         }
312                 else if (strcmp(*argv,"-port") == 0)
313                         {
314                         if (--argc < 1) goto bad;
315                         port=atoi(*(++argv));
316                         if (port == 0) goto bad;
317                         }
318                 else if (strcmp(*argv,"-connect") == 0)
319                         {
320                         if (--argc < 1) goto bad;
321                         if (!extract_host_port(*(++argv),&host,NULL,&port))
322                                 goto bad;
323                         }
324                 else if (strcmp(*argv,"-verify") == 0)
325                         {
326                         verify=SSL_VERIFY_PEER;
327                         if (--argc < 1) goto bad;
328                         verify_depth=atoi(*(++argv));
329                         BIO_printf(bio_err,"verify depth is %d\n",verify_depth);
330                         }
331                 else if (strcmp(*argv,"-cert") == 0)
332                         {
333                         if (--argc < 1) goto bad;
334                         cert_file= *(++argv);
335                         }
336                 else if (strcmp(*argv,"-crl_check") == 0)
337                         vflags |= X509_V_FLAG_CRL_CHECK;
338                 else if (strcmp(*argv,"-crl_check_all") == 0)
339                         vflags |= X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL;
340                 else if (strcmp(*argv,"-prexit") == 0)
341                         prexit=1;
342                 else if (strcmp(*argv,"-crlf") == 0)
343                         crlf=1;
344                 else if (strcmp(*argv,"-quiet") == 0)
345                         {
346                         c_quiet=1;
347                         c_ign_eof=1;
348                         }
349                 else if (strcmp(*argv,"-ign_eof") == 0)
350                         c_ign_eof=1;
351                 else if (strcmp(*argv,"-pause") == 0)
352                         c_Pause=1;
353                 else if (strcmp(*argv,"-debug") == 0)
354                         c_debug=1;
355                 else if (strcmp(*argv,"-msg") == 0)
356                         c_msg=1;
357                 else if (strcmp(*argv,"-showcerts") == 0)
358                         c_showcerts=1;
359                 else if (strcmp(*argv,"-nbio_test") == 0)
360                         nbio_test=1;
361                 else if (strcmp(*argv,"-state") == 0)
362                         state=1;
363 #ifndef OPENSSL_NO_SSL2
364                 else if (strcmp(*argv,"-ssl2") == 0)
365                         meth=SSLv2_client_method();
366 #endif
367 #ifndef OPENSSL_NO_SSL3
368                 else if (strcmp(*argv,"-ssl3") == 0)
369                         meth=SSLv3_client_method();
370 #endif
371 #ifndef OPENSSL_NO_TLS1
372                 else if (strcmp(*argv,"-tls1") == 0)
373                         meth=TLSv1_client_method();
374 #endif
375                 else if (strcmp(*argv,"-bugs") == 0)
376                         bugs=1;
377                 else if (strcmp(*argv,"-key") == 0)
378                         {
379                         if (--argc < 1) goto bad;
380                         key_file= *(++argv);
381                         }
382                 else if (strcmp(*argv,"-reconnect") == 0)
383                         {
384                         reconnect=5;
385                         }
386                 else if (strcmp(*argv,"-CApath") == 0)
387                         {
388                         if (--argc < 1) goto bad;
389                         CApath= *(++argv);
390                         }
391                 else if (strcmp(*argv,"-CAfile") == 0)
392                         {
393                         if (--argc < 1) goto bad;
394                         CAfile= *(++argv);
395                         }
396                 else if (strcmp(*argv,"-no_tls1") == 0)
397                         off|=SSL_OP_NO_TLSv1;
398                 else if (strcmp(*argv,"-no_ssl3") == 0)
399                         off|=SSL_OP_NO_SSLv3;
400                 else if (strcmp(*argv,"-no_ssl2") == 0)
401                         off|=SSL_OP_NO_SSLv2;
402                 else if (strcmp(*argv,"-serverpref") == 0)
403                         off|=SSL_OP_CIPHER_SERVER_PREFERENCE;
404                 else if (strcmp(*argv,"-cipher") == 0)
405                         {
406                         if (--argc < 1) goto bad;
407                         cipher= *(++argv);
408                         }
409 #ifdef FIONBIO
410                 else if (strcmp(*argv,"-nbio") == 0)
411                         { c_nbio=1; }
412 #endif
413                 else if (strcmp(*argv,"-starttls") == 0)
414                         {
415                         if (--argc < 1) goto bad;
416                         ++argv;
417                         if (strcmp(*argv,"smtp") == 0)
418                                 starttls_proto = 1;
419                         else if (strcmp(*argv,"pop3") == 0)
420                                 starttls_proto = 2;
421                         else
422                                 goto bad;
423                         }
424 #ifndef OPENSSL_NO_ENGINE
425                 else if (strcmp(*argv,"-engine") == 0)
426                         {
427                         if (--argc < 1) goto bad;
428                         engine_id = *(++argv);
429                         }
430 #endif
431                 else if (strcmp(*argv,"-rand") == 0)
432                         {
433                         if (--argc < 1) goto bad;
434                         inrand= *(++argv);
435                         }
436                 else
437                         {
438                         BIO_printf(bio_err,"unknown option %s\n",*argv);
439                         badop=1;
440                         break;
441                         }
442                 argc--;
443                 argv++;
444                 }
445         if (badop)
446                 {
447 bad:
448                 sc_usage();
449                 goto end;
450                 }
451
452         OpenSSL_add_ssl_algorithms();
453         SSL_load_error_strings();
454
455 #ifndef OPENSSL_NO_ENGINE
456         e = setup_engine(bio_err, engine_id, 1);
457 #endif
458
459         if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL
460                 && !RAND_status())
461                 {
462                 BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n");
463                 }
464         if (inrand != NULL)
465                 BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
466                         app_RAND_load_files(inrand));
467
468         if (bio_c_out == NULL)
469                 {
470                 if (c_quiet && !c_debug && !c_msg)
471                         {
472                         bio_c_out=BIO_new(BIO_s_null());
473                         }
474                 else
475                         {
476                         if (bio_c_out == NULL)
477                                 bio_c_out=BIO_new_fp(stdout,BIO_NOCLOSE);
478                         }
479                 }
480
481         ctx=SSL_CTX_new(meth);
482         if (ctx == NULL)
483                 {
484                 ERR_print_errors(bio_err);
485                 goto end;
486                 }
487
488         if (bugs)
489                 SSL_CTX_set_options(ctx,SSL_OP_ALL|off);
490         else
491                 SSL_CTX_set_options(ctx,off);
492
493         if (state) SSL_CTX_set_info_callback(ctx,apps_ssl_info_callback);
494         if (cipher != NULL)
495                 if(!SSL_CTX_set_cipher_list(ctx,cipher)) {
496                 BIO_printf(bio_err,"error setting cipher list\n");
497                 ERR_print_errors(bio_err);
498                 goto end;
499         }
500 #if 0
501         else
502                 SSL_CTX_set_cipher_list(ctx,getenv("SSL_CIPHER"));
503 #endif
504
505         SSL_CTX_set_verify(ctx,verify,verify_callback);
506         if (!set_cert_stuff(ctx,cert_file,key_file))
507                 goto end;
508
509         if ((!SSL_CTX_load_verify_locations(ctx,CAfile,CApath)) ||
510                 (!SSL_CTX_set_default_verify_paths(ctx)))
511                 {
512                 /* BIO_printf(bio_err,"error setting default verify locations\n"); */
513                 ERR_print_errors(bio_err);
514                 /* goto end; */
515                 }
516
517         store = SSL_CTX_get_cert_store(ctx);
518         X509_STORE_set_flags(store, vflags);
519
520         con=SSL_new(ctx);
521 #ifndef OPENSSL_NO_KRB5
522         if (con  &&  (con->kssl_ctx = kssl_ctx_new()) != NULL)
523                 {
524                 kssl_ctx_setstring(con->kssl_ctx, KSSL_SERVER, host);
525                 }
526 #endif  /* OPENSSL_NO_KRB5  */
527 /*      SSL_set_cipher_list(con,"RC4-MD5"); */
528
529 re_start:
530
531         if (init_client(&s,host,port) == 0)
532                 {
533                 BIO_printf(bio_err,"connect:errno=%d\n",get_last_socket_error());
534                 SHUTDOWN(s);
535                 goto end;
536                 }
537         BIO_printf(bio_c_out,"CONNECTED(%08X)\n",s);
538
539 #ifdef FIONBIO
540         if (c_nbio)
541                 {
542                 unsigned long l=1;
543                 BIO_printf(bio_c_out,"turning on non blocking io\n");
544                 if (BIO_socket_ioctl(s,FIONBIO,&l) < 0)
545                         {
546                         ERR_print_errors(bio_err);
547                         goto end;
548                         }
549                 }
550 #endif                                              
551         if (c_Pause & 0x01) con->debug=1;
552         sbio=BIO_new_socket(s,BIO_NOCLOSE);
553
554         if (nbio_test)
555                 {
556                 BIO *test;
557
558                 test=BIO_new(BIO_f_nbio_test());
559                 sbio=BIO_push(test,sbio);
560                 }
561
562         if (c_debug)
563                 {
564                 con->debug=1;
565                 BIO_set_callback(sbio,bio_dump_cb);
566                 BIO_set_callback_arg(sbio,bio_c_out);
567                 }
568         if (c_msg)
569                 {
570                 SSL_set_msg_callback(con, msg_cb);
571                 SSL_set_msg_callback_arg(con, bio_c_out);
572                 }
573
574         SSL_set_bio(con,sbio,sbio);
575         SSL_set_connect_state(con);
576
577         /* ok, lets connect */
578         width=SSL_get_fd(con)+1;
579
580         read_tty=1;
581         write_tty=0;
582         tty_on=0;
583         read_ssl=1;
584         write_ssl=1;
585         
586         cbuf_len=0;
587         cbuf_off=0;
588         sbuf_len=0;
589         sbuf_off=0;
590
591         /* This is an ugly hack that does a lot of assumptions */
592         if (starttls_proto == 1)
593                 {
594                 BIO_read(sbio,mbuf,BUFSIZZ);
595                 BIO_printf(sbio,"STARTTLS\r\n");
596                 BIO_read(sbio,sbuf,BUFSIZZ);
597                 }
598         if (starttls_proto == 2)
599                 {
600                 BIO_read(sbio,mbuf,BUFSIZZ);
601                 BIO_printf(sbio,"STLS\r\n");
602                 BIO_read(sbio,sbuf,BUFSIZZ);
603                 }
604
605         for (;;)
606                 {
607                 FD_ZERO(&readfds);
608                 FD_ZERO(&writefds);
609
610                 if (SSL_in_init(con) && !SSL_total_renegotiations(con))
611                         {
612                         in_init=1;
613                         tty_on=0;
614                         }
615                 else
616                         {
617                         tty_on=1;
618                         if (in_init)
619                                 {
620                                 in_init=0;
621                                 print_stuff(bio_c_out,con,full_log);
622                                 if (full_log > 0) full_log--;
623
624                                 if (starttls_proto)
625                                         {
626                                         BIO_printf(bio_err,"%s",mbuf);
627                                         /* We don't need to know any more */
628                                         starttls_proto = 0;
629                                         }
630
631                                 if (reconnect)
632                                         {
633                                         reconnect--;
634                                         BIO_printf(bio_c_out,"drop connection and then reconnect\n");
635                                         SSL_shutdown(con);
636                                         SSL_set_connect_state(con);
637                                         SHUTDOWN(SSL_get_fd(con));
638                                         goto re_start;
639                                         }
640                                 }
641                         }
642
643                 ssl_pending = read_ssl && SSL_pending(con);
644
645                 if (!ssl_pending)
646                         {
647 #ifndef OPENSSL_SYS_WINDOWS
648                         if (tty_on)
649                                 {
650                                 if (read_tty)  FD_SET(fileno(stdin),&readfds);
651                                 if (write_tty) FD_SET(fileno(stdout),&writefds);
652                                 }
653                         if (read_ssl)
654                                 FD_SET(SSL_get_fd(con),&readfds);
655                         if (write_ssl)
656                                 FD_SET(SSL_get_fd(con),&writefds);
657 #else
658                         if(!tty_on || !write_tty) {
659                                 if (read_ssl)
660                                         FD_SET(SSL_get_fd(con),&readfds);
661                                 if (write_ssl)
662                                         FD_SET(SSL_get_fd(con),&writefds);
663                         }
664 #endif
665 /*                      printf("mode tty(%d %d%d) ssl(%d%d)\n",
666                                 tty_on,read_tty,write_tty,read_ssl,write_ssl);*/
667
668                         /* Note: under VMS with SOCKETSHR the second parameter
669                          * is currently of type (int *) whereas under other
670                          * systems it is (void *) if you don't have a cast it
671                          * will choke the compiler: if you do have a cast then
672                          * you can either go for (int *) or (void *).
673                          */
674 #ifdef OPENSSL_SYS_WINDOWS
675                         /* Under Windows we make the assumption that we can
676                          * always write to the tty: therefore if we need to
677                          * write to the tty we just fall through. Otherwise
678                          * we timeout the select every second and see if there
679                          * are any keypresses. Note: this is a hack, in a proper
680                          * Windows application we wouldn't do this.
681                          */
682                         i=0;
683                         if(!write_tty) {
684                                 if(read_tty) {
685                                         tv.tv_sec = 1;
686                                         tv.tv_usec = 0;
687                                         i=select(width,(void *)&readfds,(void *)&writefds,
688                                                  NULL,&tv);
689 #ifdef OPENSSL_SYS_WINCE
690                                         if(!i && (!_kbhit() || !read_tty) ) continue;
691 #else
692                                         if(!i && (!((_kbhit()) || (WAIT_OBJECT_0 == WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 0))) || !read_tty) ) continue;
693 #endif
694                                 } else  i=select(width,(void *)&readfds,(void *)&writefds,
695                                          NULL,NULL);
696                         }
697 #else
698                         i=select(width,(void *)&readfds,(void *)&writefds,
699                                  NULL,NULL);
700 #endif
701                         if ( i < 0)
702                                 {
703                                 BIO_printf(bio_err,"bad select %d\n",
704                                 get_last_socket_error());
705                                 goto shut;
706                                 /* goto end; */
707                                 }
708                         }
709
710                 if (!ssl_pending && FD_ISSET(SSL_get_fd(con),&writefds))
711                         {
712                         k=SSL_write(con,&(cbuf[cbuf_off]),
713                                 (unsigned int)cbuf_len);
714                         switch (SSL_get_error(con,k))
715                                 {
716                         case SSL_ERROR_NONE:
717                                 cbuf_off+=k;
718                                 cbuf_len-=k;
719                                 if (k <= 0) goto end;
720                                 /* we have done a  write(con,NULL,0); */
721                                 if (cbuf_len <= 0)
722                                         {
723                                         read_tty=1;
724                                         write_ssl=0;
725                                         }
726                                 else /* if (cbuf_len > 0) */
727                                         {
728                                         read_tty=0;
729                                         write_ssl=1;
730                                         }
731                                 break;
732                         case SSL_ERROR_WANT_WRITE:
733                                 BIO_printf(bio_c_out,"write W BLOCK\n");
734                                 write_ssl=1;
735                                 read_tty=0;
736                                 break;
737                         case SSL_ERROR_WANT_READ:
738                                 BIO_printf(bio_c_out,"write R BLOCK\n");
739                                 write_tty=0;
740                                 read_ssl=1;
741                                 write_ssl=0;
742                                 break;
743                         case SSL_ERROR_WANT_X509_LOOKUP:
744                                 BIO_printf(bio_c_out,"write X BLOCK\n");
745                                 break;
746                         case SSL_ERROR_ZERO_RETURN:
747                                 if (cbuf_len != 0)
748                                         {
749                                         BIO_printf(bio_c_out,"shutdown\n");
750                                         goto shut;
751                                         }
752                                 else
753                                         {
754                                         read_tty=1;
755                                         write_ssl=0;
756                                         break;
757                                         }
758                                 
759                         case SSL_ERROR_SYSCALL:
760                                 if ((k != 0) || (cbuf_len != 0))
761                                         {
762                                         BIO_printf(bio_err,"write:errno=%d\n",
763                                                 get_last_socket_error());
764                                         goto shut;
765                                         }
766                                 else
767                                         {
768                                         read_tty=1;
769                                         write_ssl=0;
770                                         }
771                                 break;
772                         case SSL_ERROR_SSL:
773                                 ERR_print_errors(bio_err);
774                                 goto shut;
775                                 }
776                         }
777 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
778                 /* Assume Windows/DOS can always write */
779                 else if (!ssl_pending && write_tty)
780 #else
781                 else if (!ssl_pending && FD_ISSET(fileno(stdout),&writefds))
782 #endif
783                         {
784 #ifdef CHARSET_EBCDIC
785                         ascii2ebcdic(&(sbuf[sbuf_off]),&(sbuf[sbuf_off]),sbuf_len);
786 #endif
787                         i=write(fileno(stdout),&(sbuf[sbuf_off]),sbuf_len);
788
789                         if (i <= 0)
790                                 {
791                                 BIO_printf(bio_c_out,"DONE\n");
792                                 goto shut;
793                                 /* goto end; */
794                                 }
795
796                         sbuf_len-=i;;
797                         sbuf_off+=i;
798                         if (sbuf_len <= 0)
799                                 {
800                                 read_ssl=1;
801                                 write_tty=0;
802                                 }
803                         }
804                 else if (ssl_pending || FD_ISSET(SSL_get_fd(con),&readfds))
805                         {
806 #ifdef RENEG
807 { static int iiii; if (++iiii == 52) { SSL_renegotiate(con); iiii=0; } }
808 #endif
809 #if 1
810                         k=SSL_read(con,sbuf,1024 /* BUFSIZZ */ );
811 #else
812 /* Demo for pending and peek :-) */
813                         k=SSL_read(con,sbuf,16);
814 { char zbuf[10240]; 
815 printf("read=%d pending=%d peek=%d\n",k,SSL_pending(con),SSL_peek(con,zbuf,10240));
816 }
817 #endif
818
819                         switch (SSL_get_error(con,k))
820                                 {
821                         case SSL_ERROR_NONE:
822                                 if (k <= 0)
823                                         goto end;
824                                 sbuf_off=0;
825                                 sbuf_len=k;
826
827                                 read_ssl=0;
828                                 write_tty=1;
829                                 break;
830                         case SSL_ERROR_WANT_WRITE:
831                                 BIO_printf(bio_c_out,"read W BLOCK\n");
832                                 write_ssl=1;
833                                 read_tty=0;
834                                 break;
835                         case SSL_ERROR_WANT_READ:
836                                 BIO_printf(bio_c_out,"read R BLOCK\n");
837                                 write_tty=0;
838                                 read_ssl=1;
839                                 if ((read_tty == 0) && (write_ssl == 0))
840                                         write_ssl=1;
841                                 break;
842                         case SSL_ERROR_WANT_X509_LOOKUP:
843                                 BIO_printf(bio_c_out,"read X BLOCK\n");
844                                 break;
845                         case SSL_ERROR_SYSCALL:
846                                 BIO_printf(bio_err,"read:errno=%d\n",get_last_socket_error());
847                                 goto shut;
848                         case SSL_ERROR_ZERO_RETURN:
849                                 BIO_printf(bio_c_out,"closed\n");
850                                 goto shut;
851                         case SSL_ERROR_SSL:
852                                 ERR_print_errors(bio_err);
853                                 goto shut;
854                                 /* break; */
855                                 }
856                         }
857
858 #ifdef OPENSSL_SYS_WINDOWS
859 #ifdef OPENSSL_SYS_WINCE
860                 else if (_kbhit())
861 #else
862                 else if ((_kbhit()) || (WAIT_OBJECT_0 == WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 0)))
863 #endif
864 #else
865                 else if (FD_ISSET(fileno(stdin),&readfds))
866 #endif
867                         {
868                         if (crlf)
869                                 {
870                                 int j, lf_num;
871
872                                 i=read(fileno(stdin),cbuf,BUFSIZZ/2);
873                                 lf_num = 0;
874                                 /* both loops are skipped when i <= 0 */
875                                 for (j = 0; j < i; j++)
876                                         if (cbuf[j] == '\n')
877                                                 lf_num++;
878                                 for (j = i-1; j >= 0; j--)
879                                         {
880                                         cbuf[j+lf_num] = cbuf[j];
881                                         if (cbuf[j] == '\n')
882                                                 {
883                                                 lf_num--;
884                                                 i++;
885                                                 cbuf[j+lf_num] = '\r';
886                                                 }
887                                         }
888                                 assert(lf_num == 0);
889                                 }
890                         else
891                                 i=read(fileno(stdin),cbuf,BUFSIZZ);
892
893                         if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q')))
894                                 {
895                                 BIO_printf(bio_err,"DONE\n");
896                                 goto shut;
897                                 }
898
899                         if ((!c_ign_eof) && (cbuf[0] == 'R'))
900                                 {
901                                 BIO_printf(bio_err,"RENEGOTIATING\n");
902                                 SSL_renegotiate(con);
903                                 cbuf_len=0;
904                                 }
905                         else
906                                 {
907                                 cbuf_len=i;
908                                 cbuf_off=0;
909 #ifdef CHARSET_EBCDIC
910                                 ebcdic2ascii(cbuf, cbuf, i);
911 #endif
912                                 }
913
914                         write_ssl=1;
915                         read_tty=0;
916                         }
917                 }
918 shut:
919         SSL_shutdown(con);
920         SHUTDOWN(SSL_get_fd(con));
921         ret=0;
922 end:
923         if(prexit) print_stuff(bio_c_out,con,1);
924         if (con != NULL) SSL_free(con);
925         if (con2 != NULL) SSL_free(con2);
926         if (ctx != NULL) SSL_CTX_free(ctx);
927         if (cbuf != NULL) { OPENSSL_cleanse(cbuf,BUFSIZZ); OPENSSL_free(cbuf); }
928         if (sbuf != NULL) { OPENSSL_cleanse(sbuf,BUFSIZZ); OPENSSL_free(sbuf); }
929         if (mbuf != NULL) { OPENSSL_cleanse(mbuf,BUFSIZZ); OPENSSL_free(mbuf); }
930         if (bio_c_out != NULL)
931                 {
932                 BIO_free(bio_c_out);
933                 bio_c_out=NULL;
934                 }
935         apps_shutdown();
936         OPENSSL_EXIT(ret);
937         }
938
939
940 static void print_stuff(BIO *bio, SSL *s, int full)
941         {
942         X509 *peer=NULL;
943         char *p;
944         static char *space="                ";
945         char buf[BUFSIZ];
946         STACK_OF(X509) *sk;
947         STACK_OF(X509_NAME) *sk2;
948         SSL_CIPHER *c;
949         X509_NAME *xn;
950         int j,i;
951
952         if (full)
953                 {
954                 int got_a_chain = 0;
955
956                 sk=SSL_get_peer_cert_chain(s);
957                 if (sk != NULL)
958                         {
959                         got_a_chain = 1; /* we don't have it for SSL2 (yet) */
960
961                         BIO_printf(bio,"---\nCertificate chain\n");
962                         for (i=0; i<sk_X509_num(sk); i++)
963                                 {
964                                 X509_NAME_oneline(X509_get_subject_name(
965                                         sk_X509_value(sk,i)),buf,sizeof buf);
966                                 BIO_printf(bio,"%2d s:%s\n",i,buf);
967                                 X509_NAME_oneline(X509_get_issuer_name(
968                                         sk_X509_value(sk,i)),buf,sizeof buf);
969                                 BIO_printf(bio,"   i:%s\n",buf);
970                                 if (c_showcerts)
971                                         PEM_write_bio_X509(bio,sk_X509_value(sk,i));
972                                 }
973                         }
974
975                 BIO_printf(bio,"---\n");
976                 peer=SSL_get_peer_certificate(s);
977                 if (peer != NULL)
978                         {
979                         BIO_printf(bio,"Server certificate\n");
980                         if (!(c_showcerts && got_a_chain)) /* Redundant if we showed the whole chain */
981                                 PEM_write_bio_X509(bio,peer);
982                         X509_NAME_oneline(X509_get_subject_name(peer),
983                                 buf,sizeof buf);
984                         BIO_printf(bio,"subject=%s\n",buf);
985                         X509_NAME_oneline(X509_get_issuer_name(peer),
986                                 buf,sizeof buf);
987                         BIO_printf(bio,"issuer=%s\n",buf);
988                         }
989                 else
990                         BIO_printf(bio,"no peer certificate available\n");
991
992                 sk2=SSL_get_client_CA_list(s);
993                 if ((sk2 != NULL) && (sk_X509_NAME_num(sk2) > 0))
994                         {
995                         BIO_printf(bio,"---\nAcceptable client certificate CA names\n");
996                         for (i=0; i<sk_X509_NAME_num(sk2); i++)
997                                 {
998                                 xn=sk_X509_NAME_value(sk2,i);
999                                 X509_NAME_oneline(xn,buf,sizeof(buf));
1000                                 BIO_write(bio,buf,strlen(buf));
1001                                 BIO_write(bio,"\n",1);
1002                                 }
1003                         }
1004                 else
1005                         {
1006                         BIO_printf(bio,"---\nNo client certificate CA names sent\n");
1007                         }
1008                 p=SSL_get_shared_ciphers(s,buf,sizeof buf);
1009                 if (p != NULL)
1010                         {
1011                         /* This works only for SSL 2.  In later protocol
1012                          * versions, the client does not know what other
1013                          * ciphers (in addition to the one to be used
1014                          * in the current connection) the server supports. */
1015
1016                         BIO_printf(bio,"---\nCiphers common between both SSL endpoints:\n");
1017                         j=i=0;
1018                         while (*p)
1019                                 {
1020                                 if (*p == ':')
1021                                         {
1022                                         BIO_write(bio,space,15-j%25);
1023                                         i++;
1024                                         j=0;
1025                                         BIO_write(bio,((i%3)?" ":"\n"),1);
1026                                         }
1027                                 else
1028                                         {
1029                                         BIO_write(bio,p,1);
1030                                         j++;
1031                                         }
1032                                 p++;
1033                                 }
1034                         BIO_write(bio,"\n",1);
1035                         }
1036
1037                 BIO_printf(bio,"---\nSSL handshake has read %ld bytes and written %ld bytes\n",
1038                         BIO_number_read(SSL_get_rbio(s)),
1039                         BIO_number_written(SSL_get_wbio(s)));
1040                 }
1041         BIO_printf(bio,((s->hit)?"---\nReused, ":"---\nNew, "));
1042         c=SSL_get_current_cipher(s);
1043         BIO_printf(bio,"%s, Cipher is %s\n",
1044                 SSL_CIPHER_get_version(c),
1045                 SSL_CIPHER_get_name(c));
1046         if (peer != NULL) {
1047                 EVP_PKEY *pktmp;
1048                 pktmp = X509_get_pubkey(peer);
1049                 BIO_printf(bio,"Server public key is %d bit\n",
1050                                                          EVP_PKEY_bits(pktmp));
1051                 EVP_PKEY_free(pktmp);
1052         }
1053         SSL_SESSION_print(bio,SSL_get_session(s));
1054         BIO_printf(bio,"---\n");
1055         if (peer != NULL)
1056                 X509_free(peer);
1057         /* flush, or debugging output gets mixed with http response */
1058         BIO_flush(bio);
1059         }
1060