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