63641df6c3d20113bf9a5c21079143c4e7323173
[openssl.git] / ssl / ssltest.c
1 /* ssl/ssltest.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-2000 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 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  * ECC cipher suite support in OpenSSL originally developed by 
114  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
115  */
116
117 #define _BSD_SOURCE 1           /* Or gethostname won't be declared properly
118                                    on Linux and GNU platforms. */
119
120 #include <assert.h>
121 #include <errno.h>
122 #include <limits.h>
123 #include <stdio.h>
124 #include <stdlib.h>
125 #include <string.h>
126 #include <time.h>
127 #include <inttypes.h>
128
129 #define USE_SOCKETS
130 #include "e_os.h"
131
132 #include <openssl/bio.h>
133 #include <openssl/crypto.h>
134 #include <openssl/evp.h>
135 #include <openssl/x509.h>
136 #include <openssl/ssl.h>
137 #ifndef OPENSSL_NO_ENGINE
138 #include <openssl/engine.h>
139 #endif
140 #include <openssl/err.h>
141 #include <openssl/rand.h>
142
143 #define _XOPEN_SOURCE_EXTENDED  1 /* Or gethostname won't be declared properly
144                                      on Compaq platforms (at least with DEC C).
145                                      Do not try to put it earlier, or IPv6 includes
146                                      get screwed...
147                                   */
148
149 #ifdef OPENSSL_SYS_WINDOWS
150 #include <winsock.h>
151 #else
152 #include OPENSSL_UNISTD
153 #endif
154
155 #ifdef OPENSSL_SYS_VMS
156 #  define TEST_SERVER_CERT "SYS$DISK:[-.APPS]SERVER.PEM"
157 #  define TEST_CLIENT_CERT "SYS$DISK:[-.APPS]CLIENT.PEM"
158 #elif defined(OPENSSL_SYS_WINCE)
159 #  define TEST_SERVER_CERT "\\OpenSSL\\server.pem"
160 #  define TEST_CLIENT_CERT "\\OpenSSL\\client.pem"
161 #elif defined(OPENSSL_SYS_NETWARE)
162 #  define TEST_SERVER_CERT "\\openssl\\apps\\server.pem"
163 #  define TEST_CLIENT_CERT "\\openssl\\apps\\client.pem"
164 #else
165 #  define TEST_SERVER_CERT "../apps/server.pem"
166 #  define TEST_CLIENT_CERT "../apps/client.pem"
167 #endif
168
169 /* There is really no standard for this, so let's assign some tentative
170    numbers.  In any case, these numbers are only for this test */
171 #define COMP_RLE        255
172 #define COMP_ZLIB       1
173
174 static int MS_CALLBACK verify_callback(int ok, X509_STORE_CTX *ctx);
175 #ifndef OPENSSL_NO_RSA
176 static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export,int keylength);
177 static void free_tmp_rsa(void);
178 #endif
179 static int MS_CALLBACK app_verify_callback(X509_STORE_CTX *ctx, void *arg);
180 #define APP_CALLBACK "Test Callback Argument"
181 static char *app_verify_arg = APP_CALLBACK;
182
183 #ifndef OPENSSL_NO_DH
184 static DH *get_dh512(void);
185 static DH *get_dh1024(void);
186 static DH *get_dh1024dsa(void);
187 #endif
188
189 static BIO *bio_err=NULL;
190 static BIO *bio_stdout=NULL;
191
192 static char *cipher=NULL;
193 static int verbose=0;
194 static int debug=0;
195 #if 0
196 /* Not used yet. */
197 #ifdef FIONBIO
198 static int s_nbio=0;
199 #endif
200 #endif
201
202 static const char rnd_seed[] = "string to make the random number generator think it has entropy";
203
204 int doit_biopair(SSL *s_ssl,SSL *c_ssl,long bytes,clock_t *s_time,clock_t *c_time);
205 int doit(SSL *s_ssl,SSL *c_ssl,long bytes);
206 static void sv_usage(void)
207         {
208         fprintf(stderr,"usage: ssltest [args ...]\n");
209         fprintf(stderr,"\n");
210         fprintf(stderr," -server_auth  - check server certificate\n");
211         fprintf(stderr," -client_auth  - do client authentication\n");
212         fprintf(stderr," -v            - more output\n");
213         fprintf(stderr," -d            - debug output\n");
214         fprintf(stderr," -reuse        - use session-id reuse\n");
215         fprintf(stderr," -num <val>    - number of connections to perform\n");
216         fprintf(stderr," -bytes <val>  - number of bytes to swap between client/server\n");
217 #ifndef OPENSSL_NO_DH
218         fprintf(stderr," -dhe1024      - use 1024 bit key (safe prime) for DHE\n");
219         fprintf(stderr," -dhe1024dsa   - use 1024 bit key (with 160-bit subprime) for DHE\n");
220         fprintf(stderr," -no_dhe       - disable DHE\n");
221 #endif
222 #ifndef OPENSSL_NO_ECDH
223         fprintf(stderr," -no_ecdhe     - disable ECDHE\n");
224 #endif
225 #ifndef OPENSSL_NO_SSL2
226         fprintf(stderr," -ssl2         - use SSLv2\n");
227 #endif
228 #ifndef OPENSSL_NO_SSL3
229         fprintf(stderr," -ssl3         - use SSLv3\n");
230 #endif
231 #ifndef OPENSSL_NO_TLS1
232         fprintf(stderr," -tls1         - use TLSv1\n");
233 #endif
234         fprintf(stderr," -CApath arg   - PEM format directory of CA's\n");
235         fprintf(stderr," -CAfile arg   - PEM format file of CA's\n");
236         fprintf(stderr," -cert arg     - Server certificate file\n");
237         fprintf(stderr," -key arg      - Server key file (default: same as -cert)\n");
238         fprintf(stderr," -c_cert arg   - Client certificate file\n");
239         fprintf(stderr," -c_key arg    - Client key file (default: same as -c_cert)\n");
240         fprintf(stderr," -cipher arg   - The cipher list\n");
241         fprintf(stderr," -bio_pair     - Use BIO pairs\n");
242         fprintf(stderr," -f            - Test even cases that can't work\n");
243         fprintf(stderr," -time         - measure processor time used by client and server\n");
244         fprintf(stderr," -zlib         - use zlib compression\n");
245         fprintf(stderr," -rle          - use rle compression\n");
246 #ifndef OPENSSL_NO_ECDH
247         fprintf(stderr," -named_curve arg  - Elliptic curve name to use for ephemeral ECDH keys.\n" \
248                        "                 Use \"openssl ecparam -list_curves\" for all names\n"  \
249                        "                 (default is sect163r2).\n");
250 #endif
251         }
252
253 static void print_details(SSL *c_ssl, const char *prefix)
254         {
255         SSL_CIPHER *ciph;
256         X509 *cert;
257                 
258         ciph=SSL_get_current_cipher(c_ssl);
259         BIO_printf(bio_stdout,"%s%s, cipher %s %s",
260                 prefix,
261                 SSL_get_version(c_ssl),
262                 SSL_CIPHER_get_version(ciph),
263                 SSL_CIPHER_get_name(ciph));
264         cert=SSL_get_peer_certificate(c_ssl);
265         if (cert != NULL)
266                 {
267                 EVP_PKEY *pkey = X509_get_pubkey(cert);
268                 if (pkey != NULL)
269                         {
270                         if (0) 
271                                 ;
272 #ifndef OPENSSL_NO_RSA
273                         else if (pkey->type == EVP_PKEY_RSA && pkey->pkey.rsa != NULL
274                                 && pkey->pkey.rsa->n != NULL)
275                                 {
276                                 BIO_printf(bio_stdout, ", %d bit RSA",
277                                         BN_num_bits(pkey->pkey.rsa->n));
278                                 }
279 #endif
280 #ifndef OPENSSL_NO_DSA
281                         else if (pkey->type == EVP_PKEY_DSA && pkey->pkey.dsa != NULL
282                                 && pkey->pkey.dsa->p != NULL)
283                                 {
284                                 BIO_printf(bio_stdout, ", %d bit DSA",
285                                         BN_num_bits(pkey->pkey.dsa->p));
286                                 }
287 #endif
288                         EVP_PKEY_free(pkey);
289                         }
290                 X509_free(cert);
291                 }
292         /* The SSL API does not allow us to look at temporary RSA/DH keys,
293          * otherwise we should print their lengths too */
294         BIO_printf(bio_stdout,"\n");
295         }
296
297 static void lock_dbg_cb(int mode, int type, const char *file, int line)
298         {
299         static int modes[CRYPTO_NUM_LOCKS]; /* = {0, 0, ... } */
300         const char *errstr = NULL;
301         int rw;
302         
303         rw = mode & (CRYPTO_READ|CRYPTO_WRITE);
304         if (!((rw == CRYPTO_READ) || (rw == CRYPTO_WRITE)))
305                 {
306                 errstr = "invalid mode";
307                 goto err;
308                 }
309
310         if (type < 0 || type >= CRYPTO_NUM_LOCKS)
311                 {
312                 errstr = "type out of bounds";
313                 goto err;
314                 }
315
316         if (mode & CRYPTO_LOCK)
317                 {
318                 if (modes[type])
319                         {
320                         errstr = "already locked";
321                         /* must not happen in a single-threaded program
322                          * (would deadlock) */
323                         goto err;
324                         }
325
326                 modes[type] = rw;
327                 }
328         else if (mode & CRYPTO_UNLOCK)
329                 {
330                 if (!modes[type])
331                         {
332                         errstr = "not locked";
333                         goto err;
334                         }
335                 
336                 if (modes[type] != rw)
337                         {
338                         errstr = (rw == CRYPTO_READ) ?
339                                 "CRYPTO_r_unlock on write lock" :
340                                 "CRYPTO_w_unlock on read lock";
341                         }
342
343                 modes[type] = 0;
344                 }
345         else
346                 {
347                 errstr = "invalid mode";
348                 goto err;
349                 }
350
351  err:
352         if (errstr)
353                 {
354                 /* we cannot use bio_err here */
355                 fprintf(stderr, "openssl (lock_dbg_cb): %s (mode=%d, type=%d) at %s:%d\n",
356                         errstr, mode, type, file, line);
357                 }
358         }
359
360 int main(int argc, char *argv[])
361         {
362         char *CApath=NULL,*CAfile=NULL;
363         int badop=0;
364         int bio_pair=0;
365         int force=0;
366         int tls1=0,ssl2=0,ssl3=0,ret=1;
367         int client_auth=0;
368         int server_auth=0,i;
369         int app_verify=0;
370         char *server_cert=TEST_SERVER_CERT;
371         char *server_key=NULL;
372         char *client_cert=TEST_CLIENT_CERT;
373         char *client_key=NULL;
374         char *named_curve = NULL;
375         SSL_CTX *s_ctx=NULL;
376         SSL_CTX *c_ctx=NULL;
377         SSL_METHOD *meth=NULL;
378         SSL *c_ssl,*s_ssl;
379         int number=1,reuse=0;
380         long bytes=256L;
381 #ifndef OPENSSL_NO_DH
382         DH *dh;
383         int dhe1024 = 0, dhe1024dsa = 0;
384 #endif
385 #ifndef OPENSSL_NO_ECDH
386         EC_KEY *ecdh = NULL;
387 #endif
388         int no_dhe = 0;
389         int no_ecdhe = 0;
390         int print_time = 0;
391         clock_t s_time = 0, c_time = 0;
392         int comp = 0;
393         COMP_METHOD *cm = NULL;
394         STACK_OF(SSL_COMP) *ssl_comp_methods = NULL;
395
396         verbose = 0;
397         debug = 0;
398         cipher = 0;
399
400         bio_err=BIO_new_fp(stderr,BIO_NOCLOSE); 
401
402         CRYPTO_set_locking_callback(lock_dbg_cb);
403
404         /* enable memory leak checking unless explicitly disabled */
405         if (!((getenv("OPENSSL_DEBUG_MEMORY") != NULL) && (0 == strcmp(getenv("OPENSSL_DEBUG_MEMORY"), "off"))))
406                 {
407                 CRYPTO_malloc_debug_init();
408                 CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
409                 }
410         else
411                 {
412                 /* OPENSSL_DEBUG_MEMORY=off */
413                 CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
414                 }
415         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
416
417         RAND_seed(rnd_seed, sizeof rnd_seed);
418
419         bio_stdout=BIO_new_fp(stdout,BIO_NOCLOSE);
420
421         argc--;
422         argv++;
423
424         while (argc >= 1)
425                 {
426                 if      (strcmp(*argv,"-server_auth") == 0)
427                         server_auth=1;
428                 else if (strcmp(*argv,"-client_auth") == 0)
429                         client_auth=1;
430                 else if (strcmp(*argv,"-v") == 0)
431                         verbose=1;
432                 else if (strcmp(*argv,"-d") == 0)
433                         debug=1;
434                 else if (strcmp(*argv,"-reuse") == 0)
435                         reuse=1;
436                 else if (strcmp(*argv,"-dhe1024") == 0)
437                         {
438 #ifndef OPENSSL_NO_DH
439                         dhe1024=1;
440 #else
441                         fprintf(stderr,"ignoring -dhe1024, since I'm compiled without DH\n");
442 #endif
443                         }
444                 else if (strcmp(*argv,"-dhe1024dsa") == 0)
445                         {
446 #ifndef OPENSSL_NO_DH
447                         dhe1024dsa=1;
448 #else
449                         fprintf(stderr,"ignoring -dhe1024, since I'm compiled without DH\n");
450 #endif
451                         }
452                 else if (strcmp(*argv,"-no_dhe") == 0)
453                         no_dhe=1;
454                 else if (strcmp(*argv,"-no_ecdhe") == 0)
455                         no_ecdhe=1;
456                 else if (strcmp(*argv,"-ssl2") == 0)
457                         ssl2=1;
458                 else if (strcmp(*argv,"-tls1") == 0)
459                         tls1=1;
460                 else if (strcmp(*argv,"-ssl3") == 0)
461                         ssl3=1;
462                 else if (strncmp(*argv,"-num",4) == 0)
463                         {
464                         if (--argc < 1) goto bad;
465                         number= atoi(*(++argv));
466                         if (number == 0) number=1;
467                         }
468                 else if (strcmp(*argv,"-bytes") == 0)
469                         {
470                         if (--argc < 1) goto bad;
471                         bytes= atol(*(++argv));
472                         if (bytes == 0L) bytes=1L;
473                         i=strlen(argv[0]);
474                         if (argv[0][i-1] == 'k') bytes*=1024L;
475                         if (argv[0][i-1] == 'm') bytes*=1024L*1024L;
476                         }
477                 else if (strcmp(*argv,"-cert") == 0)
478                         {
479                         if (--argc < 1) goto bad;
480                         server_cert= *(++argv);
481                         }
482                 else if (strcmp(*argv,"-s_cert") == 0)
483                         {
484                         if (--argc < 1) goto bad;
485                         server_cert= *(++argv);
486                         }
487                 else if (strcmp(*argv,"-key") == 0)
488                         {
489                         if (--argc < 1) goto bad;
490                         server_key= *(++argv);
491                         }
492                 else if (strcmp(*argv,"-s_key") == 0)
493                         {
494                         if (--argc < 1) goto bad;
495                         server_key= *(++argv);
496                         }
497                 else if (strcmp(*argv,"-c_cert") == 0)
498                         {
499                         if (--argc < 1) goto bad;
500                         client_cert= *(++argv);
501                         }
502                 else if (strcmp(*argv,"-c_key") == 0)
503                         {
504                         if (--argc < 1) goto bad;
505                         client_key= *(++argv);
506                         }
507                 else if (strcmp(*argv,"-cipher") == 0)
508                         {
509                         if (--argc < 1) goto bad;
510                         cipher= *(++argv);
511                         }
512                 else if (strcmp(*argv,"-CApath") == 0)
513                         {
514                         if (--argc < 1) goto bad;
515                         CApath= *(++argv);
516                         }
517                 else if (strcmp(*argv,"-CAfile") == 0)
518                         {
519                         if (--argc < 1) goto bad;
520                         CAfile= *(++argv);
521                         }
522                 else if (strcmp(*argv,"-bio_pair") == 0)
523                         {
524                         bio_pair = 1;
525                         }
526                 else if (strcmp(*argv,"-f") == 0)
527                         {
528                         force = 1;
529                         }
530                 else if (strcmp(*argv,"-time") == 0)
531                         {
532                         print_time = 1;
533                         }
534                 else if (strcmp(*argv,"-zlib") == 0)
535                         {
536                         comp = COMP_ZLIB;
537                         }
538                 else if (strcmp(*argv,"-rle") == 0)
539                         {
540                         comp = COMP_RLE;
541                         }
542                 else if (strcmp(*argv,"-named_curve") == 0)
543                         {
544                         if (--argc < 1) goto bad;
545 #ifndef OPENSSL_NO_ECDH         
546                         named_curve = *(++argv);
547 #else
548                         fprintf(stderr,"ignoring -named_curve, since I'm compiled without ECDH\n");
549                         ++argv;
550 #endif
551                         }
552                 else if (strcmp(*argv,"-app_verify") == 0)
553                         {
554                         app_verify = 1;
555                         }
556                 else
557                         {
558                         fprintf(stderr,"unknown option %s\n",*argv);
559                         badop=1;
560                         break;
561                         }
562                 argc--;
563                 argv++;
564                 }
565         if (badop)
566                 {
567 bad:
568                 sv_usage();
569                 goto end;
570                 }
571
572         if (!ssl2 && !ssl3 && !tls1 && number > 1 && !reuse && !force)
573                 {
574                 fprintf(stderr, "This case cannot work.  Use -f to perform "
575                         "the test anyway (and\n-d to see what happens), "
576                         "or add one of -ssl2, -ssl3, -tls1, -reuse\n"
577                         "to avoid protocol mismatch.\n");
578                 EXIT(1);
579                 }
580
581         if (print_time)
582                 {
583                 if (!bio_pair)
584                         {
585                         fprintf(stderr, "Using BIO pair (-bio_pair)\n");
586                         bio_pair = 1;
587                         }
588                 if (number < 50 && !force)
589                         fprintf(stderr, "Warning: For accurate timings, use more connections (e.g. -num 1000)\n");
590                 }
591
592 /*      if (cipher == NULL) cipher=getenv("SSL_CIPHER"); */
593
594         SSL_library_init();
595         SSL_load_error_strings();
596
597         if (comp == COMP_ZLIB) cm = COMP_zlib();
598         if (comp == COMP_RLE) cm = COMP_rle();
599         if (cm != NULL)
600                 {
601                 if (cm->type != NID_undef)
602                         {
603                         if (SSL_COMP_add_compression_method(comp, cm) != 0)
604                                 {
605                                 fprintf(stderr,
606                                         "Failed to add compression method\n");
607                                 ERR_print_errors_fp(stderr);
608                                 }
609                         }
610                 else
611                         {
612                         fprintf(stderr,
613                                 "Warning: %s compression not supported\n",
614                                 (comp == COMP_RLE ? "rle" :
615                                         (comp == COMP_ZLIB ? "zlib" :
616                                                 "unknown")));
617                         ERR_print_errors_fp(stderr);
618                         }
619                 }
620         ssl_comp_methods = SSL_COMP_get_compression_methods();
621         fprintf(stderr, "Available compression methods:\n");
622         {
623         int j, n = sk_SSL_COMP_num(ssl_comp_methods);
624         if (n == 0)
625                 fprintf(stderr, "  NONE\n");
626         else
627                 for (j = 0; j < n; j++)
628                         {
629                         SSL_COMP *c = sk_SSL_COMP_value(ssl_comp_methods, j);
630                         fprintf(stderr, "  %d: %s\n", c->id, c->name);
631                         }
632         }
633
634 #if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3)
635         if (ssl2)
636                 meth=SSLv2_method();
637         else 
638         if (tls1)
639                 meth=TLSv1_method();
640         else
641         if (ssl3)
642                 meth=SSLv3_method();
643         else
644                 meth=SSLv23_method();
645 #else
646 #ifdef OPENSSL_NO_SSL2
647         meth=SSLv3_method();
648 #else
649         meth=SSLv2_method();
650 #endif
651 #endif
652
653         c_ctx=SSL_CTX_new(meth);
654         s_ctx=SSL_CTX_new(meth);
655         if ((c_ctx == NULL) || (s_ctx == NULL))
656                 {
657                 ERR_print_errors(bio_err);
658                 goto end;
659                 }
660
661         if (cipher != NULL)
662                 {
663                 SSL_CTX_set_cipher_list(c_ctx,cipher);
664                 SSL_CTX_set_cipher_list(s_ctx,cipher);
665                 }
666
667 #ifndef OPENSSL_NO_DH
668         if (!no_dhe)
669                 {
670                 if (dhe1024dsa)
671                         {
672                         /* use SSL_OP_SINGLE_DH_USE to avoid small subgroup attacks */
673                         SSL_CTX_set_options(s_ctx, SSL_OP_SINGLE_DH_USE);
674                         dh=get_dh1024dsa();
675                         }
676                 else if (dhe1024)
677                         dh=get_dh1024();
678                 else
679                         dh=get_dh512();
680                 SSL_CTX_set_tmp_dh(s_ctx,dh);
681                 DH_free(dh);
682                 }
683 #else
684         (void)no_dhe;
685 #endif
686
687 #ifndef OPENSSL_NO_ECDH
688         if (!no_ecdhe)
689                 {
690                 ecdh = EC_KEY_new();
691                 if (ecdh != NULL)
692                         {
693                         if (named_curve)
694                                 {
695                                 int nid = OBJ_sn2nid(named_curve);
696
697                                 if (nid == 0)
698                                         {
699                                         BIO_printf(bio_err, "unknown curve name (%s)\n", named_curve);
700                                         EC_KEY_free(ecdh);
701                                         goto end;
702                                         }
703
704                                 ecdh->group = EC_GROUP_new_by_nid(nid);
705                                 if (ecdh->group == NULL)
706                                         {
707                                         BIO_printf(bio_err, "unable to create curve (%s)\n", named_curve);
708                                         EC_KEY_free(ecdh);
709                                         goto end;
710                                         }
711                                 }
712                         
713                         if (ecdh->group == NULL)
714                                 ecdh->group=EC_GROUP_new_by_nid(NID_sect163r2);
715
716                         SSL_CTX_set_tmp_ecdh(s_ctx, ecdh);
717                         SSL_CTX_set_options(s_ctx, SSL_OP_SINGLE_ECDH_USE);
718                         EC_KEY_free(ecdh);
719                         }
720                 }
721 #else
722         (void)no_ecdhe;
723 #endif
724
725 #ifndef OPENSSL_NO_RSA
726         SSL_CTX_set_tmp_rsa_callback(s_ctx,tmp_rsa_cb);
727 #endif
728
729         if (!SSL_CTX_use_certificate_file(s_ctx,server_cert,SSL_FILETYPE_PEM))
730                 {
731                 ERR_print_errors(bio_err);
732                 }
733         else if (!SSL_CTX_use_PrivateKey_file(s_ctx,
734                 (server_key?server_key:server_cert), SSL_FILETYPE_PEM))
735                 {
736                 ERR_print_errors(bio_err);
737                 goto end;
738                 }
739
740         if (client_auth)
741                 {
742                 SSL_CTX_use_certificate_file(c_ctx,client_cert,
743                         SSL_FILETYPE_PEM);
744                 SSL_CTX_use_PrivateKey_file(c_ctx,
745                         (client_key?client_key:client_cert),
746                         SSL_FILETYPE_PEM);
747                 }
748
749         if (    (!SSL_CTX_load_verify_locations(s_ctx,CAfile,CApath)) ||
750                 (!SSL_CTX_set_default_verify_paths(s_ctx)) ||
751                 (!SSL_CTX_load_verify_locations(c_ctx,CAfile,CApath)) ||
752                 (!SSL_CTX_set_default_verify_paths(c_ctx)))
753                 {
754                 /* fprintf(stderr,"SSL_load_verify_locations\n"); */
755                 ERR_print_errors(bio_err);
756                 /* goto end; */
757                 }
758
759         if (client_auth)
760                 {
761                 BIO_printf(bio_err,"client authentication\n");
762                 SSL_CTX_set_verify(s_ctx,
763                         SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
764                         verify_callback);
765                 if (app_verify) 
766                         {
767                         SSL_CTX_set_cert_verify_callback(s_ctx, app_verify_callback, app_verify_arg);
768                         }
769                 }
770         if (server_auth)
771                 {
772                 BIO_printf(bio_err,"server authentication\n");
773                 SSL_CTX_set_verify(c_ctx,SSL_VERIFY_PEER,
774                         verify_callback);
775                 if (app_verify) 
776                         {
777                         SSL_CTX_set_cert_verify_callback(s_ctx, app_verify_callback, app_verify_arg);
778                         }
779                 }
780         
781         {
782                 int session_id_context = 0;
783                 SSL_CTX_set_session_id_context(s_ctx, (void *)&session_id_context, sizeof session_id_context);
784         }
785
786         c_ssl=SSL_new(c_ctx);
787         s_ssl=SSL_new(s_ctx);
788
789 #ifndef OPENSSL_NO_KRB5
790         if (c_ssl  &&  c_ssl->kssl_ctx)
791                 {
792                 char    localhost[MAXHOSTNAMELEN+2];
793
794                 if (gethostname(localhost, sizeof localhost-1) == 0)
795                         {
796                         localhost[sizeof localhost-1]='\0';
797                         if(strlen(localhost) == sizeof localhost-1)
798                                 {
799                                 BIO_printf(bio_err,"localhost name too long\n");
800                                 goto end;
801                                 }
802                         kssl_ctx_setstring(c_ssl->kssl_ctx, KSSL_SERVER,
803                                 localhost);
804                         }
805                 }
806 #endif    /* OPENSSL_NO_KRB5  */
807
808         for (i=0; i<number; i++)
809                 {
810                 if (!reuse) SSL_set_session(c_ssl,NULL);
811                 if (bio_pair)
812                         ret=doit_biopair(s_ssl,c_ssl,bytes,&s_time,&c_time);
813                 else
814                         ret=doit(s_ssl,c_ssl,bytes);
815                 }
816
817         if (!verbose)
818                 {
819                 print_details(c_ssl, "");
820                 }
821         if ((number > 1) || (bytes > 1L))
822                 BIO_printf(bio_stdout, "%d handshakes of %ld bytes done\n",number,bytes);
823         if (print_time)
824                 {
825 #ifdef CLOCKS_PER_SEC
826                 /* "To determine the time in seconds, the value returned
827                  * by the clock function should be divided by the value
828                  * of the macro CLOCKS_PER_SEC."
829                  *                                       -- ISO/IEC 9899 */
830                 BIO_printf(bio_stdout, "Approximate total server time: %6.2f s\n"
831                         "Approximate total client time: %6.2f s\n",
832                         (double)s_time/CLOCKS_PER_SEC,
833                         (double)c_time/CLOCKS_PER_SEC);
834 #else
835                 /* "`CLOCKS_PER_SEC' undeclared (first use this function)"
836                  *                            -- cc on NeXTstep/OpenStep */
837                 BIO_printf(bio_stdout,
838                         "Approximate total server time: %6.2f units\n"
839                         "Approximate total client time: %6.2f units\n",
840                         (double)s_time,
841                         (double)c_time);
842 #endif
843                 }
844
845         SSL_free(s_ssl);
846         SSL_free(c_ssl);
847
848 end:
849         if (s_ctx != NULL) SSL_CTX_free(s_ctx);
850         if (c_ctx != NULL) SSL_CTX_free(c_ctx);
851
852         if (bio_stdout != NULL) BIO_free(bio_stdout);
853
854 #ifndef OPENSSL_NO_RSA
855         free_tmp_rsa();
856 #endif
857 #ifndef OPENSSL_NO_ENGINE
858         ENGINE_cleanup();
859 #endif
860         CRYPTO_cleanup_all_ex_data();
861         ERR_free_strings();
862         ERR_remove_state(0);
863         EVP_cleanup();
864         CRYPTO_mem_leaks(bio_err);
865         if (bio_err != NULL) BIO_free(bio_err);
866         EXIT(ret);
867         }
868
869 int doit_biopair(SSL *s_ssl, SSL *c_ssl, long count,
870         clock_t *s_time, clock_t *c_time)
871         {
872         long cw_num = count, cr_num = count, sw_num = count, sr_num = count;
873         BIO *s_ssl_bio = NULL, *c_ssl_bio = NULL;
874         BIO *server = NULL, *server_io = NULL, *client = NULL, *client_io = NULL;
875         int ret = 1;
876         
877         size_t bufsiz = 256; /* small buffer for testing */
878
879         if (!BIO_new_bio_pair(&server, bufsiz, &server_io, bufsiz))
880                 goto err;
881         if (!BIO_new_bio_pair(&client, bufsiz, &client_io, bufsiz))
882                 goto err;
883         
884         s_ssl_bio = BIO_new(BIO_f_ssl());
885         if (!s_ssl_bio)
886                 goto err;
887
888         c_ssl_bio = BIO_new(BIO_f_ssl());
889         if (!c_ssl_bio)
890                 goto err;
891
892         SSL_set_connect_state(c_ssl);
893         SSL_set_bio(c_ssl, client, client);
894         (void)BIO_set_ssl(c_ssl_bio, c_ssl, BIO_NOCLOSE);
895
896         SSL_set_accept_state(s_ssl);
897         SSL_set_bio(s_ssl, server, server);
898         (void)BIO_set_ssl(s_ssl_bio, s_ssl, BIO_NOCLOSE);
899
900         do
901                 {
902                 /* c_ssl_bio:          SSL filter BIO
903                  *
904                  * client:             pseudo-I/O for SSL library
905                  *
906                  * client_io:          client's SSL communication; usually to be
907                  *                     relayed over some I/O facility, but in this
908                  *                     test program, we're the server, too:
909                  *
910                  * server_io:          server's SSL communication
911                  *
912                  * server:             pseudo-I/O for SSL library
913                  *
914                  * s_ssl_bio:          SSL filter BIO
915                  *
916                  * The client and the server each employ a "BIO pair":
917                  * client + client_io, server + server_io.
918                  * BIO pairs are symmetric.  A BIO pair behaves similar
919                  * to a non-blocking socketpair (but both endpoints must
920                  * be handled by the same thread).
921                  * [Here we could connect client and server to the ends
922                  * of a single BIO pair, but then this code would be less
923                  * suitable as an example for BIO pairs in general.]
924                  *
925                  * Useful functions for querying the state of BIO pair endpoints:
926                  *
927                  * BIO_ctrl_pending(bio)              number of bytes we can read now
928                  * BIO_ctrl_get_read_request(bio)     number of bytes needed to fulfil
929                  *                                      other side's read attempt
930                  * BIO_ctrl_get_write_guarantee(bio)   number of bytes we can write now
931                  *
932                  * ..._read_request is never more than ..._write_guarantee;
933                  * it depends on the application which one you should use.
934                  */
935
936                 /* We have non-blocking behaviour throughout this test program, but
937                  * can be sure that there is *some* progress in each iteration; so
938                  * we don't have to worry about ..._SHOULD_READ or ..._SHOULD_WRITE
939                  * -- we just try everything in each iteration
940                  */
941
942                         {
943                         /* CLIENT */
944                 
945                         MS_STATIC char cbuf[1024*8];
946                         int i, r;
947                         clock_t c_clock = clock();
948
949                         memset(cbuf, 0, sizeof(cbuf));
950
951                         if (debug)
952                                 if (SSL_in_init(c_ssl))
953                                         printf("client waiting in SSL_connect - %s\n",
954                                                 SSL_state_string_long(c_ssl));
955
956                         if (cw_num > 0)
957                                 {
958                                 /* Write to server. */
959                                 
960                                 if (cw_num > (long)sizeof cbuf)
961                                         i = sizeof cbuf;
962                                 else
963                                         i = (int)cw_num;
964                                 r = BIO_write(c_ssl_bio, cbuf, i);
965                                 if (r < 0)
966                                         {
967                                         if (!BIO_should_retry(c_ssl_bio))
968                                                 {
969                                                 fprintf(stderr,"ERROR in CLIENT\n");
970                                                 goto err;
971                                                 }
972                                         /* BIO_should_retry(...) can just be ignored here.
973                                          * The library expects us to call BIO_write with
974                                          * the same arguments again, and that's what we will
975                                          * do in the next iteration. */
976                                         }
977                                 else if (r == 0)
978                                         {
979                                         fprintf(stderr,"SSL CLIENT STARTUP FAILED\n");
980                                         goto err;
981                                         }
982                                 else
983                                         {
984                                         if (debug)
985                                                 printf("client wrote %d\n", r);
986                                         cw_num -= r;                            
987                                         }
988                                 }
989
990                         if (cr_num > 0)
991                                 {
992                                 /* Read from server. */
993
994                                 r = BIO_read(c_ssl_bio, cbuf, sizeof(cbuf));
995                                 if (r < 0)
996                                         {
997                                         if (!BIO_should_retry(c_ssl_bio))
998                                                 {
999                                                 fprintf(stderr,"ERROR in CLIENT\n");
1000                                                 goto err;
1001                                                 }
1002                                         /* Again, "BIO_should_retry" can be ignored. */
1003                                         }
1004                                 else if (r == 0)
1005                                         {
1006                                         fprintf(stderr,"SSL CLIENT STARTUP FAILED\n");
1007                                         goto err;
1008                                         }
1009                                 else
1010                                         {
1011                                         if (debug)
1012                                                 printf("client read %d\n", r);
1013                                         cr_num -= r;
1014                                         }
1015                                 }
1016
1017                         /* c_time and s_time increments will typically be very small
1018                          * (depending on machine speed and clock tick intervals),
1019                          * but sampling over a large number of connections should
1020                          * result in fairly accurate figures.  We cannot guarantee
1021                          * a lot, however -- if each connection lasts for exactly
1022                          * one clock tick, it will be counted only for the client
1023                          * or only for the server or even not at all.
1024                          */
1025                         *c_time += (clock() - c_clock);
1026                         }
1027
1028                         {
1029                         /* SERVER */
1030                 
1031                         MS_STATIC char sbuf[1024*8];
1032                         int i, r;
1033                         clock_t s_clock = clock();
1034
1035                         memset(sbuf, 0, sizeof(sbuf));
1036
1037                         if (debug)
1038                                 if (SSL_in_init(s_ssl))
1039                                         printf("server waiting in SSL_accept - %s\n",
1040                                                 SSL_state_string_long(s_ssl));
1041
1042                         if (sw_num > 0)
1043                                 {
1044                                 /* Write to client. */
1045                                 
1046                                 if (sw_num > (long)sizeof sbuf)
1047                                         i = sizeof sbuf;
1048                                 else
1049                                         i = (int)sw_num;
1050                                 r = BIO_write(s_ssl_bio, sbuf, i);
1051                                 if (r < 0)
1052                                         {
1053                                         if (!BIO_should_retry(s_ssl_bio))
1054                                                 {
1055                                                 fprintf(stderr,"ERROR in SERVER\n");
1056                                                 goto err;
1057                                                 }
1058                                         /* Ignore "BIO_should_retry". */
1059                                         }
1060                                 else if (r == 0)
1061                                         {
1062                                         fprintf(stderr,"SSL SERVER STARTUP FAILED\n");
1063                                         goto err;
1064                                         }
1065                                 else
1066                                         {
1067                                         if (debug)
1068                                                 printf("server wrote %d\n", r);
1069                                         sw_num -= r;                            
1070                                         }
1071                                 }
1072
1073                         if (sr_num > 0)
1074                                 {
1075                                 /* Read from client. */
1076
1077                                 r = BIO_read(s_ssl_bio, sbuf, sizeof(sbuf));
1078                                 if (r < 0)
1079                                         {
1080                                         if (!BIO_should_retry(s_ssl_bio))
1081                                                 {
1082                                                 fprintf(stderr,"ERROR in SERVER\n");
1083                                                 goto err;
1084                                                 }
1085                                         /* blah, blah */
1086                                         }
1087                                 else if (r == 0)
1088                                         {
1089                                         fprintf(stderr,"SSL SERVER STARTUP FAILED\n");
1090                                         goto err;
1091                                         }
1092                                 else
1093                                         {
1094                                         if (debug)
1095                                                 printf("server read %d\n", r);
1096                                         sr_num -= r;
1097                                         }
1098                                 }
1099
1100                         *s_time += (clock() - s_clock);
1101                         }
1102                         
1103                         {
1104                         /* "I/O" BETWEEN CLIENT AND SERVER. */
1105
1106                         size_t r1, r2;
1107                         BIO *io1 = server_io, *io2 = client_io;
1108                         /* we use the non-copying interface for io1
1109                          * and the standard BIO_write/BIO_read interface for io2
1110                          */
1111                         
1112                         static int prev_progress = 1;
1113                         int progress = 0;
1114                         
1115                         /* io1 to io2 */
1116                         do
1117                                 {
1118                                 size_t num;
1119                                 int r;
1120
1121                                 r1 = BIO_ctrl_pending(io1);
1122                                 r2 = BIO_ctrl_get_write_guarantee(io2);
1123
1124                                 num = r1;
1125                                 if (r2 < num)
1126                                         num = r2;
1127                                 if (num)
1128                                         {
1129                                         char *dataptr;
1130
1131                                         if (INT_MAX < num) /* yeah, right */
1132                                                 num = INT_MAX;
1133                                         
1134                                         r = BIO_nread(io1, &dataptr, (int)num);
1135                                         assert(r > 0);
1136                                         assert(r <= (int)num);
1137                                         /* possibly r < num (non-contiguous data) */
1138                                         num = r;
1139                                         r = BIO_write(io2, dataptr, (int)num);
1140                                         if (r != (int)num) /* can't happen */
1141                                                 {
1142                                                 fprintf(stderr, "ERROR: BIO_write could not write "
1143                                                         "BIO_ctrl_get_write_guarantee() bytes");
1144                                                 goto err;
1145                                                 }
1146                                         progress = 1;
1147
1148                                         if (debug)
1149                                                 printf((io1 == client_io) ?
1150                                                         "C->S relaying: %d bytes\n" :
1151                                                         "S->C relaying: %d bytes\n",
1152                                                         (int)num);
1153                                         }
1154                                 }
1155                         while (r1 && r2);
1156
1157                         /* io2 to io1 */
1158                         {
1159                                 size_t num;
1160                                 int r;
1161
1162                                 r1 = BIO_ctrl_pending(io2);
1163                                 r2 = BIO_ctrl_get_read_request(io1);
1164                                 /* here we could use ..._get_write_guarantee instead of
1165                                  * ..._get_read_request, but by using the latter
1166                                  * we test restartability of the SSL implementation
1167                                  * more thoroughly */
1168                                 num = r1;
1169                                 if (r2 < num)
1170                                         num = r2;
1171                                 if (num)
1172                                         {
1173                                         char *dataptr;
1174                                         
1175                                         if (INT_MAX < num)
1176                                                 num = INT_MAX;
1177
1178                                         if (num > 1)
1179                                                 --num; /* test restartability even more thoroughly */
1180                                         
1181                                         r = BIO_nwrite0(io1, &dataptr);
1182                                         assert(r > 0);
1183                                         if (r < (int)num)
1184                                                 num = r;
1185                                         r = BIO_read(io2, dataptr, (int)num);
1186                                         if (r != (int)num) /* can't happen */
1187                                                 {
1188                                                 fprintf(stderr, "ERROR: BIO_read could not read "
1189                                                         "BIO_ctrl_pending() bytes");
1190                                                 goto err;
1191                                                 }
1192                                         progress = 1;
1193                                         r = BIO_nwrite(io1, &dataptr, (int)num);
1194                                         if (r != (int)num) /* can't happen */
1195                                                 {
1196                                                 fprintf(stderr, "ERROR: BIO_nwrite() did not accept "
1197                                                         "BIO_nwrite0() bytes");
1198                                                 goto err;
1199                                                 }
1200                                         
1201                                         if (debug)
1202                                                 printf((io2 == client_io) ?
1203                                                         "C->S relaying: %d bytes\n" :
1204                                                         "S->C relaying: %d bytes\n",
1205                                                         (int)num);
1206                                         }
1207                         } /* no loop, BIO_ctrl_get_read_request now returns 0 anyway */
1208
1209                         if (!progress && !prev_progress)
1210                                 if (cw_num > 0 || cr_num > 0 || sw_num > 0 || sr_num > 0)
1211                                         {
1212                                         fprintf(stderr, "ERROR: got stuck\n");
1213                                         if (strcmp("SSLv2", SSL_get_version(c_ssl)) == 0)
1214                                                 {
1215                                                 fprintf(stderr, "This can happen for SSL2 because "
1216                                                         "CLIENT-FINISHED and SERVER-VERIFY are written \n"
1217                                                         "concurrently ...");
1218                                                 if (strncmp("2SCF", SSL_state_string(c_ssl), 4) == 0
1219                                                         && strncmp("2SSV", SSL_state_string(s_ssl), 4) == 0)
1220                                                         {
1221                                                         fprintf(stderr, " ok.\n");
1222                                                         goto end;
1223                                                         }
1224                                                 }
1225                                         fprintf(stderr, " ERROR.\n");
1226                                         goto err;
1227                                         }
1228                         prev_progress = progress;
1229                         }
1230                 }
1231         while (cw_num > 0 || cr_num > 0 || sw_num > 0 || sr_num > 0);
1232
1233         if (verbose)
1234                 print_details(c_ssl, "DONE via BIO pair: ");
1235 end:
1236         ret = 0;
1237
1238  err:
1239         ERR_print_errors(bio_err);
1240         
1241         if (server)
1242                 BIO_free(server);
1243         if (server_io)
1244                 BIO_free(server_io);
1245         if (client)
1246                 BIO_free(client);
1247         if (client_io)
1248                 BIO_free(client_io);
1249         if (s_ssl_bio)
1250                 BIO_free(s_ssl_bio);
1251         if (c_ssl_bio)
1252                 BIO_free(c_ssl_bio);
1253
1254         return ret;
1255         }
1256
1257
1258 #define W_READ  1
1259 #define W_WRITE 2
1260 #define C_DONE  1
1261 #define S_DONE  2
1262
1263 int doit(SSL *s_ssl, SSL *c_ssl, long count)
1264         {
1265         MS_STATIC char cbuf[1024*8],sbuf[1024*8];
1266         long cw_num=count,cr_num=count;
1267         long sw_num=count,sr_num=count;
1268         int ret=1;
1269         BIO *c_to_s=NULL;
1270         BIO *s_to_c=NULL;
1271         BIO *c_bio=NULL;
1272         BIO *s_bio=NULL;
1273         int c_r,c_w,s_r,s_w;
1274         int c_want,s_want;
1275         int i,j;
1276         int done=0;
1277         int c_write,s_write;
1278         int do_server=0,do_client=0;
1279
1280         memset(cbuf,0,sizeof(cbuf));
1281         memset(sbuf,0,sizeof(sbuf));
1282
1283         c_to_s=BIO_new(BIO_s_mem());
1284         s_to_c=BIO_new(BIO_s_mem());
1285         if ((s_to_c == NULL) || (c_to_s == NULL))
1286                 {
1287                 ERR_print_errors(bio_err);
1288                 goto err;
1289                 }
1290
1291         c_bio=BIO_new(BIO_f_ssl());
1292         s_bio=BIO_new(BIO_f_ssl());
1293         if ((c_bio == NULL) || (s_bio == NULL))
1294                 {
1295                 ERR_print_errors(bio_err);
1296                 goto err;
1297                 }
1298
1299         SSL_set_connect_state(c_ssl);
1300         SSL_set_bio(c_ssl,s_to_c,c_to_s);
1301         BIO_set_ssl(c_bio,c_ssl,BIO_NOCLOSE);
1302
1303         SSL_set_accept_state(s_ssl);
1304         SSL_set_bio(s_ssl,c_to_s,s_to_c);
1305         BIO_set_ssl(s_bio,s_ssl,BIO_NOCLOSE);
1306
1307         c_r=0; s_r=1;
1308         c_w=1; s_w=0;
1309         c_want=W_WRITE;
1310         s_want=0;
1311         c_write=1,s_write=0;
1312
1313         /* We can always do writes */
1314         for (;;)
1315                 {
1316                 do_server=0;
1317                 do_client=0;
1318
1319                 i=(int)BIO_pending(s_bio);
1320                 if ((i && s_r) || s_w) do_server=1;
1321
1322                 i=(int)BIO_pending(c_bio);
1323                 if ((i && c_r) || c_w) do_client=1;
1324
1325                 if (do_server && debug)
1326                         {
1327                         if (SSL_in_init(s_ssl))
1328                                 printf("server waiting in SSL_accept - %s\n",
1329                                         SSL_state_string_long(s_ssl));
1330 /*                      else if (s_write)
1331                                 printf("server:SSL_write()\n");
1332                         else
1333                                 printf("server:SSL_read()\n"); */
1334                         }
1335
1336                 if (do_client && debug)
1337                         {
1338                         if (SSL_in_init(c_ssl))
1339                                 printf("client waiting in SSL_connect - %s\n",
1340                                         SSL_state_string_long(c_ssl));
1341 /*                      else if (c_write)
1342                                 printf("client:SSL_write()\n");
1343                         else
1344                                 printf("client:SSL_read()\n"); */
1345                         }
1346
1347                 if (!do_client && !do_server)
1348                         {
1349                         fprintf(stdout,"ERROR IN STARTUP\n");
1350                         ERR_print_errors(bio_err);
1351                         break;
1352                         }
1353                 if (do_client && !(done & C_DONE))
1354                         {
1355                         if (c_write)
1356                                 {
1357                                 j = (cw_num > (long)sizeof(cbuf)) ?
1358                                         (int)sizeof(cbuf) : (int)cw_num;
1359                                 i=BIO_write(c_bio,cbuf,j);
1360                                 if (i < 0)
1361                                         {
1362                                         c_r=0;
1363                                         c_w=0;
1364                                         if (BIO_should_retry(c_bio))
1365                                                 {
1366                                                 if (BIO_should_read(c_bio))
1367                                                         c_r=1;
1368                                                 if (BIO_should_write(c_bio))
1369                                                         c_w=1;
1370                                                 }
1371                                         else
1372                                                 {
1373                                                 fprintf(stderr,"ERROR in CLIENT\n");
1374                                                 ERR_print_errors(bio_err);
1375                                                 goto err;
1376                                                 }
1377                                         }
1378                                 else if (i == 0)
1379                                         {
1380                                         fprintf(stderr,"SSL CLIENT STARTUP FAILED\n");
1381                                         goto err;
1382                                         }
1383                                 else
1384                                         {
1385                                         if (debug)
1386                                                 printf("client wrote %d\n",i);
1387                                         /* ok */
1388                                         s_r=1;
1389                                         c_write=0;
1390                                         cw_num-=i;
1391                                         }
1392                                 }
1393                         else
1394                                 {
1395                                 i=BIO_read(c_bio,cbuf,sizeof(cbuf));
1396                                 if (i < 0)
1397                                         {
1398                                         c_r=0;
1399                                         c_w=0;
1400                                         if (BIO_should_retry(c_bio))
1401                                                 {
1402                                                 if (BIO_should_read(c_bio))
1403                                                         c_r=1;
1404                                                 if (BIO_should_write(c_bio))
1405                                                         c_w=1;
1406                                                 }
1407                                         else
1408                                                 {
1409                                                 fprintf(stderr,"ERROR in CLIENT\n");
1410                                                 ERR_print_errors(bio_err);
1411                                                 goto err;
1412                                                 }
1413                                         }
1414                                 else if (i == 0)
1415                                         {
1416                                         fprintf(stderr,"SSL CLIENT STARTUP FAILED\n");
1417                                         goto err;
1418                                         }
1419                                 else
1420                                         {
1421                                         if (debug)
1422                                                 printf("client read %d\n",i);
1423                                         cr_num-=i;
1424                                         if (sw_num > 0)
1425                                                 {
1426                                                 s_write=1;
1427                                                 s_w=1;
1428                                                 }
1429                                         if (cr_num <= 0)
1430                                                 {
1431                                                 s_write=1;
1432                                                 s_w=1;
1433                                                 done=S_DONE|C_DONE;
1434                                                 }
1435                                         }
1436                                 }
1437                         }
1438
1439                 if (do_server && !(done & S_DONE))
1440                         {
1441                         if (!s_write)
1442                                 {
1443                                 i=BIO_read(s_bio,sbuf,sizeof(cbuf));
1444                                 if (i < 0)
1445                                         {
1446                                         s_r=0;
1447                                         s_w=0;
1448                                         if (BIO_should_retry(s_bio))
1449                                                 {
1450                                                 if (BIO_should_read(s_bio))
1451                                                         s_r=1;
1452                                                 if (BIO_should_write(s_bio))
1453                                                         s_w=1;
1454                                                 }
1455                                         else
1456                                                 {
1457                                                 fprintf(stderr,"ERROR in SERVER\n");
1458                                                 ERR_print_errors(bio_err);
1459                                                 goto err;
1460                                                 }
1461                                         }
1462                                 else if (i == 0)
1463                                         {
1464                                         ERR_print_errors(bio_err);
1465                                         fprintf(stderr,"SSL SERVER STARTUP FAILED in SSL_read\n");
1466                                         goto err;
1467                                         }
1468                                 else
1469                                         {
1470                                         if (debug)
1471                                                 printf("server read %d\n",i);
1472                                         sr_num-=i;
1473                                         if (cw_num > 0)
1474                                                 {
1475                                                 c_write=1;
1476                                                 c_w=1;
1477                                                 }
1478                                         if (sr_num <= 0)
1479                                                 {
1480                                                 s_write=1;
1481                                                 s_w=1;
1482                                                 c_write=0;
1483                                                 }
1484                                         }
1485                                 }
1486                         else
1487                                 {
1488                                 j = (sw_num > (long)sizeof(sbuf)) ?
1489                                         (int)sizeof(sbuf) : (int)sw_num;
1490                                 i=BIO_write(s_bio,sbuf,j);
1491                                 if (i < 0)
1492                                         {
1493                                         s_r=0;
1494                                         s_w=0;
1495                                         if (BIO_should_retry(s_bio))
1496                                                 {
1497                                                 if (BIO_should_read(s_bio))
1498                                                         s_r=1;
1499                                                 if (BIO_should_write(s_bio))
1500                                                         s_w=1;
1501                                                 }
1502                                         else
1503                                                 {
1504                                                 fprintf(stderr,"ERROR in SERVER\n");
1505                                                 ERR_print_errors(bio_err);
1506                                                 goto err;
1507                                                 }
1508                                         }
1509                                 else if (i == 0)
1510                                         {
1511                                         ERR_print_errors(bio_err);
1512                                         fprintf(stderr,"SSL SERVER STARTUP FAILED in SSL_write\n");
1513                                         goto err;
1514                                         }
1515                                 else
1516                                         {
1517                                         if (debug)
1518                                                 printf("server wrote %d\n",i);
1519                                         sw_num-=i;
1520                                         s_write=0;
1521                                         c_r=1;
1522                                         if (sw_num <= 0)
1523                                                 done|=S_DONE;
1524                                         }
1525                                 }
1526                         }
1527
1528                 if ((done & S_DONE) && (done & C_DONE)) break;
1529                 }
1530
1531         if (verbose)
1532                 print_details(c_ssl, "DONE: ");
1533         ret=0;
1534 err:
1535         /* We have to set the BIO's to NULL otherwise they will be
1536          * OPENSSL_free()ed twice.  Once when th s_ssl is SSL_free()ed and
1537          * again when c_ssl is SSL_free()ed.
1538          * This is a hack required because s_ssl and c_ssl are sharing the same
1539          * BIO structure and SSL_set_bio() and SSL_free() automatically
1540          * BIO_free non NULL entries.
1541          * You should not normally do this or be required to do this */
1542         if (s_ssl != NULL)
1543                 {
1544                 s_ssl->rbio=NULL;
1545                 s_ssl->wbio=NULL;
1546                 }
1547         if (c_ssl != NULL)
1548                 {
1549                 c_ssl->rbio=NULL;
1550                 c_ssl->wbio=NULL;
1551                 }
1552
1553         if (c_to_s != NULL) BIO_free(c_to_s);
1554         if (s_to_c != NULL) BIO_free(s_to_c);
1555         if (c_bio != NULL) BIO_free_all(c_bio);
1556         if (s_bio != NULL) BIO_free_all(s_bio);
1557         return(ret);
1558         }
1559
1560 static int MS_CALLBACK verify_callback(int ok, X509_STORE_CTX *ctx)
1561         {
1562         char *s,buf[256];
1563
1564         s=X509_NAME_oneline(X509_get_subject_name(ctx->current_cert),buf,
1565                             sizeof buf);
1566         if (s != NULL)
1567                 {
1568                 if (ok)
1569                         fprintf(stderr,"depth=%d %s\n",ctx->error_depth,buf);
1570                 else
1571                         fprintf(stderr,"depth=%d error=%d %s\n",
1572                                 ctx->error_depth,ctx->error,buf);
1573                 }
1574
1575         if (ok == 0)
1576                 {
1577                 switch (ctx->error)
1578                         {
1579                 case X509_V_ERR_CERT_NOT_YET_VALID:
1580                 case X509_V_ERR_CERT_HAS_EXPIRED:
1581                 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1582                         ok=1;
1583                         }
1584                 }
1585
1586         return(ok);
1587         }
1588
1589 static int MS_CALLBACK app_verify_callback(X509_STORE_CTX *ctx, void *arg)
1590         {
1591         char *s = NULL,buf[256];
1592         int ok=1;
1593
1594         fprintf(stderr, "In app_verify_callback, allowing cert. ");
1595         fprintf(stderr, "Arg is: %s\n", (char *)arg);
1596         fprintf(stderr, "Finished printing do we have a context? 0x%x a cert? 0x%x\n",
1597                         (uintptr_t)ctx, (uintptr_t)ctx->cert);
1598         if (ctx->cert)
1599                 s=X509_NAME_oneline(X509_get_subject_name(ctx->cert),buf,256);
1600         if (s != NULL)
1601                 {
1602                         fprintf(stderr,"cert depth=%d %s\n",ctx->error_depth,buf);
1603                 }
1604
1605         return(ok);
1606         }
1607
1608 #ifndef OPENSSL_NO_RSA
1609 static RSA *rsa_tmp=NULL;
1610
1611 static RSA MS_CALLBACK *tmp_rsa_cb(SSL *s, int is_export, int keylength)
1612         {
1613         if (rsa_tmp == NULL)
1614                 {
1615                 rsa_tmp = RSA_new();
1616                 if(!rsa_tmp)
1617                         {
1618                         BIO_printf(bio_err, "Memory error...");
1619                         goto end;
1620                         }
1621                 BIO_printf(bio_err,"Generating temp (%d bit) RSA key...",keylength);
1622                 (void)BIO_flush(bio_err);
1623                 if(!RSA_generate_key_ex(rsa_tmp,keylength,RSA_F4,NULL))
1624                         {
1625                         BIO_printf(bio_err, "Error generating key.");
1626                         RSA_free(rsa_tmp);
1627                         rsa_tmp = NULL;
1628                         }
1629 end:
1630                 BIO_printf(bio_err,"\n");
1631                 (void)BIO_flush(bio_err);
1632                 }
1633         return(rsa_tmp);
1634         }
1635
1636 static void free_tmp_rsa(void)
1637         {
1638         if (rsa_tmp != NULL)
1639                 {
1640                 RSA_free(rsa_tmp);
1641                 rsa_tmp = NULL;
1642                 }
1643         }
1644 #endif
1645
1646 #ifndef OPENSSL_NO_DH
1647 /* These DH parameters have been generated as follows:
1648  *    $ openssl dhparam -C -noout 512
1649  *    $ openssl dhparam -C -noout 1024
1650  *    $ openssl dhparam -C -noout -dsaparam 1024
1651  * (The third function has been renamed to avoid name conflicts.)
1652  */
1653 static DH *get_dh512()
1654         {
1655         static unsigned char dh512_p[]={
1656                 0xCB,0xC8,0xE1,0x86,0xD0,0x1F,0x94,0x17,0xA6,0x99,0xF0,0xC6,
1657                 0x1F,0x0D,0xAC,0xB6,0x25,0x3E,0x06,0x39,0xCA,0x72,0x04,0xB0,
1658                 0x6E,0xDA,0xC0,0x61,0xE6,0x7A,0x77,0x25,0xE8,0x3B,0xB9,0x5F,
1659                 0x9A,0xB6,0xB5,0xFE,0x99,0x0B,0xA1,0x93,0x4E,0x35,0x33,0xB8,
1660                 0xE1,0xF1,0x13,0x4F,0x59,0x1A,0xD2,0x57,0xC0,0x26,0x21,0x33,
1661                 0x02,0xC5,0xAE,0x23,
1662                 };
1663         static unsigned char dh512_g[]={
1664                 0x02,
1665                 };
1666         DH *dh;
1667
1668         if ((dh=DH_new()) == NULL) return(NULL);
1669         dh->p=BN_bin2bn(dh512_p,sizeof(dh512_p),NULL);
1670         dh->g=BN_bin2bn(dh512_g,sizeof(dh512_g),NULL);
1671         if ((dh->p == NULL) || (dh->g == NULL))
1672                 { DH_free(dh); return(NULL); }
1673         return(dh);
1674         }
1675
1676 static DH *get_dh1024()
1677         {
1678         static unsigned char dh1024_p[]={
1679                 0xF8,0x81,0x89,0x7D,0x14,0x24,0xC5,0xD1,0xE6,0xF7,0xBF,0x3A,
1680                 0xE4,0x90,0xF4,0xFC,0x73,0xFB,0x34,0xB5,0xFA,0x4C,0x56,0xA2,
1681                 0xEA,0xA7,0xE9,0xC0,0xC0,0xCE,0x89,0xE1,0xFA,0x63,0x3F,0xB0,
1682                 0x6B,0x32,0x66,0xF1,0xD1,0x7B,0xB0,0x00,0x8F,0xCA,0x87,0xC2,
1683                 0xAE,0x98,0x89,0x26,0x17,0xC2,0x05,0xD2,0xEC,0x08,0xD0,0x8C,
1684                 0xFF,0x17,0x52,0x8C,0xC5,0x07,0x93,0x03,0xB1,0xF6,0x2F,0xB8,
1685                 0x1C,0x52,0x47,0x27,0x1B,0xDB,0xD1,0x8D,0x9D,0x69,0x1D,0x52,
1686                 0x4B,0x32,0x81,0xAA,0x7F,0x00,0xC8,0xDC,0xE6,0xD9,0xCC,0xC1,
1687                 0x11,0x2D,0x37,0x34,0x6C,0xEA,0x02,0x97,0x4B,0x0E,0xBB,0xB1,
1688                 0x71,0x33,0x09,0x15,0xFD,0xDD,0x23,0x87,0x07,0x5E,0x89,0xAB,
1689                 0x6B,0x7C,0x5F,0xEC,0xA6,0x24,0xDC,0x53,
1690                 };
1691         static unsigned char dh1024_g[]={
1692                 0x02,
1693                 };
1694         DH *dh;
1695
1696         if ((dh=DH_new()) == NULL) return(NULL);
1697         dh->p=BN_bin2bn(dh1024_p,sizeof(dh1024_p),NULL);
1698         dh->g=BN_bin2bn(dh1024_g,sizeof(dh1024_g),NULL);
1699         if ((dh->p == NULL) || (dh->g == NULL))
1700                 { DH_free(dh); return(NULL); }
1701         return(dh);
1702         }
1703
1704 static DH *get_dh1024dsa()
1705         {
1706         static unsigned char dh1024_p[]={
1707                 0xC8,0x00,0xF7,0x08,0x07,0x89,0x4D,0x90,0x53,0xF3,0xD5,0x00,
1708                 0x21,0x1B,0xF7,0x31,0xA6,0xA2,0xDA,0x23,0x9A,0xC7,0x87,0x19,
1709                 0x3B,0x47,0xB6,0x8C,0x04,0x6F,0xFF,0xC6,0x9B,0xB8,0x65,0xD2,
1710                 0xC2,0x5F,0x31,0x83,0x4A,0xA7,0x5F,0x2F,0x88,0x38,0xB6,0x55,
1711                 0xCF,0xD9,0x87,0x6D,0x6F,0x9F,0xDA,0xAC,0xA6,0x48,0xAF,0xFC,
1712                 0x33,0x84,0x37,0x5B,0x82,0x4A,0x31,0x5D,0xE7,0xBD,0x52,0x97,
1713                 0xA1,0x77,0xBF,0x10,0x9E,0x37,0xEA,0x64,0xFA,0xCA,0x28,0x8D,
1714                 0x9D,0x3B,0xD2,0x6E,0x09,0x5C,0x68,0xC7,0x45,0x90,0xFD,0xBB,
1715                 0x70,0xC9,0x3A,0xBB,0xDF,0xD4,0x21,0x0F,0xC4,0x6A,0x3C,0xF6,
1716                 0x61,0xCF,0x3F,0xD6,0x13,0xF1,0x5F,0xBC,0xCF,0xBC,0x26,0x9E,
1717                 0xBC,0x0B,0xBD,0xAB,0x5D,0xC9,0x54,0x39,
1718                 };
1719         static unsigned char dh1024_g[]={
1720                 0x3B,0x40,0x86,0xE7,0xF3,0x6C,0xDE,0x67,0x1C,0xCC,0x80,0x05,
1721                 0x5A,0xDF,0xFE,0xBD,0x20,0x27,0x74,0x6C,0x24,0xC9,0x03,0xF3,
1722                 0xE1,0x8D,0xC3,0x7D,0x98,0x27,0x40,0x08,0xB8,0x8C,0x6A,0xE9,
1723                 0xBB,0x1A,0x3A,0xD6,0x86,0x83,0x5E,0x72,0x41,0xCE,0x85,0x3C,
1724                 0xD2,0xB3,0xFC,0x13,0xCE,0x37,0x81,0x9E,0x4C,0x1C,0x7B,0x65,
1725                 0xD3,0xE6,0xA6,0x00,0xF5,0x5A,0x95,0x43,0x5E,0x81,0xCF,0x60,
1726                 0xA2,0x23,0xFC,0x36,0xA7,0x5D,0x7A,0x4C,0x06,0x91,0x6E,0xF6,
1727                 0x57,0xEE,0x36,0xCB,0x06,0xEA,0xF5,0x3D,0x95,0x49,0xCB,0xA7,
1728                 0xDD,0x81,0xDF,0x80,0x09,0x4A,0x97,0x4D,0xA8,0x22,0x72,0xA1,
1729                 0x7F,0xC4,0x70,0x56,0x70,0xE8,0x20,0x10,0x18,0x8F,0x2E,0x60,
1730                 0x07,0xE7,0x68,0x1A,0x82,0x5D,0x32,0xA2,
1731                 };
1732         DH *dh;
1733
1734         if ((dh=DH_new()) == NULL) return(NULL);
1735         dh->p=BN_bin2bn(dh1024_p,sizeof(dh1024_p),NULL);
1736         dh->g=BN_bin2bn(dh1024_g,sizeof(dh1024_g),NULL);
1737         if ((dh->p == NULL) || (dh->g == NULL))
1738                 { DH_free(dh); return(NULL); }
1739         dh->length = 160;
1740         return(dh);
1741         }
1742 #endif