Remove HAMC_cleanup
[oweals/openssl.git] / demos / threads / mttest.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57
58 #include <stdlib.h>
59 #include <string.h>
60 #include <errno.h>
61 #ifdef LINUX
62 # include <typedefs.h>
63 #endif
64 #ifdef OPENSSL_SYS_WIN32
65 # include <windows.h>
66 #endif
67 #ifdef PTHREADS
68 # include <pthread.h>
69 #endif
70 #include <openssl/lhash.h>
71 #include <openssl/crypto.h>
72 #include <openssl/buffer.h>
73 #include <openssl/x509.h>
74 #include <openssl/ssl.h>
75 #include <openssl/err.h>
76 #include <openssl/rand.h>
77
78 #define TEST_SERVER_CERT "../../apps/server.pem"
79 #define TEST_CLIENT_CERT "../../apps/client.pem"
80
81 #define MAX_THREAD_NUMBER       100
82
83 int verify_callback(int ok, X509_STORE_CTX *xs);
84 void thread_setup(void);
85 void thread_cleanup(void);
86 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx);
87
88 void win32_locking_callback(int mode, int type, const char *file, int line);
89 void pthreads_locking_callback(int mode, int type, const char *file, int line);
90
91 void irix_thread_id(CRYPTO_THREADID *tid);
92 void pthreads_thread_id(CRYPTO_THREADID *tid);
93
94 BIO *bio_err = NULL;
95 BIO *bio_stdout = NULL;
96
97 static char *cipher = NULL;
98 int verbose = 0;
99 #ifdef FIONBIO
100 static int s_nbio = 0;
101 #endif
102
103 int thread_number = 10;
104 int number_of_loops = 10;
105 int reconnect = 0;
106 int cache_stats = 0;
107
108 static const char rnd_seed[] =
109     "string to make the random number generator think it has entropy";
110
111 int doit(char *ctx[4]);
112 static void print_stats(BIO *bio, SSL_CTX *ctx)
113 {
114     BIO_printf(bio, "%4ld items in the session cache\n",
115                SSL_CTX_sess_number(ctx));
116     BIO_printf(bio, "%4d client connects (SSL_connect())\n",
117                SSL_CTX_sess_connect(ctx));
118     BIO_printf(bio, "%4d client connects that finished\n",
119                SSL_CTX_sess_connect_good(ctx));
120     BIO_printf(bio, "%4d server connects (SSL_accept())\n",
121                SSL_CTX_sess_accept(ctx));
122     BIO_printf(bio, "%4d server connects that finished\n",
123                SSL_CTX_sess_accept_good(ctx));
124     BIO_printf(bio, "%4d session cache hits\n", SSL_CTX_sess_hits(ctx));
125     BIO_printf(bio, "%4d session cache misses\n", SSL_CTX_sess_misses(ctx));
126     BIO_printf(bio, "%4d session cache timeouts\n", SSL_CTX_sess_timeouts(ctx));
127 }
128
129 static void sv_usage(void)
130 {
131     BIO_printf(bio_err, "usage: ssltest [args ...]\n");
132     BIO_printf(bio_err, "\n");
133     BIO_printf(bio_err, " -server_auth  - check server certificate\n");
134     BIO_printf(bio_err, " -client_auth  - do client authentication\n");
135     BIO_printf(bio_err, " -v            - more output\n");
136     BIO_printf(bio_err, " -CApath arg   - PEM format directory of CA's\n");
137     BIO_printf(bio_err, " -CAfile arg   - PEM format file of CA's\n");
138     BIO_printf(bio_err, " -threads arg  - number of threads\n");
139     BIO_printf(bio_err, " -loops arg    - number of 'connections', per thread\n");
140     BIO_printf(bio_err, " -reconnect    - reuse session-id's\n");
141     BIO_printf(bio_err, " -stats        - server session-id cache stats\n");
142     BIO_printf(bio_err, " -cert arg     - server certificate/key\n");
143     BIO_printf(bio_err, " -ccert arg    - client certificate/key\n");
144     BIO_printf(bio_err, " -ssl3         - just SSLv3n\n");
145 }
146
147 int main(int argc, char *argv[])
148 {
149     char *CApath = NULL, *CAfile = NULL;
150     int badop = 0;
151     int ret = 1;
152     int client_auth = 0;
153     int server_auth = 0;
154     SSL_CTX *s_ctx = NULL;
155     SSL_CTX *c_ctx = NULL;
156     char *scert = TEST_SERVER_CERT;
157     char *ccert = TEST_CLIENT_CERT;
158     const SSL_METHOD *ssl_method = TLS_method();
159
160     RAND_seed(rnd_seed, sizeof rnd_seed);
161
162     if (bio_err == NULL)
163         bio_err = BIO_new_fd(2, BIO_NOCLOSE);
164     if (bio_stdout == NULL)
165         bio_stdout = BIO_new_fd(1, BIO_NOCLOSE);
166     argc--;
167     argv++;
168
169     while (argc >= 1) {
170         if (strcmp(*argv, "-server_auth") == 0)
171             server_auth = 1;
172         else if (strcmp(*argv, "-client_auth") == 0)
173             client_auth = 1;
174         else if (strcmp(*argv, "-reconnect") == 0)
175             reconnect = 1;
176         else if (strcmp(*argv, "-stats") == 0)
177             cache_stats = 1;
178         else if (strcmp(*argv, "-ssl3") == 0)
179             ssl_method = SSLv3_method();
180         else if (strcmp(*argv, "-CApath") == 0) {
181             if (--argc < 1)
182                 goto bad;
183             CApath = *(++argv);
184         } else if (strcmp(*argv, "-CAfile") == 0) {
185             if (--argc < 1)
186                 goto bad;
187             CAfile = *(++argv);
188         } else if (strcmp(*argv, "-cert") == 0) {
189             if (--argc < 1)
190                 goto bad;
191             scert = *(++argv);
192         } else if (strcmp(*argv, "-ccert") == 0) {
193             if (--argc < 1)
194                 goto bad;
195             ccert = *(++argv);
196         } else if (strcmp(*argv, "-threads") == 0) {
197             if (--argc < 1)
198                 goto bad;
199             thread_number = atoi(*(++argv));
200             if (thread_number == 0)
201                 thread_number = 1;
202             if (thread_number > MAX_THREAD_NUMBER)
203                 thread_number = MAX_THREAD_NUMBER;
204         } else if (strcmp(*argv, "-loops") == 0) {
205             if (--argc < 1)
206                 goto bad;
207             number_of_loops = atoi(*(++argv));
208             if (number_of_loops == 0)
209                 number_of_loops = 1;
210         } else {
211             BIO_printf(bio_err, "unknown option %s\n", *argv);
212             badop = 1;
213             break;
214         }
215         argc--;
216         argv++;
217     }
218     if (badop) {
219  bad:
220         sv_usage();
221         goto end;
222     }
223
224     if (cipher == NULL && OPENSSL_issetugid() == 0)
225         cipher = getenv("SSL_CIPHER");
226
227     SSL_load_error_strings();
228     OpenSSL_add_ssl_algorithms();
229
230     c_ctx = SSL_CTX_new(ssl_method);
231     s_ctx = SSL_CTX_new(ssl_method);
232     if ((c_ctx == NULL) || (s_ctx == NULL)) {
233         ERR_print_errors(bio_err);
234         goto end;
235     }
236
237     SSL_CTX_set_session_cache_mode(s_ctx,
238                                    SSL_SESS_CACHE_NO_AUTO_CLEAR |
239                                    SSL_SESS_CACHE_SERVER);
240     SSL_CTX_set_session_cache_mode(c_ctx,
241                                    SSL_SESS_CACHE_NO_AUTO_CLEAR |
242                                    SSL_SESS_CACHE_SERVER);
243
244     if (!SSL_CTX_use_certificate_file(s_ctx, scert, SSL_FILETYPE_PEM)) {
245         BIO_printf(bio_err, "SSL_CTX_use_certificate_file (%s)\n", scert);
246         ERR_print_errors(bio_err);
247         goto end;
248     } else
249         if (!SSL_CTX_use_RSAPrivateKey_file(s_ctx, scert, SSL_FILETYPE_PEM)) {
250         BIO_printf(bio_err, "SSL_CTX_use_RSAPrivateKey_file (%s)\n", scert);
251         ERR_print_errors(bio_err);
252         goto end;
253     }
254
255     if (client_auth) {
256         SSL_CTX_use_certificate_file(c_ctx, ccert, SSL_FILETYPE_PEM);
257         SSL_CTX_use_RSAPrivateKey_file(c_ctx, ccert, SSL_FILETYPE_PEM);
258     }
259
260     if ((!SSL_CTX_load_verify_locations(s_ctx, CAfile, CApath)) ||
261         (!SSL_CTX_set_default_verify_paths(s_ctx)) ||
262         (!SSL_CTX_load_verify_locations(c_ctx, CAfile, CApath)) ||
263         (!SSL_CTX_set_default_verify_paths(c_ctx))) {
264         BIO_printf(bio_err, "SSL_load_verify_locations\n");
265         ERR_print_errors(bio_err);
266         goto end;
267     }
268
269     if (client_auth) {
270         BIO_printf(bio_err, "client authentication\n");
271         SSL_CTX_set_verify(s_ctx,
272                            SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
273                            verify_callback);
274     }
275     if (server_auth) {
276         BIO_printf(bio_err, "server authentication\n");
277         SSL_CTX_set_verify(c_ctx, SSL_VERIFY_PEER, verify_callback);
278     }
279
280     thread_setup();
281     do_threads(s_ctx, c_ctx);
282     thread_cleanup();
283  end:
284
285     if (c_ctx != NULL) {
286         BIO_printf(bio_err, "Client SSL_CTX stats then free it\n");
287         print_stats(bio_err, c_ctx);
288         SSL_CTX_free(c_ctx);
289     }
290     if (s_ctx != NULL) {
291         BIO_printf(bio_err, "Server SSL_CTX stats then free it\n");
292         print_stats(bio_err, s_ctx);
293         if (cache_stats) {
294             BIO_printf(bio_err, "-----\n");
295             lh_SSL_SESSION_stats_bio(SSL_CTX_sessions(s_ctx), bio_err);
296             BIO_printf(bio_err, "-----\n");
297     /*-     lh_SSL_SESSION_node_stats_bio(SSL_CTX_sessions(s_ctx),bio_err);
298             BIO_printf(bio_err,"-----\n"); */
299             lh_SSL_SESSION_node_usage_stats_bio(SSL_CTX_sessions(s_ctx), bio_err);
300             BIO_printf(bio_err, "-----\n");
301         }
302         SSL_CTX_free(s_ctx);
303         BIO_printf(bio_err, "done free\n");
304     }
305     exit(ret);
306     return (0);
307 }
308
309 #define W_READ  1
310 #define W_WRITE 2
311 #define C_DONE  1
312 #define S_DONE  2
313
314 int ndoit(SSL_CTX *ssl_ctx[2])
315 {
316     int i;
317     int ret;
318     char *ctx[4];
319     CRYPTO_THREADID thread_id;
320
321     ctx[0] = (char *)ssl_ctx[0];
322     ctx[1] = (char *)ssl_ctx[1];
323
324     if (reconnect) {
325         ctx[2] = (char *)SSL_new(ssl_ctx[0]);
326         ctx[3] = (char *)SSL_new(ssl_ctx[1]);
327     } else {
328         ctx[2] = NULL;
329         ctx[3] = NULL;
330     }
331
332     CRYPTO_THREADID_current(&thread_id);
333     BIO_printf(bio_stdout, "started thread %lu\n",
334                CRYPTO_THREADID_hash(&thread_id));
335     for (i = 0; i < number_of_loops; i++) {
336 /*-     BIO_printf(bio_err,"%4d %2d ctx->ref (%3d,%3d)\n",
337                    CRYPTO_THREADID_hash(&thread_id),i,
338                    ssl_ctx[0]->references,
339                    ssl_ctx[1]->references); */
340 /*      pthread_delay_np(&tm); */
341
342         ret = doit(ctx);
343         if (ret != 0) {
344             BIO_printf(bio_stdout, "error[%d] %lu - %d\n",
345                        i, CRYPTO_THREADID_hash(&thread_id), ret);
346             return (ret);
347         }
348     }
349     BIO_printf(bio_stdout, "DONE %lu\n", CRYPTO_THREADID_hash(&thread_id));
350     if (reconnect) {
351         SSL_free((SSL *)ctx[2]);
352         SSL_free((SSL *)ctx[3]);
353     }
354     return (0);
355 }
356
357 int doit(char *ctx[4])
358 {
359     SSL_CTX *s_ctx, *c_ctx;
360     static char cbuf[200], sbuf[200];
361     SSL *c_ssl = NULL;
362     SSL *s_ssl = NULL;
363     BIO *c_to_s = NULL;
364     BIO *s_to_c = NULL;
365     BIO *c_bio = NULL;
366     BIO *s_bio = NULL;
367     int c_r, c_w, s_r, s_w;
368     int c_want, s_want;
369     int i;
370     int done = 0;
371     int c_write, s_write;
372     int do_server = 0, do_client = 0;
373
374     s_ctx = (SSL_CTX *)ctx[0];
375     c_ctx = (SSL_CTX *)ctx[1];
376
377     if (ctx[2] != NULL)
378         s_ssl = (SSL *)ctx[2];
379     else
380         s_ssl = SSL_new(s_ctx);
381
382     if (ctx[3] != NULL)
383         c_ssl = (SSL *)ctx[3];
384     else
385         c_ssl = SSL_new(c_ctx);
386
387     if ((s_ssl == NULL) || (c_ssl == NULL))
388         goto err;
389
390     c_to_s = BIO_new(BIO_s_mem());
391     s_to_c = BIO_new(BIO_s_mem());
392     if ((s_to_c == NULL) || (c_to_s == NULL))
393         goto err;
394
395     c_bio = BIO_new(BIO_f_ssl());
396     s_bio = BIO_new(BIO_f_ssl());
397     if ((c_bio == NULL) || (s_bio == NULL))
398         goto err;
399
400     SSL_set_connect_state(c_ssl);
401     SSL_set_bio(c_ssl, s_to_c, c_to_s);
402     BIO_set_ssl(c_bio, c_ssl, (ctx[2] == NULL) ? BIO_CLOSE : BIO_NOCLOSE);
403
404     SSL_set_accept_state(s_ssl);
405     SSL_set_bio(s_ssl, c_to_s, s_to_c);
406     BIO_set_ssl(s_bio, s_ssl, (ctx[3] == NULL) ? BIO_CLOSE : BIO_NOCLOSE);
407
408     c_r = 0;
409     s_r = 1;
410     c_w = 1;
411     s_w = 0;
412     c_want = W_WRITE;
413     s_want = 0;
414     c_write = 1, s_write = 0;
415
416     /* We can always do writes */
417     for (;;) {
418         do_server = 0;
419         do_client = 0;
420
421         i = (int)BIO_pending(s_bio);
422         if ((i && s_r) || s_w)
423             do_server = 1;
424
425         i = (int)BIO_pending(c_bio);
426         if ((i && c_r) || c_w)
427             do_client = 1;
428
429         if (do_server && verbose) {
430             if (SSL_in_init(s_ssl))
431                 BIO_printf(bio_stdout, "server waiting in SSL_accept - %s\n",
432                            SSL_state_string_long(s_ssl));
433             else if (s_write)
434                 BIO_printf(bio_stdout, "server:SSL_write()\n");
435             else
436                 BIO_printf(bio_stdout, "server:SSL_read()\n");
437         }
438
439         if (do_client && verbose) {
440             if (SSL_in_init(c_ssl))
441                 BIO_printf(bio_stdout, "client waiting in SSL_connect - %s\n",
442                            SSL_state_string_long(c_ssl));
443             else if (c_write)
444                 BIO_printf(bio_stdout, "client:SSL_write()\n");
445             else
446                 BIO_printf(bio_stdout, "client:SSL_read()\n");
447         }
448
449         if (!do_client && !do_server) {
450             BIO_printf(bio_stdout, "ERROR IN STARTUP\n");
451             break;
452         }
453         if (do_client && !(done & C_DONE)) {
454             if (c_write) {
455                 i = BIO_write(c_bio, "hello from client\n", 18);
456                 if (i < 0) {
457                     c_r = 0;
458                     c_w = 0;
459                     if (BIO_should_retry(c_bio)) {
460                         if (BIO_should_read(c_bio))
461                             c_r = 1;
462                         if (BIO_should_write(c_bio))
463                             c_w = 1;
464                     } else {
465                         BIO_printf(bio_err, "ERROR in CLIENT\n");
466                         ERR_print_errors_fp(stderr);
467                         return (1);
468                     }
469                 } else if (i == 0) {
470                     BIO_printf(bio_err, "SSL CLIENT STARTUP FAILED\n");
471                     return (1);
472                 } else {
473                     /* ok */
474                     c_write = 0;
475                 }
476             } else {
477                 i = BIO_read(c_bio, cbuf, 100);
478                 if (i < 0) {
479                     c_r = 0;
480                     c_w = 0;
481                     if (BIO_should_retry(c_bio)) {
482                         if (BIO_should_read(c_bio))
483                             c_r = 1;
484                         if (BIO_should_write(c_bio))
485                             c_w = 1;
486                     } else {
487                         BIO_printf(bio_err, "ERROR in CLIENT\n");
488                         ERR_print_errors_fp(stderr);
489                         return (1);
490                     }
491                 } else if (i == 0) {
492                     BIO_printf(bio_err, "SSL CLIENT STARTUP FAILED\n");
493                     return (1);
494                 } else {
495                     done |= C_DONE;
496                 }
497             }
498         }
499
500         if (do_server && !(done & S_DONE)) {
501             if (!s_write) {
502                 i = BIO_read(s_bio, sbuf, 100);
503                 if (i < 0) {
504                     s_r = 0;
505                     s_w = 0;
506                     if (BIO_should_retry(s_bio)) {
507                         if (BIO_should_read(s_bio))
508                             s_r = 1;
509                         if (BIO_should_write(s_bio))
510                             s_w = 1;
511                     } else {
512                         BIO_printf(bio_err, "ERROR in SERVER\n");
513                         ERR_print_errors_fp(stderr);
514                         return (1);
515                     }
516                 } else if (i == 0) {
517                     BIO_printf(bio_err, "SSL SERVER STARTUP FAILED\n");
518                     return (1);
519                 } else {
520                     s_write = 1;
521                     s_w = 1;
522                 }
523             } else {
524                 i = BIO_write(s_bio, "hello from server\n", 18);
525                 if (i < 0) {
526                     s_r = 0;
527                     s_w = 0;
528                     if (BIO_should_retry(s_bio)) {
529                         if (BIO_should_read(s_bio))
530                             s_r = 1;
531                         if (BIO_should_write(s_bio))
532                             s_w = 1;
533                     } else {
534                         BIO_printf(bio_err, "ERROR in SERVER\n");
535                         ERR_print_errors_fp(stderr);
536                         return (1);
537                     }
538                 } else if (i == 0) {
539                     BIO_printf(bio_err, "SSL SERVER STARTUP FAILED\n");
540                     return (1);
541                 } else {
542                     s_write = 0;
543                     s_r = 1;
544                     done |= S_DONE;
545                 }
546             }
547         }
548
549         if ((done & S_DONE) && (done & C_DONE))
550             break;
551     }
552
553     SSL_set_shutdown(c_ssl, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
554     SSL_set_shutdown(s_ssl, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
555
556  err:
557 #if 0
558     /*
559      * We have to set the BIO's to NULL otherwise they will be free()ed
560      * twice.  Once when th s_ssl is SSL_free()ed and again when c_ssl is
561      * SSL_free()ed. This is a hack required because s_ssl and c_ssl are
562      * sharing the same BIO structure and SSL_set_bio() and SSL_free()
563      * automatically BIO_free non NULL entries. You should not normally do
564      * this or be required to do this
565      */
566
567     if (s_ssl != NULL) {
568         s_ssl->rbio = NULL;
569         s_ssl->wbio = NULL;
570     }
571     if (c_ssl != NULL) {
572         c_ssl->rbio = NULL;
573         c_ssl->wbio = NULL;
574     }
575
576     /* The SSL's are optionally freed in the following calls */
577     BIO_free(c_to_s);
578     BIO_free(s_to_c);
579 #endif
580
581     BIO_free(c_bio);
582     BIO_free(s_bio);
583     return (0);
584 }
585
586 int verify_callback(int ok, X509_STORE_CTX *ctx)
587 {
588     char *s, buf[256];
589
590     if (verbose) {
591         s = X509_NAME_oneline(X509_get_subject_name(ctx->current_cert),
592                               buf, 256);
593         if (s != NULL) {
594             if (ok)
595                 BIO_printf(bio_err, "depth=%d %s\n", ctx->error_depth, buf);
596             else
597                 BIO_printf(bio_err, "depth=%d error=%d %s\n",
598                         ctx->error_depth, ctx->error, buf);
599         }
600     }
601     return (ok);
602 }
603
604 #define THREAD_STACK_SIZE (16*1024)
605
606 #ifdef OPENSSL_SYS_WIN32
607
608 static HANDLE *lock_cs;
609
610 void thread_setup(void)
611 {
612     int i;
613
614     lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(HANDLE));
615     for (i = 0; i < CRYPTO_num_locks(); i++) {
616         lock_cs[i] = CreateMutex(NULL, FALSE, NULL);
617     }
618
619     CRYPTO_set_locking_callback((void (*)(int, int, char *, int))
620                                 win32_locking_callback);
621     /* id callback defined */
622 }
623
624 void thread_cleanup(void)
625 {
626     int i;
627
628     CRYPTO_set_locking_callback(NULL);
629     for (i = 0; i < CRYPTO_num_locks(); i++)
630         CloseHandle(lock_cs[i]);
631     OPENSSL_free(lock_cs);
632 }
633
634 void win32_locking_callback(int mode, int type, const char *file, int line)
635 {
636     if (mode & CRYPTO_LOCK) {
637         WaitForSingleObject(lock_cs[type], INFINITE);
638     } else {
639         ReleaseMutex(lock_cs[type]);
640     }
641 }
642
643 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
644 {
645     double ret;
646     SSL_CTX *ssl_ctx[2];
647     DWORD thread_id[MAX_THREAD_NUMBER];
648     HANDLE thread_handle[MAX_THREAD_NUMBER];
649     int i;
650     SYSTEMTIME start, end;
651
652     ssl_ctx[0] = s_ctx;
653     ssl_ctx[1] = c_ctx;
654
655     GetSystemTime(&start);
656     for (i = 0; i < thread_number; i++) {
657         thread_handle[i] = CreateThread(NULL,
658                                         THREAD_STACK_SIZE,
659                                         (LPTHREAD_START_ROUTINE) ndoit,
660                                         (void *)ssl_ctx, 0L, &(thread_id[i]));
661     }
662
663     BIO_printf(bio_stdout, "reaping\n");
664     for (i = 0; i < thread_number; i += 50) {
665         int j;
666
667         j = (thread_number < (i + 50)) ? (thread_number - i) : 50;
668
669         if (WaitForMultipleObjects(j,
670                                    (CONST HANDLE *) & (thread_handle[i]),
671                                    TRUE, INFINITE)
672             == WAIT_FAILED) {
673             BIO_printf(bio_err, "WaitForMultipleObjects failed:%d\n",
674                     GetLastError());
675             exit(1);
676         }
677     }
678     GetSystemTime(&end);
679
680     if (start.wDayOfWeek > end.wDayOfWeek)
681         end.wDayOfWeek += 7;
682     ret = (end.wDayOfWeek - start.wDayOfWeek) * 24;
683
684     ret = (ret + end.wHour - start.wHour) * 60;
685     ret = (ret + end.wMinute - start.wMinute) * 60;
686     ret = (ret + end.wSecond - start.wSecond);
687     ret += (end.wMilliseconds - start.wMilliseconds) / 1000.0;
688
689     BIO_printf(bio_stdout, "win32 threads done - %.3f seconds\n", ret);
690 }
691
692 #endif                          /* OPENSSL_SYS_WIN32 */
693
694
695 #ifdef PTHREADS
696
697 static pthread_mutex_t *lock_cs;
698 static long *lock_count;
699
700 void thread_setup(void)
701 {
702     int i;
703
704     lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
705     lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
706     for (i = 0; i < CRYPTO_num_locks(); i++) {
707         lock_count[i] = 0;
708         pthread_mutex_init(&(lock_cs[i]), NULL);
709     }
710
711     CRYPTO_THREADID_set_callback(pthreads_thread_id);
712     CRYPTO_set_locking_callback(pthreads_locking_callback);
713 }
714
715 void thread_cleanup(void)
716 {
717     int i;
718
719     CRYPTO_set_locking_callback(NULL);
720     BIO_printf(bio_err, "cleanup\n");
721     for (i = 0; i < CRYPTO_num_locks(); i++) {
722         pthread_mutex_destroy(&(lock_cs[i]));
723         BIO_printf(bio_err, "%8ld:%s\n", lock_count[i], CRYPTO_get_lock_name(i));
724     }
725     OPENSSL_free(lock_cs);
726     OPENSSL_free(lock_count);
727
728     BIO_printf(bio_err, "done cleanup\n");
729 }
730
731 void pthreads_locking_callback(int mode, int type, const char *file, int line)
732 {
733     if (mode & CRYPTO_LOCK) {
734         pthread_mutex_lock(&(lock_cs[type]));
735         lock_count[type]++;
736     } else {
737         pthread_mutex_unlock(&(lock_cs[type]));
738     }
739 }
740
741 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
742 {
743     SSL_CTX *ssl_ctx[2];
744     pthread_t thread_ctx[MAX_THREAD_NUMBER];
745     int i;
746
747     ssl_ctx[0] = s_ctx;
748     ssl_ctx[1] = c_ctx;
749
750     for (i = 0; i < thread_number; i++) {
751         pthread_create(&(thread_ctx[i]), NULL,
752                        (void *(*)())ndoit, (void *)ssl_ctx);
753     }
754
755     BIO_printf(bio_stdout, "reaping\n");
756     for (i = 0; i < thread_number; i++) {
757         pthread_join(thread_ctx[i], NULL);
758     }
759
760 #if 0 /* We can't currently find out the reference amount */
761     BIO_printf(bio_stdout, "pthreads threads done (%d,%d)\n",
762                s_ctx->references, c_ctx->references);
763 #else
764     BIO_printf(bio_stdout, "pthreads threads done\n");
765 #endif
766 }
767
768 void pthreads_thread_id(CRYPTO_THREADID *tid)
769 {
770     CRYPTO_THREADID_set_numeric(tid, (unsigned long)pthread_self());
771 }
772
773 #endif                          /* PTHREADS */