ifdef cleanup, part 4a: '#ifdef undef'
[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 MS_CALLBACK 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, char *file, int line);
115 void solaris_locking_callback(int mode, int type, char *file, int line);
116 void win32_locking_callback(int mode, int type, char *file, int line);
117 void pthreads_locking_callback(int mode, int type, char *file, int line);
118 void netware_locking_callback(int mode, int type, char *file, int line);
119 void beos_locking_callback(int mode, int type, const char *file, int line);
120
121 unsigned long irix_thread_id(void);
122 unsigned long solaris_thread_id(void);
123 unsigned long pthreads_thread_id(void);
124 unsigned long netware_thread_id(void);
125 unsigned long beos_thread_id(void);
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 = SSLv23_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
356     ctx[0] = (char *)ssl_ctx[0];
357     ctx[1] = (char *)ssl_ctx[1];
358
359     if (reconnect) {
360         ctx[2] = (char *)SSL_new(ssl_ctx[0]);
361         ctx[3] = (char *)SSL_new(ssl_ctx[1]);
362     } else {
363         ctx[2] = NULL;
364         ctx[3] = NULL;
365     }
366
367     fprintf(stdout, "started thread %lu\n", CRYPTO_thread_id());
368     for (i = 0; i < number_of_loops; i++) {
369 /*-             fprintf(stderr,"%4d %2d ctx->ref (%3d,%3d)\n",
370                         CRYPTO_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             fprintf(stdout, "error[%d] %lu - %d\n",
378                     i, CRYPTO_thread_id(), ret);
379             return (ret);
380         }
381     }
382     fprintf(stdout, "DONE %lu\n", CRYPTO_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                 printf("server waiting in SSL_accept - %s\n",
468                        SSL_state_string_long(s_ssl));
469             else if (s_write)
470                 printf("server:SSL_write()\n");
471             else
472                 printf("server:SSL_read()\n");
473         }
474
475         if (do_client && verbose) {
476             if (SSL_in_init(c_ssl))
477                 printf("client waiting in SSL_connect - %s\n",
478                        SSL_state_string_long(c_ssl));
479             else if (c_write)
480                 printf("client:SSL_write()\n");
481             else
482                 printf("client:SSL_read()\n");
483         }
484
485         if (!do_client && !do_server) {
486             fprintf(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                         fprintf(stderr, "ERROR in CLIENT\n");
502                         ERR_print_errors_fp(stderr);
503                         return (1);
504                     }
505                 } else if (i == 0) {
506                     fprintf(stderr, "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                         fprintf(stderr, "ERROR in CLIENT\n");
524                         ERR_print_errors_fp(stderr);
525                         return (1);
526                     }
527                 } else if (i == 0) {
528                     fprintf(stderr, "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                         fprintf(stderr, "ERROR in SERVER\n");
549                         ERR_print_errors_fp(stderr);
550                         return (1);
551                     }
552                 } else if (i == 0) {
553                     fprintf(stderr, "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                         fprintf(stderr, "ERROR in SERVER\n");
571                         ERR_print_errors_fp(stderr);
572                         return (1);
573                     }
574                 } else if (i == 0) {
575                     fprintf(stderr, "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     /*
597      * We have to set the BIO's to NULL otherwise they will be free()ed
598      * twice.  Once when th s_ssl is SSL_free()ed and again when c_ssl is
599      * SSL_free()ed. This is a hack required because s_ssl and c_ssl are
600      * sharing the same BIO structure and SSL_set_bio() and SSL_free()
601      * automatically BIO_free non NULL entries. You should not normally do
602      * this or be required to do this
603      */
604
605     if (s_ssl != NULL) {
606         s_ssl->rbio = NULL;
607         s_ssl->wbio = NULL;
608     }
609     if (c_ssl != NULL) {
610         c_ssl->rbio = NULL;
611         c_ssl->wbio = NULL;
612     }
613
614     /* The SSL's are optionally freed in the following calls */
615     if (c_to_s != NULL)
616         BIO_free(c_to_s);
617     if (s_to_c != NULL)
618         BIO_free(s_to_c);
619
620     if (c_bio != NULL)
621         BIO_free(c_bio);
622     if (s_bio != NULL)
623         BIO_free(s_bio);
624     return (0);
625 }
626
627 int MS_CALLBACK verify_callback(int ok, X509_STORE_CTX *ctx)
628 {
629     char *s, buf[256];
630
631     if (verbose) {
632         s = X509_NAME_oneline(X509_get_subject_name(ctx->current_cert),
633                               buf, 256);
634         if (s != NULL) {
635             if (ok)
636                 fprintf(stderr, "depth=%d %s\n", ctx->error_depth, buf);
637             else
638                 fprintf(stderr, "depth=%d error=%d %s\n",
639                         ctx->error_depth, ctx->error, buf);
640         }
641     }
642     return (ok);
643 }
644
645 #define THREAD_STACK_SIZE (16*1024)
646
647 #ifdef OPENSSL_SYS_WIN32
648
649 static HANDLE *lock_cs;
650
651 void thread_setup(void)
652 {
653     int i;
654
655     lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(HANDLE));
656     for (i = 0; i < CRYPTO_num_locks(); i++) {
657         lock_cs[i] = CreateMutex(NULL, FALSE, NULL);
658     }
659
660     CRYPTO_set_locking_callback((void (*)(int, int, char *, int))
661                                 win32_locking_callback);
662     /* id callback defined */
663 }
664
665 void thread_cleanup(void)
666 {
667     int i;
668
669     CRYPTO_set_locking_callback(NULL);
670     for (i = 0; i < CRYPTO_num_locks(); i++)
671         CloseHandle(lock_cs[i]);
672     OPENSSL_free(lock_cs);
673 }
674
675 void win32_locking_callback(int mode, int type, char *file, int line)
676 {
677     if (mode & CRYPTO_LOCK) {
678         WaitForSingleObject(lock_cs[type], INFINITE);
679     } else {
680         ReleaseMutex(lock_cs[type]);
681     }
682 }
683
684 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
685 {
686     double ret;
687     SSL_CTX *ssl_ctx[2];
688     DWORD thread_id[MAX_THREAD_NUMBER];
689     HANDLE thread_handle[MAX_THREAD_NUMBER];
690     int i;
691     SYSTEMTIME start, end;
692
693     ssl_ctx[0] = s_ctx;
694     ssl_ctx[1] = c_ctx;
695
696     GetSystemTime(&start);
697     for (i = 0; i < thread_number; i++) {
698         thread_handle[i] = CreateThread(NULL,
699                                         THREAD_STACK_SIZE,
700                                         (LPTHREAD_START_ROUTINE) ndoit,
701                                         (void *)ssl_ctx, 0L, &(thread_id[i]));
702     }
703
704     printf("reaping\n");
705     for (i = 0; i < thread_number; i += 50) {
706         int j;
707
708         j = (thread_number < (i + 50)) ? (thread_number - i) : 50;
709
710         if (WaitForMultipleObjects(j,
711                                    (CONST HANDLE *) & (thread_handle[i]),
712                                    TRUE, INFINITE)
713             == WAIT_FAILED) {
714             fprintf(stderr, "WaitForMultipleObjects failed:%d\n",
715                     GetLastError());
716             exit(1);
717         }
718     }
719     GetSystemTime(&end);
720
721     if (start.wDayOfWeek > end.wDayOfWeek)
722         end.wDayOfWeek += 7;
723     ret = (end.wDayOfWeek - start.wDayOfWeek) * 24;
724
725     ret = (ret + end.wHour - start.wHour) * 60;
726     ret = (ret + end.wMinute - start.wMinute) * 60;
727     ret = (ret + end.wSecond - start.wSecond);
728     ret += (end.wMilliseconds - start.wMilliseconds) / 1000.0;
729
730     printf("win32 threads done - %.3f seconds\n", ret);
731 }
732
733 #endif                          /* OPENSSL_SYS_WIN32 */
734
735 #ifdef SOLARIS
736
737 static mutex_t *lock_cs;
738 /*
739  * static rwlock_t *lock_cs;
740  */
741 static long *lock_count;
742
743 void thread_setup(void)
744 {
745     int i;
746
747     lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(mutex_t));
748     lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
749     for (i = 0; i < CRYPTO_num_locks(); i++) {
750         lock_count[i] = 0;
751         /* rwlock_init(&(lock_cs[i]),USYNC_THREAD,NULL); */
752         mutex_init(&(lock_cs[i]), USYNC_THREAD, NULL);
753     }
754
755     CRYPTO_set_id_callback((unsigned long (*)())solaris_thread_id);
756     CRYPTO_set_locking_callback((void (*)())solaris_locking_callback);
757 }
758
759 void thread_cleanup(void)
760 {
761     int i;
762
763     CRYPTO_set_locking_callback(NULL);
764
765     fprintf(stderr, "cleanup\n");
766
767     for (i = 0; i < CRYPTO_num_locks(); i++) {
768         /* rwlock_destroy(&(lock_cs[i])); */
769         mutex_destroy(&(lock_cs[i]));
770         fprintf(stderr, "%8ld:%s\n", lock_count[i], CRYPTO_get_lock_name(i));
771     }
772     OPENSSL_free(lock_cs);
773     OPENSSL_free(lock_count);
774
775     fprintf(stderr, "done cleanup\n");
776
777 }
778
779 void solaris_locking_callback(int mode, int type, char *file, int line)
780 {
781     if (mode & CRYPTO_LOCK) {
782         mutex_lock(&(lock_cs[type]));
783         lock_count[type]++;
784     } else {
785         mutex_unlock(&(lock_cs[type]));
786     }
787 }
788
789 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
790 {
791     SSL_CTX *ssl_ctx[2];
792     thread_t thread_ctx[MAX_THREAD_NUMBER];
793     int i;
794
795     ssl_ctx[0] = s_ctx;
796     ssl_ctx[1] = c_ctx;
797
798     thr_setconcurrency(thread_number);
799     for (i = 0; i < thread_number; i++) {
800         thr_create(NULL, THREAD_STACK_SIZE,
801                    (void *(*)())ndoit, (void *)ssl_ctx, 0L, &(thread_ctx[i]));
802     }
803
804     printf("reaping\n");
805     for (i = 0; i < thread_number; i++) {
806         thr_join(thread_ctx[i], NULL, NULL);
807     }
808
809     printf("solaris threads done (%d,%d)\n",
810            s_ctx->references, c_ctx->references);
811 }
812
813 unsigned long solaris_thread_id(void)
814 {
815     unsigned long ret;
816
817     ret = (unsigned long)thr_self();
818     return (ret);
819 }
820 #endif                          /* SOLARIS */
821
822 #ifdef IRIX
823
824 static usptr_t *arena;
825 static usema_t **lock_cs;
826
827 void thread_setup(void)
828 {
829     int i;
830     char filename[20];
831
832     strcpy(filename, "/tmp/mttest.XXXXXX");
833     mktemp(filename);
834
835     usconfig(CONF_STHREADIOOFF);
836     usconfig(CONF_STHREADMALLOCOFF);
837     usconfig(CONF_INITUSERS, 100);
838     usconfig(CONF_LOCKTYPE, US_DEBUGPLUS);
839     arena = usinit(filename);
840     unlink(filename);
841
842     lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(usema_t *));
843     for (i = 0; i < CRYPTO_num_locks(); i++) {
844         lock_cs[i] = usnewsema(arena, 1);
845     }
846
847     CRYPTO_set_id_callback((unsigned long (*)())irix_thread_id);
848     CRYPTO_set_locking_callback((void (*)())irix_locking_callback);
849 }
850
851 void thread_cleanup(void)
852 {
853     int i;
854
855     CRYPTO_set_locking_callback(NULL);
856     for (i = 0; i < CRYPTO_num_locks(); i++) {
857         char buf[10];
858
859         sprintf(buf, "%2d:", i);
860         usdumpsema(lock_cs[i], stdout, buf);
861         usfreesema(lock_cs[i], arena);
862     }
863     OPENSSL_free(lock_cs);
864 }
865
866 void irix_locking_callback(int mode, int type, char *file, int line)
867 {
868     if (mode & CRYPTO_LOCK) {
869         printf("lock %d\n", type);
870         uspsema(lock_cs[type]);
871     } else {
872         printf("unlock %d\n", type);
873         usvsema(lock_cs[type]);
874     }
875 }
876
877 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
878 {
879     SSL_CTX *ssl_ctx[2];
880     int thread_ctx[MAX_THREAD_NUMBER];
881     int i;
882
883     ssl_ctx[0] = s_ctx;
884     ssl_ctx[1] = c_ctx;
885
886     for (i = 0; i < thread_number; i++) {
887         thread_ctx[i] = sproc((void (*)())ndoit,
888                               PR_SADDR | PR_SFDS, (void *)ssl_ctx);
889     }
890
891     printf("reaping\n");
892     for (i = 0; i < thread_number; i++) {
893         wait(NULL);
894     }
895
896     printf("irix threads done (%d,%d)\n",
897            s_ctx->references, c_ctx->references);
898 }
899
900 unsigned long irix_thread_id(void)
901 {
902     unsigned long ret;
903
904     ret = (unsigned long)getpid();
905     return (ret);
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_set_id_callback((unsigned long (*)())pthreads_thread_id);
926     CRYPTO_set_locking_callback((void (*)())pthreads_locking_callback);
927 }
928
929 void thread_cleanup(void)
930 {
931     int i;
932
933     CRYPTO_set_locking_callback(NULL);
934     fprintf(stderr, "cleanup\n");
935     for (i = 0; i < CRYPTO_num_locks(); i++) {
936         pthread_mutex_destroy(&(lock_cs[i]));
937         fprintf(stderr, "%8ld:%s\n", lock_count[i], CRYPTO_get_lock_name(i));
938     }
939     OPENSSL_free(lock_cs);
940     OPENSSL_free(lock_count);
941
942     fprintf(stderr, "done cleanup\n");
943 }
944
945 void pthreads_locking_callback(int mode, int type, 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     printf("reaping\n");
973     for (i = 0; i < thread_number; i++) {
974         pthread_join(thread_ctx[i], NULL);
975     }
976
977     printf("pthreads threads done (%d,%d)\n",
978            s_ctx->references, c_ctx->references);
979 }
980
981 unsigned long pthreads_thread_id(void)
982 {
983     unsigned long ret;
984
985     ret = (unsigned long)pthread_self();
986     return (ret);
987 }
988
989 #endif                          /* PTHREADS */
990
991 #ifdef OPENSSL_SYS_NETWARE
992
993 void thread_setup(void)
994 {
995     int i;
996
997     lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(MPKMutex));
998     lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
999     for (i = 0; i < CRYPTO_num_locks(); i++) {
1000         lock_count[i] = 0;
1001         lock_cs[i] = MPKMutexAlloc("OpenSSL mutex");
1002     }
1003
1004     ThreadSem = MPKSemaphoreAlloc("OpenSSL mttest semaphore", 0);
1005
1006     CRYPTO_set_id_callback((unsigned long (*)())netware_thread_id);
1007     CRYPTO_set_locking_callback((void (*)())netware_locking_callback);
1008 }
1009
1010 void thread_cleanup(void)
1011 {
1012     int i;
1013
1014     CRYPTO_set_locking_callback(NULL);
1015
1016     fprintf(stdout, "thread_cleanup\n");
1017
1018     for (i = 0; i < CRYPTO_num_locks(); i++) {
1019         MPKMutexFree(lock_cs[i]);
1020         fprintf(stdout, "%8ld:%s\n", lock_count[i], CRYPTO_get_lock_name(i));
1021     }
1022     OPENSSL_free(lock_cs);
1023     OPENSSL_free(lock_count);
1024
1025     MPKSemaphoreFree(ThreadSem);
1026
1027     fprintf(stdout, "done cleanup\n");
1028 }
1029
1030 void netware_locking_callback(int mode, int type, char *file, int line)
1031 {
1032     if (mode & CRYPTO_LOCK) {
1033         MPKMutexLock(lock_cs[type]);
1034         lock_count[type]++;
1035     } else
1036         MPKMutexUnlock(lock_cs[type]);
1037 }
1038
1039 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
1040 {
1041     SSL_CTX *ssl_ctx[2];
1042     int i;
1043     ssl_ctx[0] = s_ctx;
1044     ssl_ctx[1] = c_ctx;
1045
1046     for (i = 0; i < thread_number; i++) {
1047         BeginThread((void (*)(void *))ndoit, NULL, THREAD_STACK_SIZE,
1048                     (void *)ssl_ctx);
1049         ThreadSwitchWithDelay();
1050     }
1051
1052     printf("reaping\n");
1053
1054     /* loop until all threads have signaled the semaphore */
1055     for (i = 0; i < thread_number; i++) {
1056         MPKSemaphoreWait(ThreadSem);
1057     }
1058     printf("netware threads done (%d,%d)\n",
1059            s_ctx->references, c_ctx->references);
1060 }
1061
1062 unsigned long netware_thread_id(void)
1063 {
1064     unsigned long ret;
1065
1066     ret = (unsigned long)GetThreadID();
1067     return (ret);
1068 }
1069 #endif                          /* NETWARE */