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