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