1 /* crypto/threads/mttest.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 
59 #include <stdlib.h>
60 #include <string.h>
61 #include <errno.h>
62 #ifdef LINUX
63 # include <typedefs.h>
64 #endif
65 #ifdef OPENSSL_SYS_WIN32
66 # include <windows.h>
67 #endif
68 #ifdef SOLARIS
69 # include <synch.h>
70 # include <thread.h>
71 #endif
72 #ifdef IRIX
73 # include <ulocks.h>
74 # include <sys/prctl.h>
75 #endif
76 #ifdef PTHREADS
77 # include <pthread.h>
78 #endif
79 #ifdef OPENSSL_SYS_NETWARE
80 # if !defined __int64
81 #  define __int64 long long
82 # endif
83 # include <nwmpk.h>
84 #endif
85 #include <openssl/lhash.h>
86 #include <openssl/crypto.h>
87 #include <openssl/buffer.h>
88 #include "e_os.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]);
print_stats(BIO * bio,SSL_CTX * ctx)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, "%4ld client connects (SSL_connect())\n",
151 	       SSL_CTX_sess_connect(ctx));
152     BIO_printf(bio, "%4ld client connects that finished\n",
153 	       SSL_CTX_sess_connect_good(ctx));
154     BIO_printf(bio, "%4ld server connects (SSL_accept())\n",
155 	       SSL_CTX_sess_accept(ctx));
156     BIO_printf(bio, "%4ld server connects that finished\n",
157 	       SSL_CTX_sess_accept_good(ctx));
158     BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ctx));
159     BIO_printf(bio, "%4ld session cache misses\n", SSL_CTX_sess_misses(ctx));
160     BIO_printf(bio, "%4ld session cache timeouts\n", SSL_CTX_sess_timeouts(ctx));
161 }
162 
sv_usage(void)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 
main(int argc,char * argv[])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     const char *scert = TEST_SERVER_CERT;
191     const char *ccert = TEST_CLIENT_CERT;
192     const SSL_METHOD *ssl_method = SSLv23_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, "-ssl2") == 0)
215             ssl_method = SSLv2_method();
216         else if (strcmp(*argv, "-CApath") == 0) {
217             if (--argc < 1)
218                 goto bad;
219             CApath = *(++argv);
220         } else if (strcmp(*argv, "-CAfile") == 0) {
221             if (--argc < 1)
222                 goto bad;
223             CAfile = *(++argv);
224         } else if (strcmp(*argv, "-cert") == 0) {
225             if (--argc < 1)
226                 goto bad;
227             scert = *(++argv);
228         } else if (strcmp(*argv, "-ccert") == 0) {
229             if (--argc < 1)
230                 goto bad;
231             ccert = *(++argv);
232         } else if (strcmp(*argv, "-threads") == 0) {
233             if (--argc < 1)
234                 goto bad;
235             thread_number = atoi(*(++argv));
236             if (thread_number == 0)
237                 thread_number = 1;
238             if (thread_number > MAX_THREAD_NUMBER)
239                 thread_number = MAX_THREAD_NUMBER;
240         } else if (strcmp(*argv, "-loops") == 0) {
241             if (--argc < 1)
242                 goto bad;
243             number_of_loops = atoi(*(++argv));
244             if (number_of_loops == 0)
245                 number_of_loops = 1;
246         } else {
247             BIO_printf(bio_err, "unknown option %s\n", *argv);
248             badop = 1;
249             break;
250         }
251         argc--;
252         argv++;
253     }
254     if (badop) {
255  bad:
256         sv_usage();
257         goto end;
258     }
259 
260     if (cipher == NULL && OPENSSL_issetugid() == 0)
261         cipher = getenv("SSL_CIPHER");
262 
263     SSL_load_error_strings();
264     OpenSSL_add_ssl_algorithms();
265 
266     c_ctx = SSL_CTX_new(ssl_method);
267     s_ctx = SSL_CTX_new(ssl_method);
268     if ((c_ctx == NULL) || (s_ctx == NULL)) {
269         ERR_print_errors(bio_err);
270         goto end;
271     }
272 
273     SSL_CTX_set_session_cache_mode(s_ctx,
274                                    SSL_SESS_CACHE_NO_AUTO_CLEAR |
275                                    SSL_SESS_CACHE_SERVER);
276     SSL_CTX_set_session_cache_mode(c_ctx,
277                                    SSL_SESS_CACHE_NO_AUTO_CLEAR |
278                                    SSL_SESS_CACHE_SERVER);
279 
280     if (!SSL_CTX_use_certificate_file(s_ctx, scert, SSL_FILETYPE_PEM)) {
281         BIO_printf(bio_err, "SSL_CTX_use_certificate_file (%s)\n", scert);
282         ERR_print_errors(bio_err);
283         goto end;
284     } else
285         if (!SSL_CTX_use_RSAPrivateKey_file(s_ctx, scert, SSL_FILETYPE_PEM)) {
286         BIO_printf(bio_err, "SSL_CTX_use_RSAPrivateKey_file (%s)\n", scert);
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         BIO_printf(bio_err, "SSL_load_verify_locations\n");
301         ERR_print_errors(bio_err);
302         goto end;
303     }
304 
305     if (client_auth) {
306         BIO_printf(bio_err, "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         BIO_printf(bio_err, "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         BIO_printf(bio_err, "Client SSL_CTX stats then free it\n");
323         print_stats(bio_err, c_ctx);
324         SSL_CTX_free(c_ctx);
325     }
326     if (s_ctx != NULL) {
327         BIO_printf(bio_err, "Server SSL_CTX stats then free it\n");
328         print_stats(bio_err, s_ctx);
329         if (cache_stats) {
330             BIO_printf(bio_err, "-----\n");
331             lh_SSL_SESSION_stats_bio(SSL_CTX_sessions(s_ctx), bio_err);
332             BIO_printf(bio_err, "-----\n");
333     /*-     lh_SSL_SESSION_node_stats_bio(SSL_CTX_sessions(s_ctx),bio_err);
334             BIO_printf(bio_err,"-----\n"); */
335             lh_SSL_SESSION_node_usage_stats_bio(SSL_CTX_sessions(s_ctx), bio_err);
336             BIO_printf(bio_err, "-----\n");
337         }
338         SSL_CTX_free(s_ctx);
339         BIO_printf(bio_err, "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 
ndoit(SSL_CTX * ssl_ctx[2])350 static int ndoit(SSL_CTX *ssl_ctx[2])
351 {
352     int i;
353     int ret;
354     char *ctx[4];
355     CRYPTO_THREADID thread_id;
356 
357     ctx[0] = (char *)ssl_ctx[0];
358     ctx[1] = (char *)ssl_ctx[1];
359 
360     if (reconnect) {
361         ctx[2] = (char *)SSL_new(ssl_ctx[0]);
362         ctx[3] = (char *)SSL_new(ssl_ctx[1]);
363     } else {
364         ctx[2] = NULL;
365         ctx[3] = NULL;
366     }
367 
368     CRYPTO_THREADID_current(&thread_id);
369     BIO_printf(bio_stdout, "started thread %lu\n",
370 	       CRYPTO_THREADID_hash(&thread_id));
371     for (i = 0; i < number_of_loops; i++) {
372 /*-     BIO_printf(bio_err,"%4d %2d ctx->ref (%3d,%3d)\n",
373                    CRYPTO_THREADID_hash(&thread_id),i,
374                    ssl_ctx[0]->references,
375                    ssl_ctx[1]->references); */
376 /*      pthread_delay_np(&tm); */
377 
378         ret = doit(ctx);
379         if (ret != 0) {
380             BIO_printf(bio_stdout, "error[%d] %lu - %d\n",
381                        i, CRYPTO_THREADID_hash(&thread_id), ret);
382             return (ret);
383         }
384     }
385     BIO_printf(bio_stdout, "DONE %lu\n", CRYPTO_THREADID_hash(&thread_id));
386     if (reconnect) {
387         SSL_free((SSL *)ctx[2]);
388         SSL_free((SSL *)ctx[3]);
389     }
390 #ifdef OPENSSL_SYS_NETWARE
391     MPKSemaphoreSignal(ThreadSem);
392 #endif
393     return (0);
394 }
395 
doit(char * ctx[4])396 int doit(char *ctx[4])
397 {
398     SSL_CTX *s_ctx, *c_ctx;
399     static char cbuf[200], sbuf[200];
400     SSL *c_ssl = NULL;
401     SSL *s_ssl = NULL;
402     BIO *c_to_s = NULL;
403     BIO *s_to_c = NULL;
404     BIO *c_bio = NULL;
405     BIO *s_bio = NULL;
406     int c_r, c_w, s_r, s_w;
407     int i;
408     int done = 0;
409     int c_write, s_write;
410     int do_server = 0, do_client = 0;
411 
412     s_ctx = (SSL_CTX *)ctx[0];
413     c_ctx = (SSL_CTX *)ctx[1];
414 
415     if (ctx[2] != NULL)
416         s_ssl = (SSL *)ctx[2];
417     else
418         s_ssl = SSL_new(s_ctx);
419 
420     if (ctx[3] != NULL)
421         c_ssl = (SSL *)ctx[3];
422     else
423         c_ssl = SSL_new(c_ctx);
424 
425     if ((s_ssl == NULL) || (c_ssl == NULL))
426         goto err;
427 
428     c_to_s = BIO_new(BIO_s_mem());
429     s_to_c = BIO_new(BIO_s_mem());
430     if ((s_to_c == NULL) || (c_to_s == NULL))
431         goto err;
432 
433     c_bio = BIO_new(BIO_f_ssl());
434     s_bio = BIO_new(BIO_f_ssl());
435     if ((c_bio == NULL) || (s_bio == NULL))
436         goto err;
437 
438     SSL_set_connect_state(c_ssl);
439     SSL_set_bio(c_ssl, s_to_c, c_to_s);
440     BIO_set_ssl(c_bio, c_ssl, (ctx[2] == NULL) ? BIO_CLOSE : BIO_NOCLOSE);
441 
442     SSL_set_accept_state(s_ssl);
443     SSL_set_bio(s_ssl, c_to_s, s_to_c);
444     BIO_set_ssl(s_bio, s_ssl, (ctx[3] == NULL) ? BIO_CLOSE : BIO_NOCLOSE);
445 
446     c_r = 0;
447     s_r = 1;
448     c_w = 1;
449     s_w = 0;
450     c_write = 1, s_write = 0;
451 
452     /* We can always do writes */
453     for (;;) {
454         do_server = 0;
455         do_client = 0;
456 
457         i = (int)BIO_pending(s_bio);
458         if ((i && s_r) || s_w)
459             do_server = 1;
460 
461         i = (int)BIO_pending(c_bio);
462         if ((i && c_r) || c_w)
463             do_client = 1;
464 
465         if (do_server && verbose) {
466             if (SSL_in_init(s_ssl))
467                 BIO_printf(bio_stdout, "server waiting in SSL_accept - %s\n",
468                            SSL_state_string_long(s_ssl));
469             else if (s_write)
470                 BIO_printf(bio_stdout, "server:SSL_write()\n");
471             else
472                 BIO_printf(bio_stdout, "server:SSL_read()\n");
473         }
474 
475         if (do_client && verbose) {
476             if (SSL_in_init(c_ssl))
477                 BIO_printf(bio_stdout, "client waiting in SSL_connect - %s\n",
478                            SSL_state_string_long(c_ssl));
479             else if (c_write)
480                 BIO_printf(bio_stdout, "client:SSL_write()\n");
481             else
482                 BIO_printf(bio_stdout, "client:SSL_read()\n");
483         }
484 
485         if (!do_client && !do_server) {
486             BIO_printf(bio_stdout, "ERROR IN STARTUP\n");
487             break;
488         }
489         if (do_client && !(done & C_DONE)) {
490             if (c_write) {
491                 i = BIO_write(c_bio, "hello from client\n", 18);
492                 if (i < 0) {
493                     c_r = 0;
494                     c_w = 0;
495                     if (BIO_should_retry(c_bio)) {
496                         if (BIO_should_read(c_bio))
497                             c_r = 1;
498                         if (BIO_should_write(c_bio))
499                             c_w = 1;
500                     } else {
501                         BIO_printf(bio_err, "ERROR in CLIENT\n");
502                         ERR_print_errors_fp(stderr);
503                         return (1);
504                     }
505                 } else if (i == 0) {
506                     BIO_printf(bio_err, "SSL CLIENT STARTUP FAILED\n");
507                     return (1);
508                 } else {
509                     /* ok */
510                     c_write = 0;
511                 }
512             } else {
513                 i = BIO_read(c_bio, cbuf, 100);
514                 if (i < 0) {
515                     c_r = 0;
516                     c_w = 0;
517                     if (BIO_should_retry(c_bio)) {
518                         if (BIO_should_read(c_bio))
519                             c_r = 1;
520                         if (BIO_should_write(c_bio))
521                             c_w = 1;
522                     } else {
523                         BIO_printf(bio_err, "ERROR in CLIENT\n");
524                         ERR_print_errors_fp(stderr);
525                         return (1);
526                     }
527                 } else if (i == 0) {
528                     BIO_printf(bio_err, "SSL CLIENT STARTUP FAILED\n");
529                     return (1);
530                 } else {
531                     done |= C_DONE;
532 #ifdef undef
533                     BIO_printf(bio_stdout, "CLIENT:from server:");
534                     BIO_write(bio_stdout, cbuf, i);
535                     BIO_flush(bio_stdout);
536 #endif
537                 }
538             }
539         }
540 
541         if (do_server && !(done & S_DONE)) {
542             if (!s_write) {
543                 i = BIO_read(s_bio, sbuf, 100);
544                 if (i < 0) {
545                     s_r = 0;
546                     s_w = 0;
547                     if (BIO_should_retry(s_bio)) {
548                         if (BIO_should_read(s_bio))
549                             s_r = 1;
550                         if (BIO_should_write(s_bio))
551                             s_w = 1;
552                     } else {
553                         BIO_printf(bio_err, "ERROR in SERVER\n");
554                         ERR_print_errors_fp(stderr);
555                         return (1);
556                     }
557                 } else if (i == 0) {
558                     BIO_printf(bio_err, "SSL SERVER STARTUP FAILED\n");
559                     return (1);
560                 } else {
561                     s_write = 1;
562                     s_w = 1;
563 #ifdef undef
564                     BIO_printf(bio_stdout, "SERVER:from client:");
565                     BIO_write(bio_stdout, sbuf, i);
566                     BIO_flush(bio_stdout);
567 #endif
568                 }
569             } else {
570                 i = BIO_write(s_bio, "hello from server\n", 18);
571                 if (i < 0) {
572                     s_r = 0;
573                     s_w = 0;
574                     if (BIO_should_retry(s_bio)) {
575                         if (BIO_should_read(s_bio))
576                             s_r = 1;
577                         if (BIO_should_write(s_bio))
578                             s_w = 1;
579                     } else {
580                         BIO_printf(bio_err, "ERROR in SERVER\n");
581                         ERR_print_errors_fp(stderr);
582                         return (1);
583                     }
584                 } else if (i == 0) {
585                     BIO_printf(bio_err, "SSL SERVER STARTUP FAILED\n");
586                     return (1);
587                 } else {
588                     s_write = 0;
589                     s_r = 1;
590                     done |= S_DONE;
591                 }
592             }
593         }
594 
595         if ((done & S_DONE) && (done & C_DONE))
596             break;
597 #if defined(OPENSSL_SYS_NETWARE)
598         ThreadSwitchWithDelay();
599 #endif
600     }
601 
602     SSL_set_shutdown(c_ssl, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
603     SSL_set_shutdown(s_ssl, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
604 
605 #ifdef undef
606     BIO_printf(bio_stdout, "DONE\n");
607 #endif
608  err:
609     /*
610      * We have to set the BIO's to NULL otherwise they will be free()ed
611      * twice.  Once when th s_ssl is SSL_free()ed and again when c_ssl is
612      * SSL_free()ed. This is a hack required because s_ssl and c_ssl are
613      * sharing the same BIO structure and SSL_set_bio() and SSL_free()
614      * automatically BIO_free non NULL entries. You should not normally do
615      * this or be required to do this
616      */
617 
618     if (s_ssl != NULL) {
619         s_ssl->rbio = NULL;
620         s_ssl->wbio = NULL;
621     }
622     if (c_ssl != NULL) {
623         c_ssl->rbio = NULL;
624         c_ssl->wbio = NULL;
625     }
626 
627     /* The SSL's are optionally freed in the following calls */
628     if (c_to_s != NULL)
629         BIO_free(c_to_s);
630     if (s_to_c != NULL)
631         BIO_free(s_to_c);
632 
633     if (c_bio != NULL)
634         BIO_free(c_bio);
635     if (s_bio != NULL)
636         BIO_free(s_bio);
637     return (0);
638 }
639 
verify_callback(int ok,X509_STORE_CTX * ctx)640 int verify_callback(int ok, X509_STORE_CTX *ctx)
641 {
642     char *s, buf[256];
643 
644     if (verbose) {
645         s = X509_NAME_oneline(X509_get_subject_name(ctx->current_cert),
646                               buf, 256);
647         if (s != NULL) {
648             if (ok)
649                 BIO_printf(bio_err, "depth=%d %s\n", ctx->error_depth, buf);
650             else
651                 BIO_printf(bio_err, "depth=%d error=%d %s\n",
652                         ctx->error_depth, ctx->error, buf);
653         }
654     }
655     return (ok);
656 }
657 
658 #define THREAD_STACK_SIZE (16*1024)
659 
660 #ifdef OPENSSL_SYS_WIN32
661 
662 static HANDLE *lock_cs;
663 
thread_setup(void)664 void thread_setup(void)
665 {
666     int i;
667 
668     lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(HANDLE));
669     for (i = 0; i < CRYPTO_num_locks(); i++) {
670         lock_cs[i] = CreateMutex(NULL, FALSE, NULL);
671     }
672 
673     CRYPTO_set_locking_callback((void (*)(int, int, char *, int))
674                                 win32_locking_callback);
675     /* id callback defined */
676 }
677 
thread_cleanup(void)678 void thread_cleanup(void)
679 {
680     int i;
681 
682     CRYPTO_set_locking_callback(NULL);
683     for (i = 0; i < CRYPTO_num_locks(); i++)
684         CloseHandle(lock_cs[i]);
685     OPENSSL_free(lock_cs);
686 }
687 
win32_locking_callback(int mode,int type,const char * file,int line)688 void win32_locking_callback(int mode, int type, const char *file, int line)
689 {
690     if (mode & CRYPTO_LOCK) {
691         WaitForSingleObject(lock_cs[type], INFINITE);
692     } else {
693         ReleaseMutex(lock_cs[type]);
694     }
695 }
696 
do_threads(SSL_CTX * s_ctx,SSL_CTX * c_ctx)697 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
698 {
699     double ret;
700     SSL_CTX *ssl_ctx[2];
701     DWORD thread_id[MAX_THREAD_NUMBER];
702     HANDLE thread_handle[MAX_THREAD_NUMBER];
703     int i;
704     SYSTEMTIME start, end;
705 
706     ssl_ctx[0] = s_ctx;
707     ssl_ctx[1] = c_ctx;
708 
709     GetSystemTime(&start);
710     for (i = 0; i < thread_number; i++) {
711         thread_handle[i] = CreateThread(NULL,
712                                         THREAD_STACK_SIZE,
713                                         (LPTHREAD_START_ROUTINE) ndoit,
714                                         (void *)ssl_ctx, 0L, &(thread_id[i]));
715     }
716 
717     BIO_printf(bio_stdout, "reaping\n");
718     for (i = 0; i < thread_number; i += 50) {
719         int j;
720 
721         j = (thread_number < (i + 50)) ? (thread_number - i) : 50;
722 
723         if (WaitForMultipleObjects(j,
724                                    (CONST HANDLE *) & (thread_handle[i]),
725                                    TRUE, INFINITE)
726             == WAIT_FAILED) {
727             BIO_printf(bio_err, "WaitForMultipleObjects failed:%d\n",
728                     GetLastError());
729             exit(1);
730         }
731     }
732     GetSystemTime(&end);
733 
734     if (start.wDayOfWeek > end.wDayOfWeek)
735         end.wDayOfWeek += 7;
736     ret = (end.wDayOfWeek - start.wDayOfWeek) * 24;
737 
738     ret = (ret + end.wHour - start.wHour) * 60;
739     ret = (ret + end.wMinute - start.wMinute) * 60;
740     ret = (ret + end.wSecond - start.wSecond);
741     ret += (end.wMilliseconds - start.wMilliseconds) / 1000.0;
742 
743     BIO_printf(bio_stdout, "win32 threads done - %.3f seconds\n", ret);
744 }
745 
746 #endif                          /* OPENSSL_SYS_WIN32 */
747 
748 #ifdef SOLARIS
749 
750 static mutex_t *lock_cs;
751 /*
752  * static rwlock_t *lock_cs;
753  */
754 static long *lock_count;
755 
thread_setup(void)756 void thread_setup(void)
757 {
758     int i;
759 
760     lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(mutex_t));
761     lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
762     for (i = 0; i < CRYPTO_num_locks(); i++) {
763         lock_count[i] = 0;
764         /* rwlock_init(&(lock_cs[i]),USYNC_THREAD,NULL); */
765         mutex_init(&(lock_cs[i]), USYNC_THREAD, NULL);
766     }
767 
768     CRYPTO_set_id_callback((unsigned long (*)(void))solaris_thread_id);
769     CRYPTO_set_locking_callback((void (*)(void))solaris_locking_callback);
770 }
771 
thread_cleanup(void)772 void thread_cleanup(void)
773 {
774     int i;
775 
776     CRYPTO_set_locking_callback(NULL);
777 
778     BIO_printf(bio_err, "cleanup\n");
779 
780     for (i = 0; i < CRYPTO_num_locks(); i++) {
781         /* rwlock_destroy(&(lock_cs[i])); */
782         mutex_destroy(&(lock_cs[i]));
783         BIO_printf(bio_err, "%8ld:%s\n", lock_count[i], CRYPTO_get_lock_name(i));
784     }
785     OPENSSL_free(lock_cs);
786     OPENSSL_free(lock_count);
787 
788     BIO_printf(bio_err, "done cleanup\n");
789 
790 }
791 
solaris_locking_callback(int mode,int type,const char * file,int line)792 void solaris_locking_callback(int mode, int type, const char *file, int line)
793 {
794 # ifdef undef
795     BIO_printf(bio_err, "thread=%4d mode=%s lock=%s %s:%d\n",
796                CRYPTO_thread_id(),
797                (mode & CRYPTO_LOCK) ? "l" : "u",
798                (type & CRYPTO_READ) ? "r" : "w", file, line);
799 # endif
800 
801     /*-
802     if (CRYPTO_LOCK_SSL_CERT == type)
803     BIO_printf(bio_err,"(t,m,f,l) %ld %d %s %d\n",
804                CRYPTO_thread_id(),
805                mode,file,line);
806     */
807     if (mode & CRYPTO_LOCK) {
808         /*-
809         if (mode & CRYPTO_READ)
810                 rw_rdlock(&(lock_cs[type]));
811         else
812                 rw_wrlock(&(lock_cs[type])); */
813 
814         mutex_lock(&(lock_cs[type]));
815         lock_count[type]++;
816     } else {
817 /*      rw_unlock(&(lock_cs[type]));  */
818         mutex_unlock(&(lock_cs[type]));
819     }
820 }
821 
do_threads(SSL_CTX * s_ctx,SSL_CTX * c_ctx)822 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
823 {
824     SSL_CTX *ssl_ctx[2];
825     thread_t thread_ctx[MAX_THREAD_NUMBER];
826     int i;
827 
828     ssl_ctx[0] = s_ctx;
829     ssl_ctx[1] = c_ctx;
830 
831     thr_setconcurrency(thread_number);
832     for (i = 0; i < thread_number; i++) {
833         thr_create(NULL, THREAD_STACK_SIZE,
834                    (void *(*)())ndoit, (void *)ssl_ctx, 0L, &(thread_ctx[i]));
835     }
836 
837     BIO_printf(bio_stdout, "reaping\n");
838     for (i = 0; i < thread_number; i++) {
839         thr_join(thread_ctx[i], NULL, NULL);
840     }
841 
842 #if 0 /* We can't currently find out the reference amount */
843     BIO_printf(bio_stdout, "solaris threads done (%d,%d)\n",
844                s_ctx->references, c_ctx->references);
845 #else
846     BIO_printf(bio_stdout, "solaris threads done\n");
847 #endif
848 }
849 
solaris_thread_id(CRYPTO_THREADID * tid)850 void solaris_thread_id(CRYPTO_THREADID *tid)
851 {
852     CRYPTO_THREADID_set_numeric((unsigned long)thr_self());
853 }
854 #endif                          /* SOLARIS */
855 
856 #ifdef IRIX
857 
858 static usptr_t *arena;
859 static usema_t **lock_cs;
860 
thread_setup(void)861 void thread_setup(void)
862 {
863     int i;
864     char filename[20];
865 
866     strlcpy(filename,"/tmp/mttest.XXXXXX", sizeof(filename));
867     mktemp(filename);
868 
869     usconfig(CONF_STHREADIOOFF);
870     usconfig(CONF_STHREADMALLOCOFF);
871     usconfig(CONF_INITUSERS, 100);
872     usconfig(CONF_LOCKTYPE, US_DEBUGPLUS);
873     arena = usinit(filename);
874     unlink(filename);
875 
876     lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(usema_t *));
877     for (i = 0; i < CRYPTO_num_locks(); i++) {
878         lock_cs[i] = usnewsema(arena, 1);
879     }
880 
881     CRYPTO_set_id_callback((unsigned long (*)(void))irix_thread_id);
882     CRYPTO_set_locking_callback((void (*)(void))irix_locking_callback);
883 }
884 
thread_cleanup(void)885 void thread_cleanup(void)
886 {
887     int i;
888 
889     CRYPTO_set_locking_callback(NULL);
890     for (i = 0; i < CRYPTO_num_locks(); i++) {
891         char buf[10];
892 
893         snprintf(buf, sizeof(buf), "%2d:",i);
894         usdumpsema(lock_cs[i], stdout, buf);
895         usfreesema(lock_cs[i], arena);
896     }
897     OPENSSL_free(lock_cs);
898 }
899 
irix_locking_callback(int mode,int type,const char * file,int line)900 void irix_locking_callback(int mode, int type, const char *file, int line)
901 {
902     if (mode & CRYPTO_LOCK) {
903         BIO_printf(bio_stdout, "lock %d\n", type);
904         uspsema(lock_cs[type]);
905     } else {
906         BIO_printf(bio_stdout, "unlock %d\n", type);
907         usvsema(lock_cs[type]);
908     }
909 }
910 
do_threads(SSL_CTX * s_ctx,SSL_CTX * c_ctx)911 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
912 {
913     SSL_CTX *ssl_ctx[2];
914     int thread_ctx[MAX_THREAD_NUMBER];
915     int i;
916 
917     ssl_ctx[0] = s_ctx;
918     ssl_ctx[1] = c_ctx;
919 
920     for (i = 0; i < thread_number; i++) {
921         thread_ctx[i] = sproc((void (*)())ndoit,
922                               PR_SADDR | PR_SFDS, (void *)ssl_ctx);
923     }
924 
925     BIO_printf(bio_stdout, "reaping\n");
926     for (i = 0; i < thread_number; i++) {
927         wait(NULL);
928     }
929 
930 #if 0 /* We can't currently find out the reference amount */
931     BIO_printf(bio_stdout, "irix threads done (%d,%d)\n",
932                s_ctx->references, c_ctx->references);
933 #else
934     BIO_printf(bio_stdout, "irix threads done\n");
935 #endif
936 }
937 
irix_thread_id(void)938 unsigned long irix_thread_id(void)
939 {
940     CRYPTO_THREADID_set_numeric((unsigned long)getpid());
941 }
942 #endif                          /* IRIX */
943 
944 #ifdef PTHREADS
945 
946 static pthread_mutex_t *lock_cs;
947 static long *lock_count;
948 
thread_setup(void)949 void thread_setup(void)
950 {
951     int i;
952 
953     lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
954     lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
955     for (i = 0; i < CRYPTO_num_locks(); i++) {
956         lock_count[i] = 0;
957         pthread_mutex_init(&(lock_cs[i]), NULL);
958     }
959 
960     CRYPTO_set_id_callback((unsigned long (*)(void))pthreads_thread_id);
961     CRYPTO_set_locking_callback((void (*)(int, int, const char *, int))pthreads_locking_callback);
962 }
963 
thread_cleanup(void)964 void thread_cleanup(void)
965 {
966     int i;
967 
968     CRYPTO_set_locking_callback(NULL);
969     BIO_printf(bio_err, "cleanup\n");
970     for (i = 0; i < CRYPTO_num_locks(); i++) {
971         pthread_mutex_destroy(&(lock_cs[i]));
972         BIO_printf(bio_err, "%8ld:%s\n", lock_count[i], CRYPTO_get_lock_name(i));
973     }
974     OPENSSL_free(lock_cs);
975     OPENSSL_free(lock_count);
976 
977     BIO_printf(bio_err, "done cleanup\n");
978 }
979 
pthreads_locking_callback(int mode,int type,const char * file,int line)980 void pthreads_locking_callback(int mode, int type, const char *file, int line)
981 {
982 # ifdef undef
983     BIO_printf(bio_err, "thread=%4d mode=%s lock=%s %s:%d\n",
984                CRYPTO_thread_id(),
985                (mode & CRYPTO_LOCK) ? "l" : "u",
986                (type & CRYPTO_READ) ? "r" : "w", file, line);
987 # endif
988 /*-
989     if (CRYPTO_LOCK_SSL_CERT == type)
990             BIO_printf(bio_err,"(t,m,f,l) %ld %d %s %d\n",
991                        CRYPTO_thread_id(),
992                        mode,file,line);
993 */
994     if (mode & CRYPTO_LOCK) {
995         pthread_mutex_lock(&(lock_cs[type]));
996         lock_count[type]++;
997     } else {
998         pthread_mutex_unlock(&(lock_cs[type]));
999     }
1000 }
1001 
do_threads(SSL_CTX * s_ctx,SSL_CTX * c_ctx)1002 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
1003 {
1004     SSL_CTX *ssl_ctx[2];
1005     pthread_t thread_ctx[MAX_THREAD_NUMBER];
1006     int i;
1007 
1008     ssl_ctx[0] = s_ctx;
1009     ssl_ctx[1] = c_ctx;
1010 
1011     /*
1012      * thr_setconcurrency(thread_number);
1013      */
1014     for (i = 0; i < thread_number; i++) {
1015         pthread_create(&(thread_ctx[i]), NULL,
1016                        (void *(*)(void *))ndoit, (void *)ssl_ctx);
1017     }
1018 
1019     BIO_printf(bio_stdout, "reaping\n");
1020     for (i = 0; i < thread_number; i++) {
1021         pthread_join(thread_ctx[i], NULL);
1022     }
1023 
1024 #if 0 /* We can't currently find out the reference amount */
1025     BIO_printf(bio_stdout, "pthreads threads done (%d,%d)\n",
1026                s_ctx->references, c_ctx->references);
1027 #else
1028     BIO_printf(bio_stdout, "pthreads threads done\n");
1029 #endif
1030 }
1031 
pthreads_thread_id(CRYPTO_THREADID * tid)1032 void pthreads_thread_id(CRYPTO_THREADID *tid)
1033 {
1034     CRYPTO_THREADID_set_numeric(tid, (unsigned long)pthread_self());
1035 }
1036 
1037 #endif                          /* PTHREADS */
1038 
1039 #ifdef OPENSSL_SYS_NETWARE
1040 
thread_setup(void)1041 void thread_setup(void)
1042 {
1043     int i;
1044 
1045     lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(MPKMutex));
1046     lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1047     for (i = 0; i < CRYPTO_num_locks(); i++) {
1048         lock_count[i] = 0;
1049         lock_cs[i] = MPKMutexAlloc("OpenSSL mutex");
1050     }
1051 
1052     ThreadSem = MPKSemaphoreAlloc("OpenSSL mttest semaphore", 0);
1053 
1054     CRYPTO_set_id_callback(netware_thread_id);
1055     CRYPTO_set_locking_callback(netware_locking_callback);
1056 }
1057 
thread_cleanup(void)1058 void thread_cleanup(void)
1059 {
1060     int i;
1061 
1062     CRYPTO_set_locking_callback(NULL);
1063 
1064     BIO_printf(bio_stdout, "thread_cleanup\n");
1065 
1066     for (i = 0; i < CRYPTO_num_locks(); i++) {
1067         MPKMutexFree(lock_cs[i]);
1068         BIO_printf(bio_stdout, "%8ld:%s\n", lock_count[i], CRYPTO_get_lock_name(i));
1069     }
1070     OPENSSL_free(lock_cs);
1071     OPENSSL_free(lock_count);
1072 
1073     MPKSemaphoreFree(ThreadSem);
1074 
1075     BIO_printf(bio_stdout, "done cleanup\n");
1076 }
1077 
netware_locking_callback(int mode,int type,const char * file,int line)1078 void netware_locking_callback(int mode, int type, const char *file, int line)
1079 {
1080     if (mode & CRYPTO_LOCK) {
1081         MPKMutexLock(lock_cs[type]);
1082         lock_count[type]++;
1083     } else
1084         MPKMutexUnlock(lock_cs[type]);
1085 }
1086 
do_threads(SSL_CTX * s_ctx,SSL_CTX * c_ctx)1087 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
1088 {
1089     SSL_CTX *ssl_ctx[2];
1090     int i;
1091     ssl_ctx[0] = s_ctx;
1092     ssl_ctx[1] = c_ctx;
1093 
1094     for (i = 0; i < thread_number; i++) {
1095         BeginThread((void (*)(void *))ndoit, NULL, THREAD_STACK_SIZE,
1096                     (void *)ssl_ctx);
1097         ThreadSwitchWithDelay();
1098     }
1099 
1100     BIO_printf(bio_stdout, "reaping\n");
1101 
1102     /* loop until all threads have signaled the semaphore */
1103     for (i = 0; i < thread_number; i++) {
1104         MPKSemaphoreWait(ThreadSem);
1105     }
1106 #if 0 /* We can't currently find out the reference amount */
1107     BIO_printf(bio_stdout, "netware threads done (%d,%d)\n",
1108                s_ctx->references, c_ctx->references);
1109 #else
1110     BIO_printf(bio_stdout, "netware threads done\n");
1111 #endif
1112 }
1113 
netware_thread_id(void)1114 unsigned long netware_thread_id(void)
1115 {
1116     CRYPTO_THREADID_set_numeric((unsigned long)GetThreadID());
1117 }
1118 #endif                          /* NETWARE */
1119 
1120 #ifdef BEOS_THREADS
1121 
1122 # include <Locker.h>
1123 
1124 static BLocker **lock_cs;
1125 static long *lock_count;
1126 
thread_setup(void)1127 void thread_setup(void)
1128 {
1129     int i;
1130 
1131     lock_cs =
1132         (BLocker **) OPENSSL_malloc(CRYPTO_num_locks() * sizeof(BLocker *));
1133     lock_count = (long *)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1134     for (i = 0; i < CRYPTO_num_locks(); i++) {
1135         lock_count[i] = 0;
1136         lock_cs[i] = new BLocker(CRYPTO_get_lock_name(i));
1137     }
1138 
1139     CRYPTO_set_id_callback((unsigned long (*)(void))beos_thread_id);
1140     CRYPTO_set_locking_callback(beos_locking_callback);
1141 }
1142 
thread_cleanup(void)1143 void thread_cleanup(void)
1144 {
1145     int i;
1146 
1147     CRYPTO_set_locking_callback(NULL);
1148     BIO_printf(bio_err, "cleanup\n");
1149     for (i = 0; i < CRYPTO_num_locks(); i++) {
1150         delete lock_cs[i];
1151         BIO_printf(bio_err, "%8ld:%s\n", lock_count[i], CRYPTO_get_lock_name(i));
1152     }
1153     OPENSSL_free(lock_cs);
1154     OPENSSL_free(lock_count);
1155 
1156     BIO_printf(bio_err, "done cleanup\n");
1157 }
1158 
beos_locking_callback(int mode,int type,const char * file,int line)1159 void beos_locking_callback(int mode, int type, const char *file, int line)
1160 {
1161 # if 0
1162     BIO_printf(bio_err, "thread=%4d mode=%s lock=%s %s:%d\n",
1163                CRYPTO_thread_id(),
1164                (mode & CRYPTO_LOCK) ? "l" : "u",
1165                (type & CRYPTO_READ) ? "r" : "w", file, line);
1166 # endif
1167     if (mode & CRYPTO_LOCK) {
1168         lock_cs[type]->Lock();
1169         lock_count[type]++;
1170     } else {
1171         lock_cs[type]->Unlock();
1172     }
1173 }
1174 
do_threads(SSL_CTX * s_ctx,SSL_CTX * c_ctx)1175 void do_threads(SSL_CTX *s_ctx, SSL_CTX *c_ctx)
1176 {
1177     SSL_CTX *ssl_ctx[2];
1178     thread_id thread_ctx[MAX_THREAD_NUMBER];
1179     int i;
1180 
1181     ssl_ctx[0] = s_ctx;
1182     ssl_ctx[1] = c_ctx;
1183 
1184     for (i = 0; i < thread_number; i++) {
1185         thread_ctx[i] = spawn_thread((thread_func) ndoit,
1186                                      NULL, B_NORMAL_PRIORITY,
1187                                      (void *)ssl_ctx);
1188         resume_thread(thread_ctx[i]);
1189     }
1190 
1191     BIO_printf(bio_stdout, "waiting...\n");
1192     for (i = 0; i < thread_number; i++) {
1193         status_t result;
1194         wait_for_thread(thread_ctx[i], &result);
1195     }
1196 
1197     BIO_printf(bio_stdout, "beos threads done (%d,%d)\n",
1198                s_ctx->references, c_ctx->references);
1199 }
1200 
beos_thread_id(void)1201 unsigned long beos_thread_id(void)
1202 {
1203     unsigned long ret;
1204 
1205     ret = (unsigned long)find_thread(NULL);
1206     return (ret);
1207 }
1208 
1209 #endif                          /* BEOS_THREADS */
1210