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