Fixed some race conditions.
[openssl.git] / apps / s_time.c
1 /* apps/s_time.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 #define NO_SHUTDOWN
60
61 /*-----------------------------------------
62    s_time - SSL client connection timer program
63    Written and donated by Larry Streepy <streepy@healthcare.com>
64   -----------------------------------------*/
65
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69
70 #ifdef NO_STDIO
71 #define APPS_WIN16
72 #endif
73 #include "x509.h"
74 #include "ssl.h"
75 #include "pem.h"
76 #define USE_SOCKETS
77 #include "apps.h"
78 #include "s_apps.h"
79 #include "err.h"
80 #ifdef WIN32_STUFF
81 #include "winmain.h"
82 #include "wintext.h"
83 #endif
84
85 #ifndef MSDOS
86 #define TIMES
87 #endif
88
89 #ifndef VMS
90 #ifndef _IRIX
91 #include <time.h>
92 #endif
93 #ifdef TIMES
94 #include <sys/types.h>
95 #include <sys/times.h>
96 #endif
97 #else /* VMS */
98 #include <types.h>
99 struct tms {
100         time_t tms_utime;
101         time_t tms_stime;
102         time_t tms_uchild;      /* I dunno...  */
103         time_t tms_uchildsys;   /* so these names are a guess :-) */
104         }
105 #endif
106 #ifndef TIMES
107 #include <sys/timeb.h>
108 #endif
109
110 #ifdef _AIX
111 #include <sys/select.h>
112 #endif
113
114 #if defined(sun) || defined(__ultrix)
115 #define _POSIX_SOURCE
116 #include <limits.h>
117 #include <sys/param.h>
118 #endif
119
120 /* The following if from times(3) man page.  It may need to be changed
121 */
122 #ifndef HZ
123 #ifndef CLK_TCK
124 #ifndef VMS
125 #define HZ      100.0
126 #else /* VMS */
127 #define HZ      100.0
128 #endif
129 #else /* CLK_TCK */
130 #define HZ ((double)CLK_TCK)
131 #endif
132 #endif
133
134 #undef PROG
135 #define PROG s_time_main
136
137 #define ioctl ioctlsocket
138
139 #define SSL_CONNECT_NAME        "localhost:4433"
140
141 /*#define TEST_CERT "client.pem" */ /* no default cert. */
142
143 #undef BUFSIZZ
144 #define BUFSIZZ 1024*10
145
146 #define min(a,b) (((a) < (b)) ? (a) : (b))
147 #define max(a,b) (((a) > (b)) ? (a) : (b))
148
149 #undef SECONDS
150 #define SECONDS 30
151 extern int verify_depth;
152 extern int verify_error;
153
154 #ifndef NOPROTO
155 static void s_time_usage(void);
156 static int parseArgs( int argc, char **argv );
157 static SSL *doConnection( SSL *scon );
158 static void s_time_init(void);
159 #else
160 static void s_time_usage();
161 static int parseArgs();
162 static SSL *doConnection();
163 static void s_time_init();
164 #endif
165
166
167 /***********************************************************************
168  * Static data declarations
169  */
170
171 /* static char *port=PORT_STR;*/
172 static char *host=SSL_CONNECT_NAME;
173 static char *t_cert_file=NULL;
174 static char *t_key_file=NULL;
175 static char *CApath=NULL;
176 static char *CAfile=NULL;
177 static char *tm_cipher=NULL;
178 static int tm_verify = SSL_VERIFY_NONE;
179 static int maxTime = SECONDS;
180 static SSL_CTX *tm_ctx=NULL;
181 static SSL_METHOD *s_time_meth=NULL;
182 static char *s_www_path=NULL;
183 static long bytes_read=0; 
184 static int st_bugs=0;
185 static int perform=0;
186 #ifdef FIONBIO
187 static int t_nbio=0;
188 #endif
189 #ifdef WIN32
190 static int exitNow = 0;         /* Set when it's time to exit main */
191 #endif
192
193 static void s_time_init(void)
194         {
195         host=SSL_CONNECT_NAME;
196         t_cert_file=NULL;
197         t_key_file=NULL;
198         CApath=NULL;
199         CAfile=NULL;
200         tm_cipher=NULL;
201         tm_verify = SSL_VERIFY_NONE;
202         maxTime = SECONDS;
203         tm_ctx=NULL;
204         s_time_meth=NULL;
205         s_www_path=NULL;
206         bytes_read=0; 
207         st_bugs=0;
208         perform=0;
209
210 #ifdef FIONBIO
211         t_nbio=0;
212 #endif
213 #ifdef WIN32
214         exitNow = 0;            /* Set when it's time to exit main */
215 #endif
216         }
217
218 /***********************************************************************
219  * usage - display usage message
220  */
221 static void s_time_usage(void)
222 {
223         static char umsg[] = "\
224 -time arg     - max number of seconds to collect data, default %d\n\
225 -verify arg   - turn on peer certificate verification, arg == depth\n\
226 -cert arg     - certificate file to use, PEM format assumed\n\
227 -key arg      - RSA file to use, PEM format assumed, key is in cert file\n\
228                 file if not specified by this option\n\
229 -CApath arg   - PEM format directory of CA's\n\
230 -CAfile arg   - PEM format file of CA's\n\
231 -cipher       - prefered cipher to use, play with 'openssl ciphers'\n\n";
232
233         printf( "usage: s_time <args>\n\n" );
234
235         printf("-connect host:port - host:port to connect to (default is %s)\n",SSL_CONNECT_NAME);
236 #ifdef FIONBIO
237         printf("-nbio         - Run with non-blocking IO\n");
238         printf("-ssl2         - Just use SSLv2\n");
239         printf("-ssl3         - Just use SSLv3\n");
240         printf("-bugs         - Turn on SSL bug compatability\n");
241         printf("-new          - Just time new connections\n");
242         printf("-reuse        - Just time connection reuse\n");
243         printf("-www page     - Retrieve 'page' from the site\n");
244 #endif
245         printf( umsg,SECONDS );
246 }
247
248 /***********************************************************************
249  * parseArgs - Parse command line arguments and initialize data
250  *
251  * Returns 0 if ok, -1 on bad args
252  */
253 static int parseArgs(int argc, char **argv)
254 {
255     int badop = 0;
256
257     verify_depth=0;
258     verify_error=X509_V_OK;
259 #ifdef FIONBIO
260     t_nbio=0;
261 #endif
262
263         apps_startup();
264         s_time_init();
265
266         if (bio_err == NULL)
267                 bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
268
269     argc--;
270     argv++;
271
272     while (argc >= 1) {
273         if (strcmp(*argv,"-connect") == 0)
274                 {
275                 if (--argc < 1) goto bad;
276                 host= *(++argv);
277                 }
278 #if 0
279         else if( strcmp(*argv,"-host") == 0)
280                 {
281                 if (--argc < 1) goto bad;
282                 host= *(++argv);
283                 }
284         else if( strcmp(*argv,"-port") == 0)
285                 {
286                 if (--argc < 1) goto bad;
287                 port= *(++argv);
288                 }
289 #endif
290         else if (strcmp(*argv,"-reuse") == 0)
291                 perform=2;
292         else if (strcmp(*argv,"-new") == 0)
293                 perform=1;
294         else if( strcmp(*argv,"-verify") == 0) {
295
296             tm_verify=SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE;
297             if (--argc < 1) goto bad;
298             verify_depth=atoi(*(++argv));
299             BIO_printf(bio_err,"verify depth is %d\n",verify_depth);
300
301         } else if( strcmp(*argv,"-cert") == 0) {
302
303             if (--argc < 1) goto bad;
304             t_cert_file= *(++argv);
305
306         } else if( strcmp(*argv,"-key") == 0) {
307
308             if (--argc < 1) goto bad;
309             t_key_file= *(++argv);
310
311         } else if( strcmp(*argv,"-CApath") == 0) {
312
313             if (--argc < 1) goto bad;
314             CApath= *(++argv);
315
316         } else if( strcmp(*argv,"-CAfile") == 0) {
317
318             if (--argc < 1) goto bad;
319             CAfile= *(++argv);
320
321         } else if( strcmp(*argv,"-cipher") == 0) {
322
323             if (--argc < 1) goto bad;
324             tm_cipher= *(++argv);
325         }
326 #ifdef FIONBIO
327         else if(strcmp(*argv,"-nbio") == 0) {
328             t_nbio=1;
329         }
330 #endif
331         else if(strcmp(*argv,"-www") == 0)
332                 {
333                 if (--argc < 1) goto bad;
334                 s_www_path= *(++argv);
335                 }
336         else if(strcmp(*argv,"-bugs") == 0)
337             st_bugs=1;
338 #ifndef NO_SSL2
339         else if(strcmp(*argv,"-ssl2") == 0)
340             s_time_meth=SSLv2_client_method();
341 #endif
342 #ifndef NO_SSL3
343         else if(strcmp(*argv,"-ssl3") == 0)
344             s_time_meth=SSLv3_client_method();
345 #endif
346         else if( strcmp(*argv,"-time") == 0) {
347
348             if (--argc < 1) goto bad;
349             maxTime= atoi(*(++argv));
350         }
351         else {
352             BIO_printf(bio_err,"unknown option %s\n",*argv);
353             badop=1;
354             break;
355         }
356
357         argc--;
358         argv++;
359     }
360
361     if (perform == 0) perform=3;
362
363     if(badop) {
364 bad:
365                 s_time_usage();
366                 return -1;
367     }
368
369         return 0;                       /* Valid args */
370 }
371
372 /***********************************************************************
373  * TIME - time functions
374  */
375 #define START   0
376 #define STOP    1
377
378 static double tm_Time_F(int s)
379         {
380         static double ret;
381 #ifdef TIMES
382         static struct tms tstart,tend;
383
384         if(s == START) {
385                 times(&tstart);
386                 return(0);
387         } else {
388                 times(&tend);
389                 ret=((double)(tend.tms_utime-tstart.tms_utime))/HZ;
390                 return((ret == 0.0)?1e-6:ret);
391         }
392 #else /* !times() */
393         static struct timeb tstart,tend;
394         long i;
395
396         if(s == START) {
397                 ftime(&tstart);
398                 return(0);
399         } else {
400                 ftime(&tend);
401                 i=(long)tend.millitm-(long)tstart.millitm;
402                 ret=((double)(tend.time-tstart.time))+((double)i)/1000.0;
403                 return((ret == 0.0)?1e-6:ret);
404         }
405 #endif
406 }
407
408 /***********************************************************************
409  * MAIN - main processing area for client
410  *                      real name depends on MONOLITH
411  */
412 int MAIN(int argc, char **argv)
413         {
414         double totalTime = 0.0;
415         int nConn = 0;
416         SSL *scon=NULL;
417         long finishtime=0;
418         int ret=1,i;
419         MS_STATIC char buf[1024*8];
420         int ver;
421
422 #if !defined(NO_SSL2) && !defined(NO_SSL3)
423         s_time_meth=SSLv23_client_method();
424 #elif !defined(NO_SSL3)
425         s_time_meth=SSLv3_client_method();
426 #elif !defined(NO_SSL2)
427         s_time_meth=SSLv2_client_method();
428 #endif
429
430         /* parse the command line arguments */
431         if( parseArgs( argc, argv ) < 0 )
432                 goto end;
433
434         SSLeay_add_ssl_algorithms();
435         if ((tm_ctx=SSL_CTX_new(s_time_meth)) == NULL) return(1);
436
437         SSL_CTX_set_quiet_shutdown(tm_ctx,1);
438
439         if (st_bugs) SSL_CTX_set_options(tm_ctx,SSL_OP_ALL);
440         SSL_CTX_set_cipher_list(tm_ctx,tm_cipher);
441         if(!set_cert_stuff(tm_ctx,t_cert_file,t_key_file)) 
442                 goto end;
443
444         SSL_load_error_strings();
445
446         if ((!SSL_CTX_load_verify_locations(tm_ctx,CAfile,CApath)) ||
447                 (!SSL_CTX_set_default_verify_paths(tm_ctx)))
448                 {
449                 /* BIO_printf(bio_err,"error seting default verify locations\n"); */
450                 ERR_print_errors(bio_err);
451                 /* goto end; */
452                 }
453
454         if (tm_cipher == NULL)
455                 tm_cipher = getenv("SSL_CIPHER");
456
457         if (tm_cipher == NULL ) {
458                 fprintf( stderr, "No CIPHER specified\n" );
459 /*              EXIT(1); */
460         }
461
462         if (!(perform & 1)) goto next;
463         printf( "Collecting connection statistics for %d seconds\n", maxTime );
464
465         /* Loop and time how long it takes to make connections */
466
467         bytes_read=0;
468         finishtime=(long)time(NULL)+maxTime;
469         tm_Time_F(START);
470         for (;;)
471                 {
472                 if (finishtime < time(NULL)) break;
473 #ifdef WIN32_STUFF
474
475                 if( flushWinMsgs(0) == -1 )
476                         goto end;
477
478                 if( waitingToDie || exitNow )           /* we're dead */
479                         goto end;
480 #endif
481
482                 if( (scon = doConnection( NULL )) == NULL )
483                         goto end;
484
485                 if (s_www_path != NULL)
486                         {
487                         sprintf(buf,"GET %s HTTP/1.0\r\n\r\n",s_www_path);
488                         SSL_write(scon,buf,strlen(buf));
489                         while ((i=SSL_read(scon,buf,sizeof(buf))) > 0)
490                                 bytes_read+=i;
491                         }
492
493 #ifdef NO_SHUTDOWN
494                 SSL_set_shutdown(scon,SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
495 #else
496                 SSL_shutdown(scon);
497 #endif
498                 SHUTDOWN2(SSL_get_fd(scon));
499
500                 nConn += 1;
501                 if (SSL_session_reused(scon))
502                         ver='r';
503                 else
504                         {
505                         ver=SSL_version(scon);
506                         if (ver == TLS1_VERSION)
507                                 ver='t';
508                         else if (ver == SSL3_VERSION)
509                                 ver='3';
510                         else if (ver == SSL2_VERSION)
511                                 ver='2';
512                         else
513                                 ver='*';
514                         }
515                 fputc(ver,stdout);
516                 fflush(stdout);
517
518                 SSL_free( scon );
519                 scon=NULL;
520                 }
521         totalTime += tm_Time_F(STOP); /* Add the time for this iteration */
522
523         i=(int)(time(NULL)-finishtime+maxTime);
524         printf( "\n\n%d connections in %.2fs; %.2f connections/user sec, bytes read %ld\n", nConn, totalTime, ((double)nConn/totalTime),bytes_read);
525         printf( "%d connections in %ld real seconds, %ld bytes read per connection\n",nConn,time(NULL)-finishtime+maxTime,bytes_read/nConn);
526
527         /* Now loop and time connections using the same session id over and over */
528
529 next:
530         if (!(perform & 2)) goto end;
531         printf( "\n\nNow timing with session id reuse.\n" );
532
533         /* Get an SSL object so we can reuse the session id */
534         if( (scon = doConnection( NULL )) == NULL )
535                 {
536                 fprintf( stderr, "Unable to get connection\n" );
537                 goto end;
538                 }
539
540         if (s_www_path != NULL)
541                 {
542                 sprintf(buf,"GET %s HTTP/1.0\r\n\r\n",s_www_path);
543                 SSL_write(scon,buf,strlen(buf));
544                 while (SSL_read(scon,buf,sizeof(buf)) > 0)
545                         ;
546                 }
547 #ifdef NO_SHUTDOWN
548         SSL_set_shutdown(scon,SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
549 #else
550         SSL_shutdown(scon);
551 #endif
552         SHUTDOWN2(SSL_get_fd(scon));
553
554         nConn = 0;
555         totalTime = 0.0;
556
557         finishtime=time(NULL)+maxTime;
558
559         printf( "starting\n" );
560         bytes_read=0;
561         tm_Time_F(START);
562                 
563         for (;;)
564                 {
565                 if (finishtime < time(NULL)) break;
566
567 #ifdef WIN32_STUFF
568                 if( flushWinMsgs(0) == -1 )
569                         goto end;
570
571                 if( waitingToDie || exitNow )   /* we're dead */
572                         goto end;
573 #endif
574
575                 if( (doConnection( scon )) == NULL )
576                         goto end;
577
578                 if (s_www_path)
579                         {
580                         sprintf(buf,"GET %s HTTP/1.0\r\n\r\n",s_www_path);
581                         SSL_write(scon,buf,strlen(buf));
582                         while ((i=SSL_read(scon,buf,sizeof(buf))) > 0)
583                                 bytes_read+=i;
584                         }
585
586 #ifdef NO_SHUTDOWN
587                 SSL_set_shutdown(scon,SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
588 #else
589                 SSL_shutdown(scon);
590 #endif
591                 SHUTDOWN2(SSL_get_fd(scon));
592         
593                 nConn += 1;
594                 if (SSL_session_reused(scon))
595                         ver='r';
596                 else
597                         {
598                         ver=SSL_version(scon);
599                         if (ver == TLS1_VERSION)
600                                 ver='t';
601                         else if (ver == SSL3_VERSION)
602                                 ver='3';
603                         else if (ver == SSL2_VERSION)
604                                 ver='2';
605                         else
606                                 ver='*';
607                         }
608                 fputc(ver,stdout);
609                 fflush(stdout);
610                 }
611         totalTime += tm_Time_F(STOP); /* Add the time for this iteration*/
612
613
614         printf( "\n\n%d connections in %.2fs; %.2f connections/user sec, bytes read %ld\n", nConn, totalTime, ((double)nConn/totalTime),bytes_read);
615         printf( "%d connections in %ld real seconds, %ld bytes read per connection\n",nConn,time(NULL)-finishtime+maxTime,bytes_read/nConn);
616
617         ret=0;
618 end:
619         if (scon != NULL) SSL_free(scon);
620
621         if (tm_ctx != NULL)
622                 {
623                 SSL_CTX_free(tm_ctx);
624                 tm_ctx=NULL;
625                 }
626         EXIT(ret);
627         }
628
629 /***********************************************************************
630  * doConnection - make a connection
631  * Args:
632  *              scon    = earlier ssl connection for session id, or NULL
633  * Returns:
634  *              SSL *   = the connection pointer.
635  */
636 static SSL *doConnection(SSL *scon)
637         {
638         BIO *conn;
639         SSL *serverCon;
640         int width, i;
641         fd_set readfds;
642
643         if ((conn=BIO_new(BIO_s_connect())) == NULL)
644                 return(NULL);
645
646 /*      BIO_set_conn_port(conn,port);*/
647         BIO_set_conn_hostname(conn,host);
648
649         if (scon == NULL)
650                 serverCon=(SSL *)SSL_new(tm_ctx);
651         else
652                 {
653                 serverCon=scon;
654                 SSL_set_connect_state(serverCon);
655                 }
656
657         SSL_set_bio(serverCon,conn,conn);
658
659 #if 0
660         if( scon != NULL )
661                 SSL_set_session(serverCon,SSL_get_session(scon));
662 #endif
663
664         /* ok, lets connect */
665         for(;;) {
666                 i=SSL_connect(serverCon);
667                 if (BIO_sock_should_retry(i))
668                         {
669                         BIO_printf(bio_err,"DELAY\n");
670
671                         i=SSL_get_fd(serverCon);
672                         width=i+1;
673                         FD_ZERO(&readfds);
674                         FD_SET(i,&readfds);
675                         select(width,&readfds,NULL,NULL,NULL);
676                         continue;
677                         }
678                 break;
679                 }
680         if(i <= 0)
681                 {
682                 BIO_printf(bio_err,"ERROR\n");
683                 if (verify_error != X509_V_OK)
684                         BIO_printf(bio_err,"verify error:%s\n",
685                                 X509_verify_cert_error_string(verify_error));
686                 else
687                         ERR_print_errors(bio_err);
688                 if (scon == NULL)
689                         SSL_free(serverCon);
690                 return NULL;
691                 }
692
693         return serverCon;
694         }
695
696