c3a54270e6082c23bcc0879dc2a89c1d7ee513cc
[openssl.git] / crypto / threads / mttest.c
1 /* crypto/threads/mttest.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 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <errno.h>
63 #ifdef LINUX
64 # include <typedefs.h>
65 #endif
66 #ifdef OPENSSL_SYS_WIN32
67 # include <windows.h>
68 #endif
69 #ifdef SOLARIS
70 # include <synch.h>
71 # include <thread.h>
72 #endif
73 #ifdef IRIX
74 # include <ulocks.h>
75 # include <sys/prctl.h>
76 #endif
77 #ifdef PTHREADS
78 # include <pthread.h>
79 #endif
80 #ifdef OPENSSL_SYS_NETWARE
81 # if !defined __int64
82 #  define __int64 long long
83 # endif
84 # include <nwmpk.h>
85 #endif
86 #include <openssl/lhash.h>
87 #include <openssl/crypto.h>
88 #include <openssl/buffer.h>
89 #include "../../e_os.h"
90 #include <openssl/x509.h>
91 #include <openssl/ssl.h>
92 #include <openssl/err.h>
93 #include <openssl/rand.h>
94
95 #ifdef OPENSSL_NO_STDIO
96 # include "../buffer/bss_file.c"
97 #endif
98
99 #ifdef OPENSSL_SYS_NETWARE
100 # define TEST_SERVER_CERT "/openssl/apps/server.pem"
101 # define TEST_CLIENT_CERT "/openssl/apps/client.pem"
102 #else
103 # define TEST_SERVER_CERT "../../apps/server.pem"
104 # define TEST_CLIENT_CERT "../../apps/client.pem"
105 #endif
106
107 #define MAX_THREAD_NUMBER       100
108
109 int verify_callback(int ok, X509_STORE_CTX *xs);
110 void thread_setup(void);
111 void thread_cleanup(void);
112 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx);
113
114 void irix_locking_callback(int mode, int type, const char *file, int line);
115 void solaris_locking_callback(int mode, int type, const char *file, int line);
116 void win32_locking_callback(int mode, int type, const char *file, int line);
117 void pthreads_locking_callback(int mode, int type, const char *file, int line);
118 void netware_locking_callback(int mode, int type, const char *file, int line);
119 void beos_locking_callback(int mode, int type, const char *file, int line);
120
121 void irix_thread_id(CRYPTO_THREADID *tid);
122 void solaris_thread_id(CRYPTO_THREADID *tid);
123 void pthreads_thread_id(CRYPTO_THREADID *tid);
124 void netware_thread_id(CRYPTO_THREADID *tid);
125 void beos_thread_id(CRYPTO_THREADID *tid);
126
127 #if defined(OPENSSL_SYS_NETWARE)
128 static MPKMutex *lock_cs;
129 static MPKSema ThreadSem;
130 static long *lock_count;
131 #endif
132
133 BIO *bio_err = NULL;
134 BIO *bio_stdout = NULL;
135
136 static char *cipher = NULL;
137 int verbose = 0;
138 #ifdef FIONBIO
139 static int s_nbio = 0;
140 #endif
141
142 int thread_number = 10;
143 int number_of_loops = 10;
144 int reconnect = 0;
145 int cache_stats = 0;
146
147 static const char rnd_seed[] =
148     "string to make the random number generator think it has entropy";
149
150 int doit(char *ctx[4]);
151 static void print_stats(FILE *fp, SSL_CTX *ctx)
152 {
153     fprintf(fp, "%4ld items in the session cache\n",
154             SSL_CTX_sess_number(ctx));
155     fprintf(fp, "%4d client connects (SSL_connect())\n",
156             SSL_CTX_sess_connect(ctx));
157     fprintf(fp, "%4d client connects that finished\n",
158             SSL_CTX_sess_connect_good(ctx));
159     fprintf(fp, "%4d server connects (SSL_accept())\n",
160             SSL_CTX_sess_accept(ctx));
161     fprintf(fp, "%4d server connects that finished\n",
162             SSL_CTX_sess_accept_good(ctx));
163     fprintf(fp, "%4d session cache hits\n", SSL_CTX_sess_hits(ctx));
164     fprintf(fp, "%4d session cache misses\n", SSL_CTX_sess_misses(ctx));
165     fprintf(fp, "%4d session cache timeouts\n", SSL_CTX_sess_timeouts(ctx));
166 }
167
168 static void sv_usage(void)
169 {
170     fprintf(stderr, "usage: ssltest [args ...]\n");
171     fprintf(stderr, "\n");
172     fprintf(stderr, " -server_auth  - check server certificate\n");
173     fprintf(stderr, " -client_auth  - do client authentication\n");
174     fprintf(stderr, " -v            - more output\n");
175     fprintf(stderr, " -CApath arg   - PEM format directory of CA's\n");
176     fprintf(stderr, " -CAfile arg   - PEM format file of CA's\n");
177     fprintf(stderr, " -threads arg  - number of threads\n");
178     fprintf(stderr, " -loops arg    - number of 'connections', per thread\n");
179     fprintf(stderr, " -reconnect    - reuse session-id's\n");
180     fprintf(stderr, " -stats        - server session-id cache stats\n");
181     fprintf(stderr, " -cert arg     - server certificate/key\n");
182     fprintf(stderr, " -ccert arg    - client certificate/key\n");
183     fprintf(stderr, " -ssl3         - just SSLv3n\n");
184 }
185
186 int main(int argc, char *argv[])
187 {
188     char *CApath = NULL, *CAfile = NULL;
189     int badop = 0;
190     int ret = 1;
191     int client_auth = 0;
192     int server_auth = 0;
193     SSL_CTX *s_ctx = NULL;
194     SSL_CTX *c_ctx = NULL;
195     char *scert = TEST_SERVER_CERT;
196     char *ccert = TEST_CLIENT_CERT;
197     SSL_METHOD *ssl_method = TLS_method();
198
199     RAND_seed(rnd_seed, sizeof rnd_seed);
200
201     if (bio_err == NULL)
202         bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
203     if (bio_stdout == NULL)
204         bio_stdout = BIO_new_fp(stdout, BIO_NOCLOSE);
205     argc--;
206     argv++;
207
208     while (argc >= 1) {
209         if (strcmp(*argv, "-server_auth") == 0)
210             server_auth = 1;
211         else if (strcmp(*argv, "-client_auth") == 0)
212             client_auth = 1;
213         else if (strcmp(*argv, "-reconnect") == 0)
214             reconnect = 1;
215         else if (strcmp(*argv, "-stats") == 0)
216             cache_stats = 1;
217         else if (strcmp(*argv, "-ssl3") == 0)
218             ssl_method = SSLv3_method();
219         else if (strcmp(*argv, "-CApath") == 0) {
220             if (--argc < 1)
221                 goto bad;
222             CApath = *(++argv);
223         } else if (strcmp(*argv, "-CAfile") == 0) {
224             if (--argc < 1)
225                 goto bad;
226             CAfile = *(++argv);
227         } else if (strcmp(*argv, "-cert") == 0) {
228             if (--argc < 1)
229                 goto bad;
230             scert = *(++argv);
231         } else if (strcmp(*argv, "-ccert") == 0) {
232             if (--argc < 1)
233                 goto bad;
234             ccert = *(++argv);
235         } else if (strcmp(*argv, "-threads") == 0) {
236             if (--argc < 1)
237                 goto bad;
238             thread_number = atoi(*(++argv));
239             if (thread_number == 0)
240                 thread_number = 1;
241             if (thread_number > MAX_THREAD_NUMBER)
242                 thread_number = MAX_THREAD_NUMBER;
243         } else if (strcmp(*argv, "-loops") == 0) {
244             if (--argc < 1)
245                 goto bad;
246             number_of_loops = atoi(*(++argv));
247             if (number_of_loops == 0)
248                 number_of_loops = 1;
249         } else {
250             fprintf(stderr, "unknown option %s\n", *argv);
251             badop = 1;
252             break;
253         }
254         argc--;
255         argv++;
256     }
257     if (badop) {
258  bad:
259         sv_usage();
260         goto end;
261     }
262
263     if (cipher == NULL && OPENSSL_issetugid() == 0)
264         cipher = getenv("SSL_CIPHER");
265
266     SSL_load_error_strings();
267     OpenSSL_add_ssl_algorithms();
268
269     c_ctx = SSL_CTX_new(ssl_method);
270     s_ctx = SSL_CTX_new(ssl_method);
271     if ((c_ctx == NULL) || (s_ctx == NULL)) {
272         ERR_print_errors(bio_err);
273         goto end;
274     }
275
276     SSL_CTX_set_session_cache_mode(s_ctx,
277                                    SSL_SESS_CACHE_NO_AUTO_CLEAR |
278                                    SSL_SESS_CACHE_SERVER);
279     SSL_CTX_set_session_cache_mode(c_ctx,
280                                    SSL_SESS_CACHE_NO_AUTO_CLEAR |
281                                    SSL_SESS_CACHE_SERVER);
282
283     if (!SSL_CTX_use_certificate_file(s_ctx, scert, SSL_FILETYPE_PEM)) {
284         ERR_print_errors(bio_err);
285     } else
286         if (!SSL_CTX_use_RSAPrivateKey_file(s_ctx, scert, SSL_FILETYPE_PEM)) {
287         ERR_print_errors(bio_err);
288         goto end;
289     }
290
291     if (client_auth) {
292         SSL_CTX_use_certificate_file(c_ctx, ccert, SSL_FILETYPE_PEM);
293         SSL_CTX_use_RSAPrivateKey_file(c_ctx, ccert, SSL_FILETYPE_PEM);
294     }
295
296     if ((!SSL_CTX_load_verify_locations(s_ctx, CAfile, CApath)) ||
297         (!SSL_CTX_set_default_verify_paths(s_ctx)) ||
298         (!SSL_CTX_load_verify_locations(c_ctx, CAfile, CApath)) ||
299         (!SSL_CTX_set_default_verify_paths(c_ctx))) {
300         fprintf(stderr, "SSL_load_verify_locations\n");
301         ERR_print_errors(bio_err);
302         goto end;
303     }
304
305     if (client_auth) {
306         fprintf(stderr, "client authentication\n");
307         SSL_CTX_set_verify(s_ctx,
308                            SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
309                            verify_callback);
310     }
311     if (server_auth) {
312         fprintf(stderr, "server authentication\n");
313         SSL_CTX_set_verify(c_ctx, SSL_VERIFY_PEER, verify_callback);
314     }
315
316     thread_setup();
317     do_threads(s_ctx, c_ctx);
318     thread_cleanup();
319  end:
320
321     if (c_ctx != NULL) {
322         fprintf(stderr, "Client SSL_CTX stats then free it\n");
323         print_stats(stderr, c_ctx);
324         SSL_CTX_free(c_ctx);
325     }
326     if (s_ctx != NULL) {
327         fprintf(stderr, "Server SSL_CTX stats then free it\n");
328         print_stats(stderr, s_ctx);
329         if (cache_stats) {
330             fprintf(stderr, "-----\n");
331             lh_stats(SSL_CTX_sessions(s_ctx), stderr);
332             fprintf(stderr, "-----\n");
333                 /*-     lh_node_stats(SSL_CTX_sessions(s_ctx),stderr);
334                         fprintf(stderr,"-----\n"); */
335             lh_node_usage_stats(SSL_CTX_sessions(s_ctx), stderr);
336             fprintf(stderr, "-----\n");
337         }
338         SSL_CTX_free(s_ctx);
339         fprintf(stderr, "done free\n");
340     }
341     exit(ret);
342     return (0);
343 }
344
345 #define W_READ  1
346 #define W_WRITE 2
347 #define C_DONE  1
348 #define S_DONE  2
349
350 int ndoit(SSL_CTX *ssl_ctx[2])
351 {
352     int i;
353     int ret;
354     char *ctx[4];
355     CRYPTO_THREADID thread_id;
356
357     ctx[0] = (char *)ssl_ctx[0];
358     ctx[1] = (char *)ssl_ctx[1];
359
360     if (reconnect) {
361         ctx[2] = (char *)SSL_new(ssl_ctx[0]);
362         ctx[3] = (char *)SSL_new(ssl_ctx[1]);
363     } else {
364         ctx[2] = NULL;
365         ctx[3] = NULL;
366     }
367
368     CRYPTO_THREADID_current(&thread_id);
369     BIO_printf(bio_stdout, "started thread %lu\n",
370                CRYPTO_THREADID_hash(&thread_id));
371     for (i = 0; i < number_of_loops; i++) {
372 /*-     BIO_printf(bio_err,"%4d %2d ctx->ref (%3d,%3d)\n",
373                    CRYPTO_THREADID_hash(&thread_id),i,
374                    ssl_ctx[0]->references,
375                    ssl_ctx[1]->references); */
376 /*      pthread_delay_np(&tm); */
377
378         ret = doit(ctx);
379         if (ret != 0) {
380             BIO_printf(bio_stdout, "error[%d] %lu - %d\n",
381                        i, CRYPTO_THREADID_hash(&thread_id), ret);
382             return (ret);
383         }
384     }
385     BIO_printf(bio_stdout, "DONE %lu\n", CRYPTO_THREADID_hash(&thread_id));
386     if (reconnect) {
387         SSL_free((SSL *)ctx[2]);
388         SSL_free((SSL *)ctx[3]);
389     }
390 #ifdef OPENSSL_SYS_NETWARE
391     MPKSemaphoreSignal(ThreadSem);
392 #endif
393     return (0);
394 }
395
396 int doit(char *ctx[4])
397 {
398     SSL_CTX *s_ctx, *c_ctx;
399     static char cbuf[200], sbuf[200];
400     SSL *c_ssl = NULL;
401     SSL *s_ssl = NULL;
402     BIO *c_to_s = NULL;
403     BIO *s_to_c = NULL;
404     BIO *c_bio = NULL;
405     BIO *s_bio = NULL;
406     int c_r, c_w, s_r, s_w;
407     int c_want, s_want;
408     int i;
409     int done = 0;
410     int c_write, s_write;
411     int do_server = 0, do_client = 0;
412
413     s_ctx = (SSL_CTX *)ctx[0];
414     c_ctx = (SSL_CTX *)ctx[1];
415
416     if (ctx[2] != NULL)
417         s_ssl = (SSL *)ctx[2];
418     else
419         s_ssl = SSL_new(s_ctx);
420
421     if (ctx[3] != NULL)
422         c_ssl = (SSL *)ctx[3];
423     else
424         c_ssl = SSL_new(c_ctx);
425
426     if ((s_ssl == NULL) || (c_ssl == NULL))
427         goto err;
428
429     c_to_s = BIO_new(BIO_s_mem());
430     s_to_c = BIO_new(BIO_s_mem());
431     if ((s_to_c == NULL) || (c_to_s == NULL))
432         goto err;
433
434     c_bio = BIO_new(BIO_f_ssl());
435     s_bio = BIO_new(BIO_f_ssl());
436     if ((c_bio == NULL) || (s_bio == NULL))
437         goto err;
438
439     SSL_set_connect_state(c_ssl);
440     SSL_set_bio(c_ssl, s_to_c, c_to_s);
441     BIO_set_ssl(c_bio, c_ssl, (ctx[2] == NULL) ? BIO_CLOSE : BIO_NOCLOSE);
442
443     SSL_set_accept_state(s_ssl);
444     SSL_set_bio(s_ssl, c_to_s, s_to_c);
445     BIO_set_ssl(s_bio, s_ssl, (ctx[3] == NULL) ? BIO_CLOSE : BIO_NOCLOSE);
446
447     c_r = 0;
448     s_r = 1;
449     c_w = 1;
450     s_w = 0;
451     c_want = W_WRITE;
452     s_want = 0;
453     c_write = 1, s_write = 0;
454
455     /* We can always do writes */
456     for (;;) {
457         do_server = 0;
458         do_client = 0;
459
460         i = (int)BIO_pending(s_bio);
461         if ((i && s_r) || s_w)
462             do_server = 1;
463
464         i = (int)BIO_pending(c_bio);
465         if ((i && c_r) || c_w)
466             do_client = 1;
467
468         if (do_server && verbose) {
469             if (SSL_in_init(s_ssl))
470                 printf("server waiting in SSL_accept - %s\n",
471                        SSL_state_string_long(s_ssl));
472             else if (s_write)
473                 printf("server:SSL_write()\n");
474             else
475                 printf("server:SSL_read()\n");
476         }
477
478         if (do_client && verbose) {
479             if (SSL_in_init(c_ssl))
480                 printf("client waiting in SSL_connect - %s\n",
481                        SSL_state_string_long(c_ssl));
482             else if (c_write)
483                 printf("client:SSL_write()\n");
484             else
485                 printf("client:SSL_read()\n");
486         }
487
488         if (!do_client && !do_server) {
489             fprintf(stdout, "ERROR IN STARTUP\n");
490             break;
491         }
492         if (do_client && !(done & C_DONE)) {
493             if (c_write) {
494                 i = BIO_write(c_bio, "hello from client\n", 18);
495                 if (i < 0) {
496                     c_r = 0;
497                     c_w = 0;
498                     if (BIO_should_retry(c_bio)) {
499                         if (BIO_should_read(c_bio))
500                             c_r = 1;
501                         if (BIO_should_write(c_bio))
502                             c_w = 1;
503                     } else {
504                         fprintf(stderr, "ERROR in CLIENT\n");
505                         ERR_print_errors_fp(stderr);
506                         return (1);
507                     }
508                 } else if (i == 0) {
509                     fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
510                     return (1);
511                 } else {
512                     /* ok */
513                     c_write = 0;
514                 }
515             } else {
516                 i = BIO_read(c_bio, cbuf, 100);
517                 if (i < 0) {
518                     c_r = 0;
519                     c_w = 0;
520                     if (BIO_should_retry(c_bio)) {
521                         if (BIO_should_read(c_bio))
522                             c_r = 1;
523                         if (BIO_should_write(c_bio))
524                             c_w = 1;
525                     } else {
526                         fprintf(stderr, "ERROR in CLIENT\n");
527                         ERR_print_errors_fp(stderr);
528                         return (1);
529                     }
530                 } else if (i == 0) {
531                     fprintf(stderr, "SSL CLIENT STARTUP FAILED\n");
532                     return (1);
533                 } else {
534                     done |= C_DONE;
535                 }
536             }
537         }
538
539         if (do_server && !(done & S_DONE)) {
540             if (!s_write) {
541                 i = BIO_read(s_bio, sbuf, 100);
542                 if (i < 0) {
543                     s_r = 0;
544                     s_w = 0;
545                     if (BIO_should_retry(s_bio)) {
546                         if (BIO_should_read(s_bio))
547                             s_r = 1;
548                         if (BIO_should_write(s_bio))
549                             s_w = 1;
550                     } else {
551                         fprintf(stderr, "ERROR in SERVER\n");
552                         ERR_print_errors_fp(stderr);
553                         return (1);
554                     }
555                 } else if (i == 0) {
556                     fprintf(stderr, "SSL SERVER STARTUP FAILED\n");
557                     return (1);
558                 } else {
559                     s_write = 1;
560                     s_w = 1;
561                 }
562             } else {
563                 i = BIO_write(s_bio, "hello from server\n", 18);
564                 if (i < 0) {
565                     s_r = 0;
566                     s_w = 0;
567                     if (BIO_should_retry(s_bio)) {
568                         if (BIO_should_read(s_bio))
569                             s_r = 1;
570                         if (BIO_should_write(s_bio))
571                             s_w = 1;
572                     } else {
573                         fprintf(stderr, "ERROR in SERVER\n");
574                         ERR_print_errors_fp(stderr);
575                         return (1);
576                     }
577                 } else if (i == 0) {
578                     fprintf(stderr, "SSL SERVER STARTUP FAILED\n");
579                     return (1);
580                 } else {
581                     s_write = 0;
582                     s_r = 1;
583                     done |= S_DONE;
584                 }
585             }
586         }
587
588         if ((done & S_DONE) && (done & C_DONE))
589             break;
590 #if defined(OPENSSL_SYS_NETWARE)
591         ThreadSwitchWithDelay();
592 #endif
593     }
594
595     SSL_set_shutdown(c_ssl, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
596     SSL_set_shutdown(s_ssl, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
597
598  err:
599     /*
600      * We have to set the BIO's to NULL otherwise they will be free()ed
601      * twice.  Once when th s_ssl is SSL_free()ed and again when c_ssl is
602      * SSL_free()ed. This is a hack required because s_ssl and c_ssl are
603      * sharing the same BIO structure and SSL_set_bio() and SSL_free()
604      * automatically BIO_free non NULL entries. You should not normally do
605      * this or be required to do this
606      */
607
608     if (s_ssl != NULL) {
609         s_ssl->rbio = NULL;
610         s_ssl->wbio = NULL;
611     }
612     if (c_ssl != NULL) {
613         c_ssl->rbio = NULL;
614         c_ssl->wbio = NULL;
615     }
616
617     /* The SSL's are optionally freed in the following calls */
618     BIO_free(c_to_s);
619     BIO_free(s_to_c);
620
621     BIO_free(c_bio);
622     BIO_free(s_bio);
623     return (0);
624 }
625
626 int verify_callback(int ok, X509_STORE_CTX *ctx)
627 {
628     char *s, buf[256];
629
630     if (verbose) {
631         s = X509_NAME_oneline(X509_get_subject_name(ctx->current_cert),
632                               buf, 256);
633         if (s != NULL) {
634             if (ok)
635                 fprintf(stderr, "depth=%d %s\n", ctx->error_depth, buf);
636             else
637                 fprintf(stderr, "depth=%d error=%d %s\n",
638                         ctx->error_depth, ctx->error, buf);
639         }
640     }
641     return (ok);
642 }
643
644 #define THREAD_STACK_SIZE (16*1024)
645
646 #ifdef OPENSSL_SYS_WIN32
647
648 static HANDLE *lock_cs;
649
650 void thread_setup(void)
651 {
652     int i;
653
654     lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(HANDLE));
655     for (i = 0; i < CRYPTO_num_locks(); i++) {
656         lock_cs[i] = CreateMutex(NULL, FALSE, NULL);
657     }
658
659     CRYPTO_set_locking_callback((void (*)(int, int, char *, int))
660                                 win32_locking_callback);
661     /* id callback defined */
662 }
663
664 void thread_cleanup(void)
665 {
666     int i;
667
668     CRYPTO_set_locking_callback(NULL);
669     for (i = 0; i < CRYPTO_num_locks(); i++)
670         CloseHandle(lock_cs[i]);
671     OPENSSL_free(lock_cs);
672 }
673
674 void win32_locking_callback(int mode, int type, const char *file, int line)
675 {
676     if (mode & CRYPTO_LOCK) {
677         WaitForSingleObject(lock_cs[type], INFINITE);
678     } else {
679         ReleaseMutex(lock_cs[type]);
680     }
681 }
682
683 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
684 {
685     double ret;
686     SSL_CTX *ssl_ctx[2];
687     DWORD thread_id[MAX_THREAD_NUMBER];
688     HANDLE thread_handle[MAX_THREAD_NUMBER];
689     int i;
690     SYSTEMTIME start, end;
691
692     ssl_ctx[0] = s_ctx;
693     ssl_ctx[1] = c_ctx;
694
695     GetSystemTime(&start);
696     for (i = 0; i < thread_number; i++) {
697         thread_handle[i] = CreateThread(NULL,
698                                         THREAD_STACK_SIZE,
699                                         (LPTHREAD_START_ROUTINE) ndoit,
700                                         (void *)ssl_ctx, 0L, &(thread_id[i]));
701     }
702
703     printf("reaping\n");
704     for (i = 0; i < thread_number; i += 50) {
705         int j;
706
707         j = (thread_number < (i + 50)) ? (thread_number - i) : 50;
708
709         if (WaitForMultipleObjects(j,
710                                    (CONST HANDLE *) & (thread_handle[i]),
711                                    TRUE, INFINITE)
712             == WAIT_FAILED) {
713             fprintf(stderr, "WaitForMultipleObjects failed:%d\n",
714                     GetLastError());
715             exit(1);
716         }
717     }
718     GetSystemTime(&end);
719
720     if (start.wDayOfWeek > end.wDayOfWeek)
721         end.wDayOfWeek += 7;
722     ret = (end.wDayOfWeek - start.wDayOfWeek) * 24;
723
724     ret = (ret + end.wHour - start.wHour) * 60;
725     ret = (ret + end.wMinute - start.wMinute) * 60;
726     ret = (ret + end.wSecond - start.wSecond);
727     ret += (end.wMilliseconds - start.wMilliseconds) / 1000.0;
728
729     printf("win32 threads done - %.3f seconds\n", ret);
730 }
731
732 #endif                          /* OPENSSL_SYS_WIN32 */
733
734 #ifdef SOLARIS
735
736 static mutex_t *lock_cs;
737 /*
738  * static rwlock_t *lock_cs;
739  */
740 static long *lock_count;
741
742 void thread_setup(void)
743 {
744     int i;
745
746     lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(mutex_t));
747     lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
748     for (i = 0; i < CRYPTO_num_locks(); i++) {
749         lock_count[i] = 0;
750         /* rwlock_init(&(lock_cs[i]),USYNC_THREAD,NULL); */
751         mutex_init(&(lock_cs[i]), USYNC_THREAD, NULL);
752     }
753
754     CRYPTO_set_id_callback(solaris_thread_id);
755     CRYPTO_set_locking_callback(solaris_locking_callback);
756 }
757
758 void thread_cleanup(void)
759 {
760     int i;
761
762     CRYPTO_set_locking_callback(NULL);
763
764     fprintf(stderr, "cleanup\n");
765
766     for (i = 0; i < CRYPTO_num_locks(); i++) {
767         /* rwlock_destroy(&(lock_cs[i])); */
768         mutex_destroy(&(lock_cs[i]));
769         fprintf(stderr, "%8ld:%s\n", lock_count[i], CRYPTO_get_lock_name(i));
770     }
771     OPENSSL_free(lock_cs);
772     OPENSSL_free(lock_count);
773
774     fprintf(stderr, "done cleanup\n");
775
776 }
777
778 void solaris_locking_callback(int mode, int type, const char *file, int line)
779 {
780     if (mode & CRYPTO_LOCK) {
781         mutex_lock(&(lock_cs[type]));
782         lock_count[type]++;
783     } else {
784         mutex_unlock(&(lock_cs[type]));
785     }
786 }
787
788 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
789 {
790     SSL_CTX *ssl_ctx[2];
791     thread_t thread_ctx[MAX_THREAD_NUMBER];
792     int i;
793
794     ssl_ctx[0] = s_ctx;
795     ssl_ctx[1] = c_ctx;
796
797     thr_setconcurrency(thread_number);
798     for (i = 0; i < thread_number; i++) {
799         thr_create(NULL, THREAD_STACK_SIZE,
800                    (void *(*)())ndoit, (void *)ssl_ctx, 0L, &(thread_ctx[i]));
801     }
802
803     printf("reaping\n");
804     for (i = 0; i < thread_number; i++) {
805         thr_join(thread_ctx[i], NULL, NULL);
806     }
807
808     printf("solaris threads done (%d,%d)\n",
809            s_ctx->references, c_ctx->references);
810 }
811
812 void solaris_thread_id(CRYPTO_THREADID *tid)
813 {
814     CRYPTO_THREADID_set_numeric((unsigned long)thr_self());
815 }
816 #endif                          /* SOLARIS */
817
818 #ifdef IRIX
819
820 static usptr_t *arena;
821 static usema_t **lock_cs;
822
823 void thread_setup(void)
824 {
825     int i;
826     char filename[20];
827
828     strcpy(filename, "/tmp/mttest.XXXXXX");
829     mktemp(filename);
830
831     usconfig(CONF_STHREADIOOFF);
832     usconfig(CONF_STHREADMALLOCOFF);
833     usconfig(CONF_INITUSERS, 100);
834     usconfig(CONF_LOCKTYPE, US_DEBUGPLUS);
835     arena = usinit(filename);
836     unlink(filename);
837
838     lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(usema_t *));
839     for (i = 0; i < CRYPTO_num_locks(); i++) {
840         lock_cs[i] = usnewsema(arena, 1);
841     }
842
843     CRYPTO_set_id_callback(irix_thread_id);
844     CRYPTO_set_locking_callback(irix_locking_callback);
845 }
846
847 void thread_cleanup(void)
848 {
849     int i;
850
851     CRYPTO_set_locking_callback(NULL);
852     for (i = 0; i < CRYPTO_num_locks(); i++) {
853         char buf[10];
854
855         sprintf(buf, "%2d:", i);
856         usdumpsema(lock_cs[i], stdout, buf);
857         usfreesema(lock_cs[i], arena);
858     }
859     OPENSSL_free(lock_cs);
860 }
861
862 void irix_locking_callback(int mode, int type, const char *file, int line)
863 {
864     if (mode & CRYPTO_LOCK) {
865         printf("lock %d\n", type);
866         uspsema(lock_cs[type]);
867     } else {
868         printf("unlock %d\n", type);
869         usvsema(lock_cs[type]);
870     }
871 }
872
873 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
874 {
875     SSL_CTX *ssl_ctx[2];
876     int thread_ctx[MAX_THREAD_NUMBER];
877     int i;
878
879     ssl_ctx[0] = s_ctx;
880     ssl_ctx[1] = c_ctx;
881
882     for (i = 0; i < thread_number; i++) {
883         thread_ctx[i] = sproc((void (*)())ndoit,
884                               PR_SADDR | PR_SFDS, (void *)ssl_ctx);
885     }
886
887     printf("reaping\n");
888     for (i = 0; i < thread_number; i++) {
889         wait(NULL);
890     }
891
892     printf("irix threads done (%d,%d)\n",
893            s_ctx->references, c_ctx->references);
894 }
895
896 unsigned long irix_thread_id(void)
897 {
898     CRYPTO_THREADID_set_numeric((unsigned long)getpid());
899 }
900 #endif                          /* IRIX */
901
902 #ifdef PTHREADS
903
904 static pthread_mutex_t *lock_cs;
905 static long *lock_count;
906
907 void thread_setup(void)
908 {
909     int i;
910
911     lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
912     lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
913     for (i = 0; i < CRYPTO_num_locks(); i++) {
914         lock_count[i] = 0;
915         pthread_mutex_init(&(lock_cs[i]), NULL);
916     }
917
918     CRYPTO_THREADID_set_callback(pthreads_thread_id);
919     CRYPTO_set_locking_callback(pthreads_locking_callback);
920 }
921
922 void thread_cleanup(void)
923 {
924     int i;
925
926     CRYPTO_set_locking_callback(NULL);
927     fprintf(stderr, "cleanup\n");
928     for (i = 0; i < CRYPTO_num_locks(); i++) {
929         pthread_mutex_destroy(&(lock_cs[i]));
930         fprintf(stderr, "%8ld:%s\n", lock_count[i], CRYPTO_get_lock_name(i));
931     }
932     OPENSSL_free(lock_cs);
933     OPENSSL_free(lock_count);
934
935     fprintf(stderr, "done cleanup\n");
936 }
937
938 void pthreads_locking_callback(int mode, int type, const char *file, int line)
939 {
940     if (mode & CRYPTO_LOCK) {
941         pthread_mutex_lock(&(lock_cs[type]));
942         lock_count[type]++;
943     } else {
944         pthread_mutex_unlock(&(lock_cs[type]));
945     }
946 }
947
948 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
949 {
950     SSL_CTX *ssl_ctx[2];
951     pthread_t thread_ctx[MAX_THREAD_NUMBER];
952     int i;
953
954     ssl_ctx[0] = s_ctx;
955     ssl_ctx[1] = c_ctx;
956
957     /*
958      * thr_setconcurrency(thread_number);
959      */
960     for (i = 0; i < thread_number; i++) {
961         pthread_create(&(thread_ctx[i]), NULL,
962                        (void *(*)())ndoit, (void *)ssl_ctx);
963     }
964
965     printf("reaping\n");
966     for (i = 0; i < thread_number; i++) {
967         pthread_join(thread_ctx[i], NULL);
968     }
969
970     printf("pthreads threads done (%d,%d)\n",
971            s_ctx->references, c_ctx->references);
972 }
973
974 void pthreads_thread_id(CRYPTO_THREADID *tid)
975 {
976     CRYPTO_THREADID_set_numeric(tid, (unsigned long)pthread_self());
977 }
978
979 #endif                          /* PTHREADS */
980
981 #ifdef OPENSSL_SYS_NETWARE
982
983 void thread_setup(void)
984 {
985     int i;
986
987     lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(MPKMutex));
988     lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
989     for (i = 0; i < CRYPTO_num_locks(); i++) {
990         lock_count[i] = 0;
991         lock_cs[i] = MPKMutexAlloc("OpenSSL mutex");
992     }
993
994     ThreadSem = MPKSemaphoreAlloc("OpenSSL mttest semaphore", 0);
995
996     CRYPTO_set_id_callback(netware_thread_id);
997     CRYPTO_set_locking_callback(netware_locking_callback);
998 }
999
1000 void thread_cleanup(void)
1001 {
1002     int i;
1003
1004     CRYPTO_set_locking_callback(NULL);
1005
1006     fprintf(stdout, "thread_cleanup\n");
1007
1008     for (i = 0; i < CRYPTO_num_locks(); i++) {
1009         MPKMutexFree(lock_cs[i]);
1010         fprintf(stdout, "%8ld:%s\n", lock_count[i], CRYPTO_get_lock_name(i));
1011     }
1012     OPENSSL_free(lock_cs);
1013     OPENSSL_free(lock_count);
1014
1015     MPKSemaphoreFree(ThreadSem);
1016
1017     fprintf(stdout, "done cleanup\n");
1018 }
1019
1020 void netware_locking_callback(int mode, int type, const char *file, int line)
1021 {
1022     if (mode & CRYPTO_LOCK) {
1023         MPKMutexLock(lock_cs[type]);
1024         lock_count[type]++;
1025     } else
1026         MPKMutexUnlock(lock_cs[type]);
1027 }
1028
1029 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
1030 {
1031     SSL_CTX *ssl_ctx[2];
1032     int i;
1033     ssl_ctx[0] = s_ctx;
1034     ssl_ctx[1] = c_ctx;
1035
1036     for (i = 0; i < thread_number; i++) {
1037         BeginThread((void (*)(void *))ndoit, NULL, THREAD_STACK_SIZE,
1038                     (void *)ssl_ctx);
1039         ThreadSwitchWithDelay();
1040     }
1041
1042     printf("reaping\n");
1043
1044     /* loop until all threads have signaled the semaphore */
1045     for (i = 0; i < thread_number; i++) {
1046         MPKSemaphoreWait(ThreadSem);
1047     }
1048     printf("netware threads done (%d,%d)\n",
1049            s_ctx->references, c_ctx->references);
1050 }
1051
1052 unsigned long netware_thread_id(void)
1053 {
1054     CRYPTO_THREADID_set_numeric((unsigned long)GetThreadID());
1055 }
1056 #endif                          /* NETWARE */