]> granicus.if.org Git - apache/blob - support/ab.c
XML updates.
[apache] / support / ab.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18    ** This program is based on ZeusBench V1.0 written by Adam Twiss
19    ** which is Copyright (c) 1996 by Zeus Technology Ltd. http://www.zeustech.net/
20    **
21    ** This software is provided "as is" and any express or implied waranties,
22    ** including but not limited to, the implied warranties of merchantability and
23    ** fitness for a particular purpose are disclaimed.  In no event shall
24    ** Zeus Technology Ltd. be liable for any direct, indirect, incidental, special,
25    ** exemplary, or consequential damaged (including, but not limited to,
26    ** procurement of substitute good or services; loss of use, data, or profits;
27    ** or business interruption) however caused and on theory of liability.  Whether
28    ** in contract, strict liability or tort (including negligence or otherwise)
29    ** arising in any way out of the use of this software, even if advised of the
30    ** possibility of such damage.
31    **
32  */
33
34 /*
35    ** HISTORY:
36    **    - Originally written by Adam Twiss <adam@zeus.co.uk>, March 1996
37    **      with input from Mike Belshe <mbelshe@netscape.com> and
38    **      Michael Campanella <campanella@stevms.enet.dec.com>
39    **    - Enhanced by Dean Gaudet <dgaudet@apache.org>, November 1997
40    **    - Cleaned up by Ralf S. Engelschall <rse@apache.org>, March 1998
41    **    - POST and verbosity by Kurt Sussman <kls@merlot.com>, August 1998
42    **    - HTML table output added by David N. Welton <davidw@prosa.it>, January 1999
43    **    - Added Cookie, Arbitrary header and auth support. <dirkx@webweaving.org>, April 1999
44    ** Version 1.3d
45    **    - Increased version number - as some of the socket/error handling has
46    **      fundamentally changed - and will give fundamentally different results
47    **      in situations where a server is dropping requests. Therefore you can
48    **      no longer compare results of AB as easily. Hence the inc of the version.
49    **      They should be closer to the truth though. Sander & <dirkx@covalent.net>, End 2000.
50    **    - Fixed proxy functionality, added median/mean statistics, added gnuplot
51    **      output option, added _experimental/rudimentary_ SSL support. Added
52    **      confidence guestimators and warnings. Sander & <dirkx@covalent.net>, End 2000
53    **    - Fixed serious int overflow issues which would cause realistic (longer
54    **      than a few minutes) run's to have wrong (but believable) results. Added
55    **      trapping of connection errors which influenced measurements.
56    **      Contributed by Sander Temme, Early 2001
57    ** Version 1.3e
58    **    - Changed timeout behavour during write to work whilst the sockets
59    **      are filling up and apr_write() does writes a few - but not all.
60    **      This will potentially change results. <dirkx@webweaving.org>, April 2001
61    ** Version 2.0.36-dev
62    **    Improvements to concurrent processing:
63    **      - Enabled non-blocking connect()s.
64    **      - Prevent blocking calls to apr_socket_recv() (thereby allowing AB to
65    **        manage its entire set of socket descriptors).
66    **      - Any error returned from apr_socket_recv() that is not EAGAIN or EOF
67    **        is now treated as fatal.
68    **      Contributed by Aaron Bannert, April 24, 2002
69    **
70    ** Version 2.0.36-2
71    **     Internalized the version string - this string is part
72    **     of the Agent: header and the result output.
73    **
74    ** Version 2.0.37-dev
75    **     Adopted SSL code by Madhu Mathihalli <madhusudan_mathihalli@hp.com>
76    **     [PATCH] ab with SSL support  Posted Wed, 15 Aug 2001 20:55:06 GMT
77    **     Introduces four 'if (int == value)' tests per non-ssl request.
78    **
79    ** Version 2.0.40-dev
80    **     Switched to the new abstract pollset API, allowing ab to
81    **     take advantage of future apr_pollset_t scalability improvements.
82    **     Contributed by Brian Pane, August 31, 2002
83    **
84    ** Version 2.3
85    **     SIGINT now triggers output_results().
86    **     Contributed by colm, March 30, 2006
87    **/
88
89 /* Note: this version string should start with \d+[\d\.]* and be a valid
90  * string for an HTTP Agent: header when prefixed with 'ApacheBench/'.
91  * It should reflect the version of AB - and not that of the apache server
92  * it happens to accompany. And it should be updated or changed whenever
93  * the results are no longer fundamentally comparable to the results of
94  * a previous version of ab. Either due to a change in the logic of
95  * ab - or to due to a change in the distribution it is compiled with
96  * (such as an APR change in for example blocking).
97  */
98 #define AP_AB_BASEREVISION "2.3"
99
100 /*
101  * BUGS:
102  *
103  * - uses strcpy/etc.
104  * - has various other poor buffer attacks related to the lazy parsing of
105  *   response headers from the server
106  * - doesn't implement much of HTTP/1.x, only accepts certain forms of
107  *   responses
108  * - (performance problem) heavy use of strstr shows up top in profile
109  *   only an issue for loopback usage
110  */
111
112 /*  -------------------------------------------------------------------- */
113
114 #if 'A' != 0x41
115 /* Hmmm... This source code isn't being compiled in ASCII.
116  * In order for data that flows over the network to make
117  * sense, we need to translate to/from ASCII.
118  */
119 #define NOT_ASCII
120 #endif
121
122 /* affects include files on Solaris */
123 #define BSD_COMP
124
125 #include "apr.h"
126 #include "apr_signal.h"
127 #include "apr_strings.h"
128 #include "apr_network_io.h"
129 #include "apr_file_io.h"
130 #include "apr_time.h"
131 #include "apr_getopt.h"
132 #include "apr_general.h"
133 #include "apr_lib.h"
134 #include "apr_portable.h"
135 #include "ap_release.h"
136 #include "apr_poll.h"
137
138 #define APR_WANT_STRFUNC
139 #include "apr_want.h"
140
141 #include "apr_base64.h"
142 #ifdef NOT_ASCII
143 #include "apr_xlate.h"
144 #endif
145 #if APR_HAVE_STDIO_H
146 #include <stdio.h>
147 #endif
148 #if APR_HAVE_STDLIB_H
149 #include <stdlib.h>
150 #endif
151 #if APR_HAVE_UNISTD_H
152 #include <unistd.h> /* for getpid() */
153 #endif
154
155 #if !defined(WIN32) && !defined(NETWARE)
156 #include "ap_config_auto.h"
157 #endif
158
159 #if defined(HAVE_OPENSSL)
160
161 #include <openssl/rsa.h>
162 #include <openssl/crypto.h>
163 #include <openssl/x509.h>
164 #include <openssl/pem.h>
165 #include <openssl/err.h>
166 #include <openssl/ssl.h>
167 #include <openssl/rand.h>
168 #define USE_SSL
169 #define SK_NUM(x) sk_X509_num(x)
170 #define SK_VALUE(x,y) sk_X509_value(x,y)
171 typedef STACK_OF(X509) X509_STACK_TYPE;
172
173 #if defined(_MSC_VER) && !defined(LIBRESSL_VERSION_NUMBER)
174 /* The following logic ensures we correctly glue FILE* within one CRT used
175  * by the OpenSSL library build to another CRT used by the ab.exe build.
176  * This became especially problematic with Visual Studio 2015.
177  */
178 #include <openssl/applink.c>
179 #endif
180
181 #endif
182
183 #if defined(USE_SSL)
184 #if (OPENSSL_VERSION_NUMBER >= 0x00909000)
185 #define AB_SSL_METHOD_CONST const
186 #else
187 #define AB_SSL_METHOD_CONST
188 #endif
189 #if (OPENSSL_VERSION_NUMBER >= 0x0090707f)
190 #define AB_SSL_CIPHER_CONST const
191 #else
192 #define AB_SSL_CIPHER_CONST
193 #endif
194 #ifdef SSL_OP_NO_TLSv1_2
195 #define HAVE_TLSV1_X
196 #endif
197 #if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_set_tlsext_host_name)
198 #define HAVE_TLSEXT
199 #endif
200 #if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2060000f
201 #define SSL_CTRL_SET_MIN_PROTO_VERSION 123
202 #define SSL_CTRL_SET_MAX_PROTO_VERSION 124
203 #define SSL_CTX_set_min_proto_version(ctx, version) \
204    SSL_CTX_ctrl(ctx, SSL_CTRL_SET_MIN_PROTO_VERSION, version, NULL)
205 #define SSL_CTX_set_max_proto_version(ctx, version) \
206    SSL_CTX_ctrl(ctx, SSL_CTRL_SET_MAX_PROTO_VERSION, version, NULL)
207 #endif
208 #endif
209
210 #include <math.h>
211 #if APR_HAVE_CTYPE_H
212 #include <ctype.h>
213 #endif
214 #if APR_HAVE_LIMITS_H
215 #include <limits.h>
216 #endif
217
218 /* ------------------- DEFINITIONS -------------------------- */
219
220 #ifndef LLONG_MAX
221 #define AB_MAX APR_INT64_C(0x7fffffffffffffff)
222 #else
223 #define AB_MAX LLONG_MAX
224 #endif
225
226 /* maximum number of requests on a time limited test */
227 #define MAX_REQUESTS (INT_MAX > 50000 ? 50000 : INT_MAX)
228
229 /* connection state
230  * don't add enums or rearrange or otherwise change values without
231  * visiting set_conn_state()
232  */
233 typedef enum {
234     STATE_UNCONNECTED = 0,
235     STATE_CONNECTING,           /* TCP connect initiated, but we don't
236                                  * know if it worked yet
237                                  */
238     STATE_CONNECTED,            /* we know TCP connect completed */
239     STATE_READ
240 } connect_state_e;
241
242 #define CBUFFSIZE (8192)
243
244 struct connection {
245     apr_pool_t *ctx;
246     apr_socket_t *aprsock;
247     apr_pollfd_t pollfd;
248     int state;
249     apr_size_t read;            /* amount of bytes read */
250     apr_size_t bread;           /* amount of body read */
251     apr_size_t rwrite, rwrote;  /* keep pointers in what we write - across
252                                  * EAGAINs */
253     apr_size_t length;          /* Content-Length value used for keep-alive */
254     char cbuff[CBUFFSIZE];      /* a buffer to store server response header */
255     int cbx;                    /* offset in cbuffer */
256     int keepalive;              /* non-zero if a keep-alive request */
257     int gotheader;              /* non-zero if we have the entire header in
258                                  * cbuff */
259     apr_time_t start,           /* Start of connection */
260                connect,         /* Connected, start writing */
261                endwrite,        /* Request written */
262                beginread,       /* First byte of input */
263                done;            /* Connection closed */
264
265     int socknum;
266 #ifdef USE_SSL
267     SSL *ssl;
268 #endif
269 };
270
271 struct data {
272     apr_time_t starttime;         /* start time of connection */
273     apr_interval_time_t waittime; /* between request and reading response */
274     apr_interval_time_t ctime;    /* time to connect */
275     apr_interval_time_t time;     /* time for connection */
276 };
277
278 #define ap_min(a,b) (((a)<(b))?(a):(b))
279 #define ap_max(a,b) (((a)>(b))?(a):(b))
280 #define ap_round_ms(a) ((apr_time_t)((a) + 500)/1000)
281 #define ap_double_ms(a) ((double)(a)/1000.0)
282 #define MAX_CONCURRENCY 20000
283
284 /* --------------------- GLOBALS ---------------------------- */
285
286 int verbosity = 0;      /* no verbosity by default */
287 int recverrok = 0;      /* ok to proceed after socket receive errors */
288 enum {NO_METH = 0, GET, HEAD, PUT, POST, CUSTOM_METHOD} method = NO_METH;
289 const char *method_str[] = {"bug", "GET", "HEAD", "PUT", "POST", ""};
290 int send_body = 0;      /* non-zero if sending body with request */
291 int requests = 1;       /* Number of requests to make */
292 int heartbeatres = 100; /* How often do we say we're alive */
293 int concurrency = 1;    /* Number of multiple requests to make */
294 int percentile = 1;     /* Show percentile served */
295 int nolength = 0;       /* Accept variable document length */
296 int confidence = 1;     /* Show confidence estimator and warnings */
297 int tlimit = 0;         /* time limit in secs */
298 int keepalive = 0;      /* try and do keepalive connections */
299 int windowsize = 0;     /* we use the OS default window size */
300 char servername[1024];  /* name that server reports */
301 char *hostname;         /* host name from URL */
302 const char *host_field;       /* value of "Host:" header field */
303 const char *path;             /* path name */
304 char *postdata;         /* *buffer containing data from postfile */
305 apr_size_t postlen = 0; /* length of data to be POSTed */
306 char *content_type = NULL;     /* content type to put in POST header */
307 const char *cookie,           /* optional cookie line */
308            *auth,             /* optional (basic/uuencoded) auhentication */
309            *hdrs;             /* optional arbitrary headers */
310 apr_port_t port;        /* port number */
311 char *proxyhost = NULL; /* proxy host name */
312 int proxyport = 0;      /* proxy port */
313 const char *connecthost;
314 const char *myhost;
315 apr_port_t connectport;
316 const char *gnuplot;          /* GNUplot file */
317 const char *csvperc;          /* CSV Percentile file */
318 const char *fullurl;
319 const char *colonhost;
320 int isproxy = 0;
321 apr_interval_time_t aprtimeout = apr_time_from_sec(30); /* timeout value */
322
323 /* overrides for ab-generated common headers */
324 const char *opt_host;   /* which optional "Host:" header specified, if any */
325 int opt_useragent = 0;  /* was an optional "User-Agent:" header specified? */
326 int opt_accept = 0;     /* was an optional "Accept:" header specified? */
327  /*
328   * XXX - this is now a per read/write transact type of value
329   */
330
331 int use_html = 0;       /* use html in the report */
332 const char *tablestring;
333 const char *trstring;
334 const char *tdstring;
335
336 apr_size_t doclen = 0;     /* the length the document should be */
337 apr_int64_t totalread = 0;    /* total number of bytes read */
338 apr_int64_t totalbread = 0;   /* totoal amount of entity body read */
339 apr_int64_t totalposted = 0;  /* total number of bytes posted, inc. headers */
340 int started = 0;           /* number of requests started, so no excess */
341 int done = 0;              /* number of requests we have done */
342 int doneka = 0;            /* number of keep alive connections done */
343 int good = 0, bad = 0;     /* number of good and bad requests */
344 int epipe = 0;             /* number of broken pipe writes */
345 int err_length = 0;        /* requests failed due to response length */
346 int err_conn = 0;          /* requests failed due to connection drop */
347 int err_recv = 0;          /* requests failed due to broken read */
348 int err_except = 0;        /* requests failed due to exception */
349 int err_response = 0;      /* requests with invalid or non-200 response */
350
351 #ifdef USE_SSL
352 int is_ssl;
353 SSL_CTX *ssl_ctx;
354 char *ssl_cipher = NULL;
355 char *ssl_info = NULL;
356 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
357 char *ssl_tmp_key = NULL;
358 #endif
359 BIO *bio_out,*bio_err;
360 #ifdef HAVE_TLSEXT
361 int tls_use_sni = 1;         /* used by default, -I disables it */
362 const char *tls_sni = NULL; /* 'opt_host' if any, 'hostname' otherwise */
363 #endif
364 #endif
365
366 apr_time_t start, lasttime, stoptime;
367
368 /* global request (and its length) */
369 char _request[8192];
370 char *request = _request;
371 apr_size_t reqlen;
372 int requests_initialized = 0;
373
374 /* one global throw-away buffer to read stuff into */
375 char buffer[8192];
376
377 /* interesting percentiles */
378 int percs[] = {50, 66, 75, 80, 90, 95, 98, 99, 100};
379
380 struct connection *con;     /* connection array */
381 struct data *stats;         /* data for each request */
382 apr_pool_t *cntxt;
383
384 apr_pollset_t *readbits;
385
386 apr_sockaddr_t *mysa;
387 apr_sockaddr_t *destsa;
388
389 #ifdef NOT_ASCII
390 apr_xlate_t *from_ascii, *to_ascii;
391 #endif
392
393 static void write_request(struct connection * c);
394 static void close_connection(struct connection * c);
395
396 /* --------------------------------------------------------- */
397
398 /* simple little function to write an error string and exit */
399
400 static void err(const char *s)
401 {
402     fprintf(stderr, "%s\n", s);
403     if (done)
404         printf("Total of %d requests completed\n" , done);
405     exit(1);
406 }
407
408 /* simple little function to write an APR error string and exit */
409
410 static void apr_err(const char *s, apr_status_t rv)
411 {
412     char buf[120];
413
414     fprintf(stderr,
415         "%s: %s (%d)\n",
416         s, apr_strerror(rv, buf, sizeof buf), rv);
417     if (done)
418         printf("Total of %d requests completed\n" , done);
419     exit(rv);
420 }
421
422 static void *xmalloc(size_t size)
423 {
424     void *ret = malloc(size);
425     if (ret == NULL) {
426         fprintf(stderr, "Could not allocate memory (%"
427                 APR_SIZE_T_FMT" bytes)\n", size);
428         exit(1);
429     }
430     return ret;
431 }
432
433 static void *xcalloc(size_t num, size_t size)
434 {
435     void *ret = calloc(num, size);
436     if (ret == NULL) {
437         fprintf(stderr, "Could not allocate memory (%"
438                 APR_SIZE_T_FMT" bytes)\n", size*num);
439         exit(1);
440     }
441     return ret;
442 }
443
444 static char *xstrdup(const char *s)
445 {
446     char *ret = strdup(s);
447     if (ret == NULL) {
448         fprintf(stderr, "Could not allocate memory (%"
449                 APR_SIZE_T_FMT " bytes)\n", strlen(s));
450         exit(1);
451     }
452     return ret;
453 }
454
455 /*
456  * Similar to standard strstr() but we ignore case in this version.
457  * Copied from ap_strcasestr().
458  */
459 static char *xstrcasestr(const char *s1, const char *s2)
460 {
461     char *p1, *p2;
462     if (*s2 == '\0') {
463         /* an empty s2 */
464         return((char *)s1);
465     }
466     while(1) {
467         for ( ; (*s1 != '\0') && (apr_tolower(*s1) != apr_tolower(*s2)); s1++);
468         if (*s1 == '\0') {
469             return(NULL);
470         }
471         /* found first character of s2, see if the rest matches */
472         p1 = (char *)s1;
473         p2 = (char *)s2;
474         for (++p1, ++p2; apr_tolower(*p1) == apr_tolower(*p2); ++p1, ++p2) {
475             if (*p1 == '\0') {
476                 /* both strings ended together */
477                 return((char *)s1);
478             }
479         }
480         if (*p2 == '\0') {
481             /* second string ended, a match */
482             break;
483         }
484         /* didn't find a match here, try starting at next character in s1 */
485         s1++;
486     }
487     return((char *)s1);
488 }
489
490 /* pool abort function */
491 static int abort_on_oom(int retcode)
492 {
493     fprintf(stderr, "Could not allocate memory\n");
494     exit(1);
495     /* not reached */
496     return retcode;
497 }
498
499 static void set_polled_events(struct connection *c, apr_int16_t new_reqevents)
500 {
501     apr_status_t rv;
502
503     if (c->pollfd.reqevents != new_reqevents) {
504         if (c->pollfd.reqevents != 0) {
505             rv = apr_pollset_remove(readbits, &c->pollfd);
506             if (rv != APR_SUCCESS) {
507                 apr_err("apr_pollset_remove()", rv);
508             }
509         }
510
511         if (new_reqevents != 0) {
512             c->pollfd.reqevents = new_reqevents;
513             rv = apr_pollset_add(readbits, &c->pollfd);
514             if (rv != APR_SUCCESS) {
515                 apr_err("apr_pollset_add()", rv);
516             }
517         }
518     }
519 }
520
521 static void set_conn_state(struct connection *c, connect_state_e new_state)
522 {
523     apr_int16_t events_by_state[] = {
524         0,           /* for STATE_UNCONNECTED */
525         APR_POLLOUT, /* for STATE_CONNECTING */
526         APR_POLLIN,  /* for STATE_CONNECTED; we don't poll in this state,
527                       * so prepare for polling in the following state --
528                       * STATE_READ
529                       */
530         APR_POLLIN   /* for STATE_READ */
531     };
532
533     c->state = new_state;
534
535     set_polled_events(c, events_by_state[new_state]);
536 }
537
538 /* --------------------------------------------------------- */
539 /* write out request to a connection - assumes we can write
540  * (small) request out in one go into our new socket buffer
541  *
542  */
543 #ifdef USE_SSL
544 static long ssl_print_cb(BIO *bio,int cmd,const char *argp,int argi,long argl,long ret)
545 {
546     BIO *out;
547
548     out=(BIO *)BIO_get_callback_arg(bio);
549     if (out == NULL) return(ret);
550
551     if (cmd == (BIO_CB_READ|BIO_CB_RETURN)) {
552         BIO_printf(out,"read from %p [%p] (%d bytes => %ld (0x%lX))\n",
553                    bio, argp, argi, ret, ret);
554         BIO_dump(out,(char *)argp,(int)ret);
555         return(ret);
556     }
557     else if (cmd == (BIO_CB_WRITE|BIO_CB_RETURN)) {
558         BIO_printf(out,"write to %p [%p] (%d bytes => %ld (0x%lX))\n",
559                    bio, argp, argi, ret, ret);
560         BIO_dump(out,(char *)argp,(int)ret);
561     }
562     return ret;
563 }
564
565 static void ssl_state_cb(const SSL *s, int w, int r)
566 {
567     if (w & SSL_CB_ALERT) {
568         BIO_printf(bio_err, "SSL/TLS Alert [%s] %s:%s\n",
569                    (w & SSL_CB_READ ? "read" : "write"),
570                    SSL_alert_type_string_long(r),
571                    SSL_alert_desc_string_long(r));
572     } else if (w & SSL_CB_LOOP) {
573         BIO_printf(bio_err, "SSL/TLS State [%s] %s\n",
574                    (SSL_in_connect_init((SSL*)s) ? "connect" : "-"),
575                    SSL_state_string_long(s));
576     } else if (w & (SSL_CB_HANDSHAKE_START|SSL_CB_HANDSHAKE_DONE)) {
577         BIO_printf(bio_err, "SSL/TLS Handshake [%s] %s\n",
578                    (w & SSL_CB_HANDSHAKE_START ? "Start" : "Done"),
579                    SSL_state_string_long(s));
580     }
581 }
582
583 #ifndef RAND_MAX
584 #define RAND_MAX INT_MAX
585 #endif
586
587 static int ssl_rand_choosenum(int l, int h)
588 {
589     int i;
590     char buf[50];
591
592     srand((unsigned int)time(NULL));
593     apr_snprintf(buf, sizeof(buf), "%.0f",
594                  (((double)(rand()%RAND_MAX)/RAND_MAX)*(h-l)));
595     i = atoi(buf)+1;
596     if (i < l) i = l;
597     if (i > h) i = h;
598     return i;
599 }
600
601 static void ssl_rand_seed(void)
602 {
603     int n, l;
604     time_t t;
605     pid_t pid;
606     unsigned char stackdata[256];
607
608     /*
609      * seed in the current time (usually just 4 bytes)
610      */
611     t = time(NULL);
612     l = sizeof(time_t);
613     RAND_seed((unsigned char *)&t, l);
614
615     /*
616      * seed in the current process id (usually just 4 bytes)
617      */
618     pid = getpid();
619     l = sizeof(pid_t);
620     RAND_seed((unsigned char *)&pid, l);
621
622     /*
623      * seed in some current state of the run-time stack (128 bytes)
624      */
625     n = ssl_rand_choosenum(0, sizeof(stackdata)-128-1);
626     RAND_seed(stackdata+n, 128);
627 }
628
629 static int ssl_print_connection_info(BIO *bio, SSL *ssl)
630 {
631     AB_SSL_CIPHER_CONST SSL_CIPHER *c;
632     int alg_bits,bits;
633
634     BIO_printf(bio,"Transport Protocol      :%s\n", SSL_get_version(ssl));
635
636     c = SSL_get_current_cipher(ssl);
637     BIO_printf(bio,"Cipher Suite Protocol   :%s\n", SSL_CIPHER_get_version(c));
638     BIO_printf(bio,"Cipher Suite Name       :%s\n",SSL_CIPHER_get_name(c));
639
640     bits = SSL_CIPHER_get_bits(c,&alg_bits);
641     BIO_printf(bio,"Cipher Suite Cipher Bits:%d (%d)\n",bits,alg_bits);
642
643     return(1);
644 }
645
646 static void ssl_print_cert_info(BIO *bio, X509 *cert)
647 {
648     X509_NAME *dn;
649     EVP_PKEY *pk;
650     char buf[1024];
651
652     BIO_printf(bio, "Certificate version: %ld\n", X509_get_version(cert)+1);
653     BIO_printf(bio,"Valid from: ");
654     ASN1_UTCTIME_print(bio, X509_get_notBefore(cert));
655     BIO_printf(bio,"\n");
656
657     BIO_printf(bio,"Valid to  : ");
658     ASN1_UTCTIME_print(bio, X509_get_notAfter(cert));
659     BIO_printf(bio,"\n");
660
661     pk = X509_get_pubkey(cert);
662     BIO_printf(bio,"Public key is %d bits\n",
663                EVP_PKEY_bits(pk));
664     EVP_PKEY_free(pk);
665
666     dn = X509_get_issuer_name(cert);
667     X509_NAME_oneline(dn, buf, sizeof(buf));
668     BIO_printf(bio,"The issuer name is %s\n", buf);
669
670     dn=X509_get_subject_name(cert);
671     X509_NAME_oneline(dn, buf, sizeof(buf));
672     BIO_printf(bio,"The subject name is %s\n", buf);
673
674     /* dump the extension list too */
675     BIO_printf(bio, "Extension Count: %d\n", X509_get_ext_count(cert));
676 }
677
678 static void ssl_print_info(struct connection *c)
679 {
680     X509_STACK_TYPE *sk;
681     X509 *cert;
682     int count;
683
684     BIO_printf(bio_err, "\n");
685     sk = SSL_get_peer_cert_chain(c->ssl);
686     if ((count = SK_NUM(sk)) > 0) {
687         int i;
688         for (i=1; i<count; i++) {
689             cert = (X509 *)SK_VALUE(sk, i);
690             ssl_print_cert_info(bio_out, cert);
691     }
692     }
693     cert = SSL_get_peer_certificate(c->ssl);
694     if (cert == NULL) {
695         BIO_printf(bio_out, "Anon DH\n");
696     } else {
697         BIO_printf(bio_out, "Peer certificate\n");
698         ssl_print_cert_info(bio_out, cert);
699         X509_free(cert);
700     }
701     ssl_print_connection_info(bio_err,c->ssl);
702     SSL_SESSION_print(bio_err, SSL_get_session(c->ssl));
703     }
704
705 static void ssl_proceed_handshake(struct connection *c)
706 {
707     int do_next = 1;
708
709     while (do_next) {
710         int ret, ecode;
711
712         ret = SSL_do_handshake(c->ssl);
713         ecode = SSL_get_error(c->ssl, ret);
714
715         switch (ecode) {
716         case SSL_ERROR_NONE:
717             if (verbosity >= 2)
718                 ssl_print_info(c);
719             if (ssl_info == NULL) {
720                 AB_SSL_CIPHER_CONST SSL_CIPHER *ci;
721                 X509 *cert;
722                 int sk_bits, pk_bits, swork;
723
724                 ci = SSL_get_current_cipher(c->ssl);
725                 sk_bits = SSL_CIPHER_get_bits(ci, &swork);
726                 cert = SSL_get_peer_certificate(c->ssl);
727                 if (cert)
728                     pk_bits = EVP_PKEY_bits(X509_get_pubkey(cert));
729                 else
730                     pk_bits = 0;  /* Anon DH */
731
732                 ssl_info = xmalloc(128);
733                 apr_snprintf(ssl_info, 128, "%s,%s,%d,%d",
734                              SSL_get_version(c->ssl),
735                              SSL_CIPHER_get_name(ci),
736                              pk_bits, sk_bits);
737             }
738 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
739             if (ssl_tmp_key == NULL) {
740                 EVP_PKEY *key;
741                 if (SSL_get_server_tmp_key(c->ssl, &key)) {
742                     ssl_tmp_key = xmalloc(128);
743                     switch (EVP_PKEY_id(key)) {
744                     case EVP_PKEY_RSA:
745                         apr_snprintf(ssl_tmp_key, 128, "RSA %d bits",
746                                      EVP_PKEY_bits(key));
747                         break;
748                     case EVP_PKEY_DH:
749                         apr_snprintf(ssl_tmp_key, 128, "DH %d bits",
750                                      EVP_PKEY_bits(key));
751                         break;
752 #ifndef OPENSSL_NO_EC
753                     case EVP_PKEY_EC: {
754                         const char *cname = NULL;
755                         EC_KEY *ec = EVP_PKEY_get1_EC_KEY(key);
756                         int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
757                         EC_KEY_free(ec);
758                         cname = EC_curve_nid2nist(nid);
759                         if (!cname)
760                             cname = OBJ_nid2sn(nid);
761
762                         apr_snprintf(ssl_tmp_key, 128, "ECDH %s %d bits",
763                                      cname,
764                                      EVP_PKEY_bits(key));
765                         break;
766                         }
767 #endif
768                     default:
769                         apr_snprintf(ssl_tmp_key, 128, "%s %d bits",
770                                      OBJ_nid2sn(EVP_PKEY_id(key)),
771                                      EVP_PKEY_bits(key));
772                         break;
773                     }
774                     EVP_PKEY_free(key);
775                 }
776             }
777 #endif
778             write_request(c);
779             do_next = 0;
780             break;
781         case SSL_ERROR_WANT_READ:
782             set_polled_events(c, APR_POLLIN);
783             do_next = 0;
784             break;
785         case SSL_ERROR_WANT_WRITE:
786             set_polled_events(c, APR_POLLOUT);
787             do_next = 0;
788             break;
789         case SSL_ERROR_WANT_CONNECT:
790         case SSL_ERROR_SSL:
791         case SSL_ERROR_SYSCALL:
792             /* Unexpected result */
793             BIO_printf(bio_err, "SSL handshake failed (%d).\n", ecode);
794             ERR_print_errors(bio_err);
795             close_connection(c);
796             do_next = 0;
797             break;
798         }
799     }
800 }
801
802 #endif /* USE_SSL */
803
804 static void write_request(struct connection * c)
805 {
806     if (started >= requests) {
807         return;
808     }
809
810     do {
811         apr_time_t tnow;
812         apr_size_t l = c->rwrite;
813         apr_status_t e = APR_SUCCESS; /* prevent gcc warning */
814
815         tnow = lasttime = apr_time_now();
816
817         /*
818          * First time round ?
819          */
820         if (c->rwrite == 0) {
821             apr_socket_timeout_set(c->aprsock, 0);
822             c->connect = tnow;
823             c->rwrote = 0;
824             c->rwrite = reqlen;
825             if (send_body)
826                 c->rwrite += postlen;
827             l = c->rwrite;
828         }
829         else if (tnow > c->connect + aprtimeout) {
830             printf("Send request timed out!\n");
831             close_connection(c);
832             return;
833         }
834
835 #ifdef USE_SSL
836         if (c->ssl) {
837             e = SSL_write(c->ssl, request + c->rwrote, l);
838             if (e <= 0) {
839                 switch (SSL_get_error(c->ssl, e)) {
840                 case SSL_ERROR_WANT_READ:
841                     set_polled_events(c, APR_POLLIN);
842                     break;
843                 case SSL_ERROR_WANT_WRITE:
844                     set_polled_events(c, APR_POLLOUT);
845                     break;
846                 default:
847                     BIO_printf(bio_err, "SSL write failed - closing connection\n");
848                     ERR_print_errors(bio_err);
849                     close_connection (c);
850                     break;
851                 }
852                 return;
853             }
854             l = e;
855         }
856         else
857 #endif
858         {
859             e = apr_socket_send(c->aprsock, request + c->rwrote, &l);
860             if (e != APR_SUCCESS && !l) {
861                 if (!APR_STATUS_IS_EAGAIN(e)) {
862                     epipe++;
863                     printf("Send request failed!\n");
864                     close_connection(c);
865                 }
866                 else {
867                     set_polled_events(c, APR_POLLOUT);
868                 }
869                 return;
870             }
871         }
872         totalposted += l;
873         c->rwrote += l;
874         c->rwrite -= l;
875     } while (c->rwrite);
876
877     c->endwrite = lasttime = apr_time_now();
878     started++;
879     set_conn_state(c, STATE_READ);
880 }
881
882 /* --------------------------------------------------------- */
883
884 /* calculate and output results */
885
886 static int compradre(struct data * a, struct data * b)
887 {
888     if ((a->ctime) < (b->ctime))
889         return -1;
890     if ((a->ctime) > (b->ctime))
891         return +1;
892     return 0;
893 }
894
895 static int comprando(struct data * a, struct data * b)
896 {
897     if ((a->time) < (b->time))
898         return -1;
899     if ((a->time) > (b->time))
900         return +1;
901     return 0;
902 }
903
904 static int compri(struct data * a, struct data * b)
905 {
906     apr_interval_time_t p = a->time - a->ctime;
907     apr_interval_time_t q = b->time - b->ctime;
908     if (p < q)
909         return -1;
910     if (p > q)
911         return +1;
912     return 0;
913 }
914
915 static int compwait(struct data * a, struct data * b)
916 {
917     if ((a->waittime) < (b->waittime))
918         return -1;
919     if ((a->waittime) > (b->waittime))
920         return 1;
921     return 0;
922 }
923
924 static void output_results(int sig)
925 {
926     double timetaken;
927
928     if (sig) {
929         lasttime = apr_time_now();  /* record final time if interrupted */
930     }
931     timetaken = (double) (lasttime - start) / APR_USEC_PER_SEC;
932
933     printf("\n\n");
934     printf("Server Software:        %s\n", servername);
935     printf("Server Hostname:        %s\n", hostname);
936     printf("Server Port:            %hu\n", port);
937 #ifdef USE_SSL
938     if (is_ssl && ssl_info) {
939         printf("SSL/TLS Protocol:       %s\n", ssl_info);
940     }
941 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
942     if (is_ssl && ssl_tmp_key) {
943         printf("Server Temp Key:        %s\n", ssl_tmp_key);
944     }
945 #endif
946 #ifdef HAVE_TLSEXT
947     if (is_ssl && tls_sni) {
948         printf("TLS Server Name:        %s\n", tls_sni);
949     }
950 #endif
951 #endif
952     printf("\n");
953     printf("Document Path:          %s\n", path);
954     if (nolength)
955         printf("Document Length:        Variable\n");
956     else
957         printf("Document Length:        %" APR_SIZE_T_FMT " bytes\n", doclen);
958     printf("\n");
959     printf("Concurrency Level:      %d\n", concurrency);
960     printf("Time taken for tests:   %.3f seconds\n", timetaken);
961     printf("Complete requests:      %d\n", done);
962     printf("Failed requests:        %d\n", bad);
963     if (bad)
964         printf("   (Connect: %d, Receive: %d, Length: %d, Exceptions: %d)\n",
965             err_conn, err_recv, err_length, err_except);
966     if (epipe)
967         printf("Write errors:           %d\n", epipe);
968     if (err_response)
969         printf("Non-2xx responses:      %d\n", err_response);
970     if (keepalive)
971         printf("Keep-Alive requests:    %d\n", doneka);
972     printf("Total transferred:      %" APR_INT64_T_FMT " bytes\n", totalread);
973     if (send_body)
974         printf("Total body sent:        %" APR_INT64_T_FMT "\n",
975                totalposted);
976     printf("HTML transferred:       %" APR_INT64_T_FMT " bytes\n", totalbread);
977
978     /* avoid divide by zero */
979     if (timetaken && done) {
980         printf("Requests per second:    %.2f [#/sec] (mean)\n",
981                (double) done / timetaken);
982         printf("Time per request:       %.3f [ms] (mean)\n",
983                (double) concurrency * timetaken * 1000 / done);
984         printf("Time per request:       %.3f [ms] (mean, across all concurrent requests)\n",
985                (double) timetaken * 1000 / done);
986         printf("Transfer rate:          %.2f [Kbytes/sec] received\n",
987                (double) totalread / 1024 / timetaken);
988         if (send_body) {
989             printf("                        %.2f kb/s sent\n",
990                (double) totalposted / 1024 / timetaken);
991             printf("                        %.2f kb/s total\n",
992                (double) (totalread + totalposted) / 1024 / timetaken);
993         }
994     }
995
996     if (done > 0) {
997         /* work out connection times */
998         int i;
999         apr_time_t totalcon = 0, total = 0, totald = 0, totalwait = 0;
1000         apr_time_t meancon, meantot, meand, meanwait;
1001         apr_interval_time_t mincon = AB_MAX, mintot = AB_MAX, mind = AB_MAX,
1002                             minwait = AB_MAX;
1003         apr_interval_time_t maxcon = 0, maxtot = 0, maxd = 0, maxwait = 0;
1004         apr_interval_time_t mediancon = 0, mediantot = 0, mediand = 0, medianwait = 0;
1005         double sdtot = 0, sdcon = 0, sdd = 0, sdwait = 0;
1006
1007         for (i = 0; i < done; i++) {
1008             struct data *s = &stats[i];
1009             mincon = ap_min(mincon, s->ctime);
1010             mintot = ap_min(mintot, s->time);
1011             mind = ap_min(mind, s->time - s->ctime);
1012             minwait = ap_min(minwait, s->waittime);
1013
1014             maxcon = ap_max(maxcon, s->ctime);
1015             maxtot = ap_max(maxtot, s->time);
1016             maxd = ap_max(maxd, s->time - s->ctime);
1017             maxwait = ap_max(maxwait, s->waittime);
1018
1019             totalcon += s->ctime;
1020             total += s->time;
1021             totald += s->time - s->ctime;
1022             totalwait += s->waittime;
1023         }
1024         meancon = totalcon / done;
1025         meantot = total / done;
1026         meand = totald / done;
1027         meanwait = totalwait / done;
1028
1029         /* calculating the sample variance: the sum of the squared deviations, divided by n-1 */
1030         for (i = 0; i < done; i++) {
1031             struct data *s = &stats[i];
1032             double a;
1033             a = ((double)s->time - meantot);
1034             sdtot += a * a;
1035             a = ((double)s->ctime - meancon);
1036             sdcon += a * a;
1037             a = ((double)s->time - (double)s->ctime - meand);
1038             sdd += a * a;
1039             a = ((double)s->waittime - meanwait);
1040             sdwait += a * a;
1041         }
1042
1043         sdtot = (done > 1) ? sqrt(sdtot / (done - 1)) : 0;
1044         sdcon = (done > 1) ? sqrt(sdcon / (done - 1)) : 0;
1045         sdd = (done > 1) ? sqrt(sdd / (done - 1)) : 0;
1046         sdwait = (done > 1) ? sqrt(sdwait / (done - 1)) : 0;
1047
1048         /*
1049          * XXX: what is better; this hideous cast of the compradre function; or
1050          * the four warnings during compile ? dirkx just does not know and
1051          * hates both/
1052          */
1053         qsort(stats, done, sizeof(struct data),
1054               (int (*) (const void *, const void *)) compradre);
1055         if ((done > 1) && (done % 2))
1056             mediancon = (stats[done / 2].ctime + stats[done / 2 + 1].ctime) / 2;
1057         else
1058             mediancon = stats[done / 2].ctime;
1059
1060         qsort(stats, done, sizeof(struct data),
1061               (int (*) (const void *, const void *)) compri);
1062         if ((done > 1) && (done % 2))
1063             mediand = (stats[done / 2].time + stats[done / 2 + 1].time \
1064             -stats[done / 2].ctime - stats[done / 2 + 1].ctime) / 2;
1065         else
1066             mediand = stats[done / 2].time - stats[done / 2].ctime;
1067
1068         qsort(stats, done, sizeof(struct data),
1069               (int (*) (const void *, const void *)) compwait);
1070         if ((done > 1) && (done % 2))
1071             medianwait = (stats[done / 2].waittime + stats[done / 2 + 1].waittime) / 2;
1072         else
1073             medianwait = stats[done / 2].waittime;
1074
1075         qsort(stats, done, sizeof(struct data),
1076               (int (*) (const void *, const void *)) comprando);
1077         if ((done > 1) && (done % 2))
1078             mediantot = (stats[done / 2].time + stats[done / 2 + 1].time) / 2;
1079         else
1080             mediantot = stats[done / 2].time;
1081
1082         printf("\nConnection Times (ms)\n");
1083         /*
1084          * Reduce stats from apr time to milliseconds
1085          */
1086         mincon     = ap_round_ms(mincon);
1087         mind       = ap_round_ms(mind);
1088         minwait    = ap_round_ms(minwait);
1089         mintot     = ap_round_ms(mintot);
1090         meancon    = ap_round_ms(meancon);
1091         meand      = ap_round_ms(meand);
1092         meanwait   = ap_round_ms(meanwait);
1093         meantot    = ap_round_ms(meantot);
1094         mediancon  = ap_round_ms(mediancon);
1095         mediand    = ap_round_ms(mediand);
1096         medianwait = ap_round_ms(medianwait);
1097         mediantot  = ap_round_ms(mediantot);
1098         maxcon     = ap_round_ms(maxcon);
1099         maxd       = ap_round_ms(maxd);
1100         maxwait    = ap_round_ms(maxwait);
1101         maxtot     = ap_round_ms(maxtot);
1102         sdcon      = ap_double_ms(sdcon);
1103         sdd        = ap_double_ms(sdd);
1104         sdwait     = ap_double_ms(sdwait);
1105         sdtot      = ap_double_ms(sdtot);
1106
1107         if (confidence) {
1108 #define CONF_FMT_STRING "%5" APR_TIME_T_FMT " %4" APR_TIME_T_FMT " %5.1f %6" APR_TIME_T_FMT " %7" APR_TIME_T_FMT "\n"
1109             printf("              min  mean[+/-sd] median   max\n");
1110             printf("Connect:    " CONF_FMT_STRING,
1111                    mincon, meancon, sdcon, mediancon, maxcon);
1112             printf("Processing: " CONF_FMT_STRING,
1113                    mind, meand, sdd, mediand, maxd);
1114             printf("Waiting:    " CONF_FMT_STRING,
1115                    minwait, meanwait, sdwait, medianwait, maxwait);
1116             printf("Total:      " CONF_FMT_STRING,
1117                    mintot, meantot, sdtot, mediantot, maxtot);
1118 #undef CONF_FMT_STRING
1119
1120 #define     SANE(what,mean,median,sd) \
1121               { \
1122                 double d = (double)mean - median; \
1123                 if (d < 0) d = -d; \
1124                 if (d > 2 * sd ) \
1125                     printf("ERROR: The median and mean for " what " are more than twice the standard\n" \
1126                            "       deviation apart. These results are NOT reliable.\n"); \
1127                 else if (d > sd ) \
1128                     printf("WARNING: The median and mean for " what " are not within a normal deviation\n" \
1129                            "        These results are probably not that reliable.\n"); \
1130             }
1131             SANE("the initial connection time", meancon, mediancon, sdcon);
1132             SANE("the processing time", meand, mediand, sdd);
1133             SANE("the waiting time", meanwait, medianwait, sdwait);
1134             SANE("the total time", meantot, mediantot, sdtot);
1135         }
1136         else {
1137             printf("              min   avg   max\n");
1138 #define CONF_FMT_STRING "%5" APR_TIME_T_FMT " %5" APR_TIME_T_FMT "%5" APR_TIME_T_FMT "\n"
1139             printf("Connect:    " CONF_FMT_STRING, mincon, meancon, maxcon);
1140             printf("Processing: " CONF_FMT_STRING, mind, meand, maxd);
1141             printf("Waiting:    " CONF_FMT_STRING, minwait, meanwait, maxwait);
1142             printf("Total:      " CONF_FMT_STRING, mintot, meantot, maxtot);
1143 #undef CONF_FMT_STRING
1144         }
1145
1146
1147         /* Sorted on total connect times */
1148         if (percentile && (done > 1)) {
1149             printf("\nPercentage of the requests served within a certain time (ms)\n");
1150             for (i = 0; i < sizeof(percs) / sizeof(int); i++) {
1151                 if (percs[i] <= 0)
1152                     printf(" 0%%  <0> (never)\n");
1153                 else if (percs[i] >= 100)
1154                     printf(" 100%%  %5" APR_TIME_T_FMT " (longest request)\n",
1155                            ap_round_ms(stats[done - 1].time));
1156                 else
1157                     printf("  %d%%  %5" APR_TIME_T_FMT "\n", percs[i],
1158                            ap_round_ms(stats[(unsigned long)done * percs[i] / 100].time));
1159             }
1160         }
1161         if (csvperc) {
1162             FILE *out = fopen(csvperc, "w");
1163             if (!out) {
1164                 perror("Cannot open CSV output file");
1165                 exit(1);
1166             }
1167             fprintf(out, "" "Percentage served" "," "Time in ms" "\n");
1168             for (i = 0; i <= 100; i++) {
1169                 double t;
1170                 if (i == 0)
1171                     t = ap_double_ms(stats[0].time);
1172                 else if (i == 100)
1173                     t = ap_double_ms(stats[done - 1].time);
1174                 else
1175                     t = ap_double_ms(stats[(unsigned long) (0.5 + (double)done * i / 100.0)].time);
1176                 fprintf(out, "%d,%.3f\n", i, t);
1177             }
1178             fclose(out);
1179         }
1180         if (gnuplot) {
1181             FILE *out = fopen(gnuplot, "w");
1182             char tmstring[APR_CTIME_LEN];
1183             if (!out) {
1184                 perror("Cannot open gnuplot output file");
1185                 exit(1);
1186             }
1187             fprintf(out, "starttime\tseconds\tctime\tdtime\tttime\twait\n");
1188             for (i = 0; i < done; i++) {
1189                 (void) apr_ctime(tmstring, stats[i].starttime);
1190                 fprintf(out, "%s\t%" APR_TIME_T_FMT "\t%" APR_TIME_T_FMT
1191                                "\t%" APR_TIME_T_FMT "\t%" APR_TIME_T_FMT
1192                                "\t%" APR_TIME_T_FMT "\n", tmstring,
1193                         apr_time_sec(stats[i].starttime),
1194                         ap_round_ms(stats[i].ctime),
1195                         ap_round_ms(stats[i].time - stats[i].ctime),
1196                         ap_round_ms(stats[i].time),
1197                         ap_round_ms(stats[i].waittime));
1198             }
1199             fclose(out);
1200         }
1201     }
1202
1203     if (sig) {
1204         exit(1);
1205     }
1206 }
1207
1208 /* --------------------------------------------------------- */
1209
1210 /* calculate and output results in HTML  */
1211
1212 static void output_html_results(void)
1213 {
1214     double timetaken = (double) (lasttime - start) / APR_USEC_PER_SEC;
1215
1216     printf("\n\n<table %s>\n", tablestring);
1217     printf("<tr %s><th colspan=2 %s>Server Software:</th>"
1218        "<td colspan=2 %s>%s</td></tr>\n",
1219        trstring, tdstring, tdstring, servername);
1220     printf("<tr %s><th colspan=2 %s>Server Hostname:</th>"
1221        "<td colspan=2 %s>%s</td></tr>\n",
1222        trstring, tdstring, tdstring, hostname);
1223     printf("<tr %s><th colspan=2 %s>Server Port:</th>"
1224        "<td colspan=2 %s>%hu</td></tr>\n",
1225        trstring, tdstring, tdstring, port);
1226     printf("<tr %s><th colspan=2 %s>Document Path:</th>"
1227        "<td colspan=2 %s>%s</td></tr>\n",
1228        trstring, tdstring, tdstring, path);
1229     if (nolength)
1230         printf("<tr %s><th colspan=2 %s>Document Length:</th>"
1231             "<td colspan=2 %s>Variable</td></tr>\n",
1232             trstring, tdstring, tdstring);
1233     else
1234         printf("<tr %s><th colspan=2 %s>Document Length:</th>"
1235             "<td colspan=2 %s>%" APR_SIZE_T_FMT " bytes</td></tr>\n",
1236             trstring, tdstring, tdstring, doclen);
1237     printf("<tr %s><th colspan=2 %s>Concurrency Level:</th>"
1238        "<td colspan=2 %s>%d</td></tr>\n",
1239        trstring, tdstring, tdstring, concurrency);
1240     printf("<tr %s><th colspan=2 %s>Time taken for tests:</th>"
1241        "<td colspan=2 %s>%.3f seconds</td></tr>\n",
1242        trstring, tdstring, tdstring, timetaken);
1243     printf("<tr %s><th colspan=2 %s>Complete requests:</th>"
1244        "<td colspan=2 %s>%d</td></tr>\n",
1245        trstring, tdstring, tdstring, done);
1246     printf("<tr %s><th colspan=2 %s>Failed requests:</th>"
1247        "<td colspan=2 %s>%d</td></tr>\n",
1248        trstring, tdstring, tdstring, bad);
1249     if (bad)
1250         printf("<tr %s><td colspan=4 %s >   (Connect: %d, Length: %d, Exceptions: %d)</td></tr>\n",
1251            trstring, tdstring, err_conn, err_length, err_except);
1252     if (err_response)
1253         printf("<tr %s><th colspan=2 %s>Non-2xx responses:</th>"
1254            "<td colspan=2 %s>%d</td></tr>\n",
1255            trstring, tdstring, tdstring, err_response);
1256     if (keepalive)
1257         printf("<tr %s><th colspan=2 %s>Keep-Alive requests:</th>"
1258            "<td colspan=2 %s>%d</td></tr>\n",
1259            trstring, tdstring, tdstring, doneka);
1260     printf("<tr %s><th colspan=2 %s>Total transferred:</th>"
1261        "<td colspan=2 %s>%" APR_INT64_T_FMT " bytes</td></tr>\n",
1262        trstring, tdstring, tdstring, totalread);
1263     if (send_body)
1264         printf("<tr %s><th colspan=2 %s>Total body sent:</th>"
1265            "<td colspan=2 %s>%" APR_INT64_T_FMT "</td></tr>\n",
1266            trstring, tdstring,
1267            tdstring, totalposted);
1268     printf("<tr %s><th colspan=2 %s>HTML transferred:</th>"
1269        "<td colspan=2 %s>%" APR_INT64_T_FMT " bytes</td></tr>\n",
1270        trstring, tdstring, tdstring, totalbread);
1271
1272     /* avoid divide by zero */
1273     if (timetaken) {
1274         printf("<tr %s><th colspan=2 %s>Requests per second:</th>"
1275            "<td colspan=2 %s>%.2f</td></tr>\n",
1276            trstring, tdstring, tdstring, (double) done / timetaken);
1277         printf("<tr %s><th colspan=2 %s>Transfer rate:</th>"
1278            "<td colspan=2 %s>%.2f kb/s received</td></tr>\n",
1279            trstring, tdstring, tdstring, (double) totalread / 1024 / timetaken);
1280         if (send_body) {
1281             printf("<tr %s><td colspan=2 %s>&nbsp;</td>"
1282                "<td colspan=2 %s>%.2f kb/s sent</td></tr>\n",
1283                trstring, tdstring, tdstring,
1284                (double) totalposted / 1024 / timetaken);
1285             printf("<tr %s><td colspan=2 %s>&nbsp;</td>"
1286                "<td colspan=2 %s>%.2f kb/s total</td></tr>\n",
1287                trstring, tdstring, tdstring,
1288                (double) (totalread + totalposted) / 1024 / timetaken);
1289         }
1290     }
1291     {
1292         /* work out connection times */
1293         int i;
1294         apr_interval_time_t totalcon = 0, total = 0;
1295         apr_interval_time_t mincon = AB_MAX, mintot = AB_MAX;
1296         apr_interval_time_t maxcon = 0, maxtot = 0;
1297
1298         for (i = 0; i < done; i++) {
1299             struct data *s = &stats[i];
1300             mincon = ap_min(mincon, s->ctime);
1301             mintot = ap_min(mintot, s->time);
1302             maxcon = ap_max(maxcon, s->ctime);
1303             maxtot = ap_max(maxtot, s->time);
1304             totalcon += s->ctime;
1305             total    += s->time;
1306         }
1307         /*
1308          * Reduce stats from apr time to milliseconds
1309          */
1310         mincon   = ap_round_ms(mincon);
1311         mintot   = ap_round_ms(mintot);
1312         maxcon   = ap_round_ms(maxcon);
1313         maxtot   = ap_round_ms(maxtot);
1314         totalcon = ap_round_ms(totalcon);
1315         total    = ap_round_ms(total);
1316
1317         if (done > 0) { /* avoid division by zero (if 0 done) */
1318             printf("<tr %s><th %s colspan=4>Connnection Times (ms)</th></tr>\n",
1319                trstring, tdstring);
1320             printf("<tr %s><th %s>&nbsp;</th> <th %s>min</th>   <th %s>avg</th>   <th %s>max</th></tr>\n",
1321                trstring, tdstring, tdstring, tdstring, tdstring);
1322             printf("<tr %s><th %s>Connect:</th>"
1323                "<td %s>%5" APR_TIME_T_FMT "</td>"
1324                "<td %s>%5" APR_TIME_T_FMT "</td>"
1325                "<td %s>%5" APR_TIME_T_FMT "</td></tr>\n",
1326                trstring, tdstring, tdstring, mincon, tdstring, totalcon / done, tdstring, maxcon);
1327             printf("<tr %s><th %s>Processing:</th>"
1328                "<td %s>%5" APR_TIME_T_FMT "</td>"
1329                "<td %s>%5" APR_TIME_T_FMT "</td>"
1330                "<td %s>%5" APR_TIME_T_FMT "</td></tr>\n",
1331                trstring, tdstring, tdstring, mintot - mincon, tdstring,
1332                (total / done) - (totalcon / done), tdstring, maxtot - maxcon);
1333             printf("<tr %s><th %s>Total:</th>"
1334                "<td %s>%5" APR_TIME_T_FMT "</td>"
1335                "<td %s>%5" APR_TIME_T_FMT "</td>"
1336                "<td %s>%5" APR_TIME_T_FMT "</td></tr>\n",
1337                trstring, tdstring, tdstring, mintot, tdstring, total / done, tdstring, maxtot);
1338         }
1339         printf("</table>\n");
1340     }
1341 }
1342
1343 /* --------------------------------------------------------- */
1344
1345 /* start asnchronous non-blocking connection */
1346
1347 static void start_connect(struct connection * c)
1348 {
1349     apr_status_t rv;
1350
1351     if (!(started < requests))
1352         return;
1353
1354     c->read = 0;
1355     c->bread = 0;
1356     c->keepalive = 0;
1357     c->cbx = 0;
1358     c->gotheader = 0;
1359     c->rwrite = 0;
1360     if (c->ctx)
1361         apr_pool_clear(c->ctx);
1362     else
1363         apr_pool_create(&c->ctx, cntxt);
1364
1365     if ((rv = apr_socket_create(&c->aprsock, destsa->family,
1366                 SOCK_STREAM, 0, c->ctx)) != APR_SUCCESS) {
1367     apr_err("socket", rv);
1368     }
1369
1370     if (myhost) {
1371         if ((rv = apr_socket_bind(c->aprsock, mysa)) != APR_SUCCESS) {
1372             apr_err("bind", rv);
1373         }
1374     }
1375
1376     c->pollfd.desc_type = APR_POLL_SOCKET;
1377     c->pollfd.desc.s = c->aprsock;
1378     c->pollfd.reqevents = 0;
1379     c->pollfd.client_data = c;
1380
1381     if ((rv = apr_socket_opt_set(c->aprsock, APR_SO_NONBLOCK, 1))
1382          != APR_SUCCESS) {
1383         apr_err("socket nonblock", rv);
1384     }
1385
1386     if (windowsize != 0) {
1387         rv = apr_socket_opt_set(c->aprsock, APR_SO_SNDBUF,
1388                                 windowsize);
1389         if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
1390             apr_err("socket send buffer", rv);
1391         }
1392         rv = apr_socket_opt_set(c->aprsock, APR_SO_RCVBUF,
1393                                 windowsize);
1394         if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
1395             apr_err("socket receive buffer", rv);
1396         }
1397     }
1398
1399     c->start = lasttime = apr_time_now();
1400 #ifdef USE_SSL
1401     if (is_ssl) {
1402         BIO *bio;
1403         apr_os_sock_t fd;
1404
1405         if ((c->ssl = SSL_new(ssl_ctx)) == NULL) {
1406             BIO_printf(bio_err, "SSL_new failed.\n");
1407             ERR_print_errors(bio_err);
1408             exit(1);
1409         }
1410         ssl_rand_seed();
1411         apr_os_sock_get(&fd, c->aprsock);
1412         bio = BIO_new_socket(fd, BIO_NOCLOSE);
1413         BIO_set_nbio(bio, 1);
1414         SSL_set_bio(c->ssl, bio, bio);
1415         SSL_set_connect_state(c->ssl);
1416         if (verbosity >= 4) {
1417             BIO_set_callback(bio, ssl_print_cb);
1418             BIO_set_callback_arg(bio, (void *)bio_err);
1419         }
1420 #ifdef HAVE_TLSEXT
1421         if (tls_sni) {
1422             SSL_set_tlsext_host_name(c->ssl, tls_sni);
1423         }
1424 #endif
1425     } else {
1426         c->ssl = NULL;
1427     }
1428 #endif
1429     if ((rv = apr_socket_connect(c->aprsock, destsa)) != APR_SUCCESS) {
1430         if (APR_STATUS_IS_EINPROGRESS(rv)) {
1431             set_conn_state(c, STATE_CONNECTING);
1432             c->rwrite = 0;
1433             return;
1434         }
1435         else {
1436             set_conn_state(c, STATE_UNCONNECTED);
1437             apr_socket_close(c->aprsock);
1438             if (good == 0 && destsa->next) {
1439                 destsa = destsa->next;
1440                 err_conn = 0;
1441             }
1442             else if (bad++ > 10) {
1443                 fprintf(stderr,
1444                    "\nTest aborted after 10 failures\n\n");
1445                 apr_err("apr_socket_connect()", rv);
1446             }
1447             else {
1448                 err_conn++;
1449             }
1450
1451             start_connect(c);
1452             return;
1453         }
1454     }
1455
1456     /* connected first time */
1457     set_conn_state(c, STATE_CONNECTED);
1458 #ifdef USE_SSL
1459     if (c->ssl) {
1460         ssl_proceed_handshake(c);
1461     } else
1462 #endif
1463     {
1464         write_request(c);
1465     }
1466 }
1467
1468 /* --------------------------------------------------------- */
1469
1470 /* close down connection and save stats */
1471
1472 static void close_connection(struct connection * c)
1473 {
1474     if (c->read == 0 && c->keepalive) {
1475         /*
1476          * server has legitimately shut down an idle keep alive request
1477          */
1478         if (good)
1479             good--;     /* connection never happened */
1480     }
1481     else {
1482         if (good == 1) {
1483             /* first time here */
1484             doclen = c->bread;
1485         }
1486         else if ((c->bread != doclen) && !nolength) {
1487             bad++;
1488             err_length++;
1489         }
1490         /* save out time */
1491         if (done < requests) {
1492             struct data *s = &stats[done++];
1493             c->done      = lasttime = apr_time_now();
1494             s->starttime = c->start;
1495             s->ctime     = ap_max(0, c->connect - c->start);
1496             s->time      = ap_max(0, c->done - c->start);
1497             s->waittime  = ap_max(0, c->beginread - c->endwrite);
1498             if (heartbeatres && !(done % heartbeatres)) {
1499                 fprintf(stderr, "Completed %d requests\n", done);
1500                 fflush(stderr);
1501             }
1502         }
1503     }
1504
1505     set_conn_state(c, STATE_UNCONNECTED);
1506 #ifdef USE_SSL
1507     if (c->ssl) {
1508         SSL_shutdown(c->ssl);
1509         SSL_free(c->ssl);
1510         c->ssl = NULL;
1511     }
1512 #endif
1513     apr_socket_close(c->aprsock);
1514
1515     /* connect again */
1516     start_connect(c);
1517     return;
1518 }
1519
1520 /* --------------------------------------------------------- */
1521
1522 /* read data from connection */
1523
1524 static void read_connection(struct connection * c)
1525 {
1526     apr_size_t r;
1527     apr_status_t status;
1528     char *part;
1529     char respcode[4];       /* 3 digits and null */
1530     int i;
1531
1532     r = sizeof(buffer);
1533 read_more:
1534 #ifdef USE_SSL
1535     if (c->ssl) {
1536         status = SSL_read(c->ssl, buffer, r);
1537         if (status <= 0) {
1538             int scode = SSL_get_error(c->ssl, status);
1539
1540             if (scode == SSL_ERROR_ZERO_RETURN) {
1541                 /* connection closed cleanly: */
1542                 good++;
1543                 close_connection(c);
1544             }
1545             else if (scode == SSL_ERROR_SYSCALL
1546                      && status == 0
1547                      && c->read != 0) {
1548                 /* connection closed, but in violation of the protocol, after
1549                  * some data has already been read; this commonly happens, so
1550                  * let the length check catch any response errors
1551                  */
1552                 good++;
1553                 close_connection(c);
1554             }
1555             else if (scode == SSL_ERROR_SYSCALL 
1556                      && c->read == 0
1557                      && destsa->next
1558                      && c->state == STATE_CONNECTING
1559                      && good == 0) {
1560                 return;
1561             }
1562             else if (scode == SSL_ERROR_WANT_READ) {
1563                 set_polled_events(c, APR_POLLIN);
1564             }
1565             else if (scode == SSL_ERROR_WANT_WRITE) {
1566                 set_polled_events(c, APR_POLLOUT);
1567             }
1568             else {
1569                 /* some fatal error: */
1570                 c->read = 0;
1571                 BIO_printf(bio_err, "SSL read failed (%d) - closing connection\n", scode);
1572                 ERR_print_errors(bio_err);
1573                 close_connection(c);
1574             }
1575             return;
1576         }
1577         r = status;
1578     }
1579     else
1580 #endif
1581     {
1582         status = apr_socket_recv(c->aprsock, buffer, &r);
1583         if (APR_STATUS_IS_EAGAIN(status))
1584             return;
1585         else if (r == 0 && APR_STATUS_IS_EOF(status)) {
1586             good++;
1587             close_connection(c);
1588             return;
1589         }
1590         /* catch legitimate fatal apr_socket_recv errors */
1591         else if (status != APR_SUCCESS) {
1592             if (recverrok) {
1593                 err_recv++;
1594                 bad++;
1595                 close_connection(c);
1596                 if (verbosity >= 1) {
1597                     char buf[120];
1598                     fprintf(stderr,"%s: %s (%d)\n", "apr_socket_recv", apr_strerror(status, buf, sizeof buf), status);
1599                 }
1600                 return;
1601             } else if (destsa->next && c->state == STATE_CONNECTING
1602                        && c->read == 0 && good == 0) {
1603                 return;
1604             }
1605             else {
1606                 err_recv++;
1607                 apr_err("apr_socket_recv", status);
1608             }
1609         }
1610     }
1611
1612     totalread += r;
1613     if (c->read == 0) {
1614         c->beginread = apr_time_now();
1615     }
1616     c->read += r;
1617
1618
1619     if (!c->gotheader) {
1620         char *s;
1621         int l = 4;
1622         apr_size_t space = CBUFFSIZE - c->cbx - 1; /* -1 allows for \0 term */
1623         int tocopy = (space < r) ? space : r;
1624 #ifdef NOT_ASCII
1625         apr_size_t inbytes_left = space, outbytes_left = space;
1626
1627         status = apr_xlate_conv_buffer(from_ascii, buffer, &inbytes_left,
1628                            c->cbuff + c->cbx, &outbytes_left);
1629         if (status || inbytes_left || outbytes_left) {
1630             fprintf(stderr, "only simple translation is supported (%d/%" APR_SIZE_T_FMT
1631                             "/%" APR_SIZE_T_FMT ")\n", status, inbytes_left, outbytes_left);
1632             exit(1);
1633         }
1634 #else
1635         memcpy(c->cbuff + c->cbx, buffer, space);
1636 #endif              /* NOT_ASCII */
1637         c->cbx += tocopy;
1638         space -= tocopy;
1639         c->cbuff[c->cbx] = 0;   /* terminate for benefit of strstr */
1640         if (verbosity >= 2) {
1641             printf("LOG: header received:\n%s\n", c->cbuff);
1642         }
1643         s = strstr(c->cbuff, "\r\n\r\n");
1644         /*
1645          * this next line is so that we talk to NCSA 1.5 which blatantly
1646          * breaks the http specifaction
1647          */
1648         if (!s) {
1649             s = strstr(c->cbuff, "\n\n");
1650             l = 2;
1651         }
1652
1653         if (!s) {
1654             /* read rest next time */
1655             if (space) {
1656                 return;
1657             }
1658             else {
1659             /* header is in invalid or too big - close connection */
1660                 set_conn_state(c, STATE_UNCONNECTED);
1661                 apr_socket_close(c->aprsock);
1662                 err_response++;
1663                 if (bad++ > 10) {
1664                     err("\nTest aborted after 10 failures\n\n");
1665                 }
1666                 start_connect(c);
1667             }
1668         }
1669         else {
1670             /* have full header */
1671             if (!good) {
1672                 /*
1673                  * this is first time, extract some interesting info
1674                  */
1675                 char *p, *q;
1676                 size_t len = 0;
1677                 p = xstrcasestr(c->cbuff, "Server:");
1678                 q = servername;
1679                 if (p) {
1680                     p += 8;
1681                     /* -1 to not overwrite last '\0' byte */
1682                     while (*p > 32 && len++ < sizeof(servername) - 1)
1683                         *q++ = *p++;
1684                 }
1685                 *q = 0;
1686             }
1687             /*
1688              * XXX: this parsing isn't even remotely HTTP compliant... but in
1689              * the interest of speed it doesn't totally have to be, it just
1690              * needs to be extended to handle whatever servers folks want to
1691              * test against. -djg
1692              */
1693
1694             /* check response code */
1695             part = strstr(c->cbuff, "HTTP");    /* really HTTP/1.x_ */
1696             if (part && strlen(part) > strlen("HTTP/1.x_")) {
1697                 strncpy(respcode, (part + strlen("HTTP/1.x_")), 3);
1698                 respcode[3] = '\0';
1699             }
1700             else {
1701                 strcpy(respcode, "500");
1702             }
1703
1704             if (respcode[0] != '2') {
1705                 err_response++;
1706                 if (verbosity >= 2)
1707                     printf("WARNING: Response code not 2xx (%s)\n", respcode);
1708             }
1709             else if (verbosity >= 3) {
1710                 printf("LOG: Response code = %s\n", respcode);
1711             }
1712             c->gotheader = 1;
1713             *s = 0;     /* terminate at end of header */
1714             if (keepalive && xstrcasestr(c->cbuff, "Keep-Alive")) {
1715                 char *cl;
1716                 c->keepalive = 1;
1717                 cl = xstrcasestr(c->cbuff, "Content-Length:");
1718                 if (cl && method != HEAD) {
1719                     /* response to HEAD doesn't have entity body */
1720                     c->length = atoi(cl + 16);
1721                 }
1722                 else {
1723                     c->length = 0;
1724                 }
1725             }
1726             c->bread += c->cbx - (s + l - c->cbuff) + r - tocopy;
1727             totalbread += c->bread;
1728
1729             /* We have received the header, so we know this destination socket
1730              * address is working, so initialize all remaining requests. */
1731             if (!requests_initialized) {
1732                 for (i = 1; i < concurrency; i++) {
1733                     con[i].socknum = i;
1734                     start_connect(&con[i]);
1735                 }
1736                 requests_initialized = 1;
1737             }
1738         }
1739     }
1740     else {
1741         /* outside header, everything we have read is entity body */
1742         c->bread += r;
1743         totalbread += r;
1744     }
1745     if (r == sizeof(buffer) && c->bread < c->length) {
1746         /* read was full, try more immediately (nonblocking already) */
1747         goto read_more;
1748     }
1749
1750     if (c->keepalive && (c->bread >= c->length)) {
1751         /* finished a keep-alive connection */
1752         good++;
1753         /* save out time */
1754         if (good == 1) {
1755             /* first time here */
1756             doclen = c->bread;
1757         }
1758         else if ((c->bread != doclen) && !nolength) {
1759             bad++;
1760             err_length++;
1761         }
1762         if (done < requests) {
1763             struct data *s = &stats[done++];
1764             doneka++;
1765             c->done      = apr_time_now();
1766             s->starttime = c->start;
1767             s->ctime     = ap_max(0, c->connect - c->start);
1768             s->time      = ap_max(0, c->done - c->start);
1769             s->waittime  = ap_max(0, c->beginread - c->endwrite);
1770             if (heartbeatres && !(done % heartbeatres)) {
1771                 fprintf(stderr, "Completed %d requests\n", done);
1772                 fflush(stderr);
1773             }
1774         }
1775         c->keepalive = 0;
1776         c->length = 0;
1777         c->gotheader = 0;
1778         c->cbx = 0;
1779         c->read = c->bread = 0;
1780         /* zero connect time with keep-alive */
1781         c->start = c->connect = lasttime = apr_time_now();
1782         set_conn_state(c, STATE_CONNECTED);
1783         write_request(c);
1784     }
1785 }
1786
1787 /* --------------------------------------------------------- */
1788
1789 /* run the tests */
1790
1791 static void test(void)
1792 {
1793     apr_time_t stoptime;
1794     apr_int16_t rtnev;
1795     apr_status_t rv;
1796     int i;
1797     apr_status_t status;
1798     int snprintf_res = 0;
1799 #ifdef NOT_ASCII
1800     apr_size_t inbytes_left, outbytes_left;
1801 #endif
1802
1803     if (isproxy) {
1804         connecthost = apr_pstrdup(cntxt, proxyhost);
1805         connectport = proxyport;
1806     }
1807     else {
1808         connecthost = apr_pstrdup(cntxt, hostname);
1809         connectport = port;
1810     }
1811
1812     if (!use_html) {
1813         printf("Benchmarking %s ", hostname);
1814     if (isproxy)
1815         printf("[through %s:%d] ", proxyhost, proxyport);
1816     printf("(be patient)%s",
1817            (heartbeatres ? "\n" : "..."));
1818     fflush(stdout);
1819     }
1820
1821     con = xcalloc(concurrency, sizeof(struct connection));
1822
1823     /*
1824      * XXX: a way to calculate the stats without requiring O(requests) memory
1825      * XXX: would be nice.
1826      */
1827     stats = xcalloc(requests, sizeof(struct data));
1828
1829     if ((status = apr_pollset_create(&readbits, concurrency, cntxt,
1830                                      APR_POLLSET_NOCOPY)) != APR_SUCCESS) {
1831         apr_err("apr_pollset_create failed", status);
1832     }
1833
1834     /* add default headers if necessary */
1835     if (!opt_host) {
1836         /* Host: header not overridden, add default value to hdrs */
1837         hdrs = apr_pstrcat(cntxt, hdrs, "Host: ", host_field, colonhost, "\r\n", NULL);
1838     }
1839     else {
1840         /* Header overridden, no need to add, as it is already in hdrs */
1841     }
1842
1843 #ifdef HAVE_TLSEXT
1844     if (is_ssl && tls_use_sni) {
1845         apr_ipsubnet_t *ip;
1846         if (((tls_sni = opt_host) || (tls_sni = hostname)) &&
1847             (!*tls_sni || apr_ipsubnet_create(&ip, tls_sni, NULL,
1848                                                cntxt) == APR_SUCCESS)) {
1849             /* IP not allowed in TLS SNI extension */
1850             tls_sni = NULL;
1851         }
1852     }
1853 #endif
1854
1855     if (!opt_useragent) {
1856         /* User-Agent: header not overridden, add default value to hdrs */
1857         hdrs = apr_pstrcat(cntxt, hdrs, "User-Agent: ApacheBench/", AP_AB_BASEREVISION, "\r\n", NULL);
1858     }
1859     else {
1860         /* Header overridden, no need to add, as it is already in hdrs */
1861     }
1862
1863     if (!opt_accept) {
1864         /* Accept: header not overridden, add default value to hdrs */
1865         hdrs = apr_pstrcat(cntxt, hdrs, "Accept: */*\r\n", NULL);
1866     }
1867     else {
1868         /* Header overridden, no need to add, as it is already in hdrs */
1869     }
1870
1871     /* setup request */
1872     if (!send_body) {
1873         snprintf_res = apr_snprintf(request, sizeof(_request),
1874             "%s %s HTTP/1.0\r\n"
1875             "%s" "%s" "%s"
1876             "%s" "\r\n",
1877             method_str[method],
1878             (isproxy) ? fullurl : path,
1879             keepalive ? "Connection: Keep-Alive\r\n" : "",
1880             cookie, auth, hdrs);
1881     }
1882     else {
1883         snprintf_res = apr_snprintf(request,  sizeof(_request),
1884             "%s %s HTTP/1.0\r\n"
1885             "%s" "%s" "%s"
1886             "Content-length: %" APR_SIZE_T_FMT "\r\n"
1887             "Content-type: %s\r\n"
1888             "%s"
1889             "\r\n",
1890             method_str[method],
1891             (isproxy) ? fullurl : path,
1892             keepalive ? "Connection: Keep-Alive\r\n" : "",
1893             cookie, auth,
1894             postlen,
1895             (content_type != NULL) ? content_type : "text/plain", hdrs);
1896     }
1897     if (snprintf_res >= sizeof(_request)) {
1898         err("Request too long\n");
1899     }
1900
1901     if (verbosity >= 2)
1902         printf("INFO: %s header == \n---\n%s\n---\n",
1903                method_str[method], request);
1904
1905     reqlen = strlen(request);
1906
1907     /*
1908      * Combine headers and (optional) post file into one continuous buffer
1909      */
1910     if (send_body) {
1911         char *buff = xmalloc(postlen + reqlen + 1);
1912         strcpy(buff, request);
1913         memcpy(buff + reqlen, postdata, postlen);
1914         request = buff;
1915     }
1916
1917 #ifdef NOT_ASCII
1918     inbytes_left = outbytes_left = reqlen;
1919     status = apr_xlate_conv_buffer(to_ascii, request, &inbytes_left,
1920                    request, &outbytes_left);
1921     if (status || inbytes_left || outbytes_left) {
1922         fprintf(stderr, "only simple translation is supported (%d/%"
1923                         APR_SIZE_T_FMT "/%" APR_SIZE_T_FMT ")\n",
1924                         status, inbytes_left, outbytes_left);
1925         exit(1);
1926     }
1927 #endif              /* NOT_ASCII */
1928
1929     if (myhost) {
1930         /* This only needs to be done once */
1931         if ((rv = apr_sockaddr_info_get(&mysa, myhost, APR_UNSPEC, 0, 0, cntxt)) != APR_SUCCESS) {
1932             char buf[120];
1933             apr_snprintf(buf, sizeof(buf),
1934                          "apr_sockaddr_info_get() for %s", myhost);
1935             apr_err(buf, rv);
1936         }
1937     }
1938
1939     /* This too */
1940     if ((rv = apr_sockaddr_info_get(&destsa, connecthost,
1941                                     myhost ? mysa->family : APR_UNSPEC,
1942                                     connectport, 0, cntxt))
1943        != APR_SUCCESS) {
1944         char buf[120];
1945         apr_snprintf(buf, sizeof(buf),
1946                  "apr_sockaddr_info_get() for %s", connecthost);
1947         apr_err(buf, rv);
1948     }
1949
1950     /* ok - lets start */
1951     start = lasttime = apr_time_now();
1952     stoptime = tlimit ? (start + apr_time_from_sec(tlimit)) : AB_MAX;
1953
1954 #ifdef SIGINT
1955     /* Output the results if the user terminates the run early. */
1956     apr_signal(SIGINT, output_results);
1957 #endif
1958
1959     /* initialise first connection to determine destination socket address
1960      * which should be used for next connections. */
1961     con[0].socknum = 0;
1962     start_connect(&con[0]);
1963
1964     do {
1965         apr_int32_t n;
1966         const apr_pollfd_t *pollresults, *pollfd;
1967
1968         n = concurrency;
1969         do {
1970             status = apr_pollset_poll(readbits, aprtimeout, &n, &pollresults);
1971         } while (APR_STATUS_IS_EINTR(status));
1972         if (status != APR_SUCCESS)
1973             apr_err("apr_pollset_poll", status);
1974
1975         for (i = 0, pollfd = pollresults; i < n; i++, pollfd++) {
1976             struct connection *c;
1977
1978             c = pollfd->client_data;
1979
1980             /*
1981              * If the connection isn't connected how can we check it?
1982              */
1983             if (c->state == STATE_UNCONNECTED)
1984                 continue;
1985
1986             rtnev = pollfd->rtnevents;
1987
1988 #ifdef USE_SSL
1989             if (c->state == STATE_CONNECTED && c->ssl && SSL_in_init(c->ssl)) {
1990                 ssl_proceed_handshake(c);
1991                 continue;
1992             }
1993 #endif
1994
1995             /*
1996              * Notes: APR_POLLHUP is set after FIN is received on some
1997              * systems, so treat that like APR_POLLIN so that we try to read
1998              * again.
1999              *
2000              * Some systems return APR_POLLERR with APR_POLLHUP.  We need to
2001              * call read_connection() for APR_POLLHUP, so check for
2002              * APR_POLLHUP first so that a closed connection isn't treated
2003              * like an I/O error.  If it is, we never figure out that the
2004              * connection is done and we loop here endlessly calling
2005              * apr_poll().
2006              */
2007             if ((rtnev & APR_POLLIN) || (rtnev & APR_POLLPRI) || (rtnev & APR_POLLHUP))
2008                 read_connection(c);
2009             if ((rtnev & APR_POLLERR) || (rtnev & APR_POLLNVAL)) {
2010                 if (destsa->next && c->state == STATE_CONNECTING && good == 0) {
2011                     destsa = destsa->next;
2012                     start_connect(c);
2013                 }
2014                 else {
2015                     bad++;
2016                     err_except++;
2017                     /* avoid apr_poll/EINPROGRESS loop on HP-UX, let recv discover ECONNREFUSED */
2018                     if (c->state == STATE_CONNECTING) {
2019                         read_connection(c);
2020                     }
2021                     else {
2022                         start_connect(c);
2023                     }
2024                 }
2025                 continue;
2026             }
2027             if (rtnev & APR_POLLOUT) {
2028                 if (c->state == STATE_CONNECTING) {
2029                     /* call connect() again to detect errors */
2030                     rv = apr_socket_connect(c->aprsock, destsa);
2031                     if (rv != APR_SUCCESS) {
2032                         set_conn_state(c, STATE_UNCONNECTED);
2033                         apr_socket_close(c->aprsock);
2034                         err_conn++;
2035                         if (bad++ > 10) {
2036                             fprintf(stderr,
2037                                     "\nTest aborted after 10 failures\n\n");
2038                             apr_err("apr_socket_connect()", rv);
2039                         }
2040                         start_connect(c);
2041                         continue;
2042                     }
2043                     else {
2044                         set_conn_state(c, STATE_CONNECTED);
2045 #ifdef USE_SSL
2046                         if (c->ssl)
2047                             ssl_proceed_handshake(c);
2048                         else
2049 #endif
2050                         write_request(c);
2051                     }
2052                 }
2053                 else {
2054                     /* POLLOUT is one shot */
2055                     set_polled_events(c, APR_POLLIN);
2056                     if (c->state == STATE_READ) {
2057                         read_connection(c);
2058                     }
2059                     else {
2060                         write_request(c);
2061                     }
2062                 }
2063             }
2064         }
2065     } while (lasttime < stoptime && done < requests);
2066
2067     if (heartbeatres)
2068         fprintf(stderr, "Finished %d requests\n", done);
2069     else
2070         printf("..done\n");
2071
2072     if (use_html)
2073         output_html_results();
2074     else
2075         output_results(0);
2076 }
2077
2078 /* ------------------------------------------------------- */
2079
2080 /* display copyright information */
2081 static void copyright(void)
2082 {
2083     if (!use_html) {
2084         printf("This is ApacheBench, Version %s\n", AP_AB_BASEREVISION " <$Revision$>");
2085         printf("Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\n");
2086         printf("Licensed to The Apache Software Foundation, http://www.apache.org/\n");
2087         printf("\n");
2088     }
2089     else {
2090         printf("<p>\n");
2091         printf(" This is ApacheBench, Version %s <i>&lt;%s&gt;</i><br>\n", AP_AB_BASEREVISION, "$Revision$");
2092         printf(" Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/<br>\n");
2093         printf(" Licensed to The Apache Software Foundation, http://www.apache.org/<br>\n");
2094         printf("</p>\n<p>\n");
2095     }
2096 }
2097
2098 /* display usage information */
2099 static void usage(const char *progname)
2100 {
2101     fprintf(stderr, "Usage: %s [options] [http"
2102 #ifdef USE_SSL
2103         "[s]"
2104 #endif
2105         "://]hostname[:port]/path\n", progname);
2106 /* 80 column ruler:  ********************************************************************************
2107  */
2108     fprintf(stderr, "Options are:\n");
2109     fprintf(stderr, "    -n requests     Number of requests to perform\n");
2110     fprintf(stderr, "    -c concurrency  Number of multiple requests to make at a time\n");
2111     fprintf(stderr, "    -t timelimit    Seconds to max. to spend on benchmarking\n");
2112     fprintf(stderr, "                    This implies -n 50000\n");
2113     fprintf(stderr, "    -s timeout      Seconds to max. wait for each response\n");
2114     fprintf(stderr, "                    Default is 30 seconds\n");
2115     fprintf(stderr, "    -b windowsize   Size of TCP send/receive buffer, in bytes\n");
2116     fprintf(stderr, "    -B address      Address to bind to when making outgoing connections\n");
2117     fprintf(stderr, "    -p postfile     File containing data to POST. Remember also to set -T\n");
2118     fprintf(stderr, "    -u putfile      File containing data to PUT. Remember also to set -T\n");
2119     fprintf(stderr, "    -T content-type Content-type header to use for POST/PUT data, eg.\n");
2120     fprintf(stderr, "                    'application/x-www-form-urlencoded'\n");
2121     fprintf(stderr, "                    Default is 'text/plain'\n");
2122     fprintf(stderr, "    -v verbosity    How much troubleshooting info to print\n");
2123     fprintf(stderr, "    -w              Print out results in HTML tables\n");
2124     fprintf(stderr, "    -i              Use HEAD instead of GET\n");
2125     fprintf(stderr, "    -x attributes   String to insert as table attributes\n");
2126     fprintf(stderr, "    -y attributes   String to insert as tr attributes\n");
2127     fprintf(stderr, "    -z attributes   String to insert as td or th attributes\n");
2128     fprintf(stderr, "    -C attribute    Add cookie, eg. 'Apache=1234'. (repeatable)\n");
2129     fprintf(stderr, "    -H attribute    Add Arbitrary header line, eg. 'Accept-Encoding: gzip'\n");
2130     fprintf(stderr, "                    Inserted after all normal header lines. (repeatable)\n");
2131     fprintf(stderr, "    -A attribute    Add Basic WWW Authentication, the attributes\n");
2132     fprintf(stderr, "                    are a colon separated username and password.\n");
2133     fprintf(stderr, "    -P attribute    Add Basic Proxy Authentication, the attributes\n");
2134     fprintf(stderr, "                    are a colon separated username and password.\n");
2135     fprintf(stderr, "    -X proxy:port   Proxyserver and port number to use\n");
2136     fprintf(stderr, "    -V              Print version number and exit\n");
2137     fprintf(stderr, "    -k              Use HTTP KeepAlive feature\n");
2138     fprintf(stderr, "    -d              Do not show percentiles served table.\n");
2139     fprintf(stderr, "    -S              Do not show confidence estimators and warnings.\n");
2140     fprintf(stderr, "    -q              Do not show progress when doing more than 150 requests\n");
2141     fprintf(stderr, "    -l              Accept variable document length (use this for dynamic pages)\n");
2142     fprintf(stderr, "    -g filename     Output collected data to gnuplot format file.\n");
2143     fprintf(stderr, "    -e filename     Output CSV file with percentages served\n");
2144     fprintf(stderr, "    -r              Don't exit on socket receive errors.\n");
2145     fprintf(stderr, "    -m method       Method name\n");
2146     fprintf(stderr, "    -h              Display usage information (this message)\n");
2147 #ifdef USE_SSL
2148
2149 #ifndef OPENSSL_NO_SSL2
2150 #define SSL2_HELP_MSG "SSL2, "
2151 #else
2152 #define SSL2_HELP_MSG ""
2153 #endif
2154
2155 #ifndef OPENSSL_NO_SSL3
2156 #define SSL3_HELP_MSG "SSL3, "
2157 #else
2158 #define SSL3_HELP_MSG ""
2159 #endif
2160
2161 #ifdef HAVE_TLSV1_X
2162 #define TLS1_X_HELP_MSG ", TLS1.1, TLS1.2"
2163 #else
2164 #define TLS1_X_HELP_MSG ""
2165 #endif
2166
2167 #ifdef HAVE_TLSEXT
2168     fprintf(stderr, "    -I              Disable TLS Server Name Indication (SNI) extension\n");
2169 #endif
2170     fprintf(stderr, "    -Z ciphersuite  Specify SSL/TLS cipher suite (See openssl ciphers)\n");
2171     fprintf(stderr, "    -f protocol     Specify SSL/TLS protocol\n");
2172     fprintf(stderr, "                    (" SSL2_HELP_MSG SSL3_HELP_MSG "TLS1" TLS1_X_HELP_MSG " or ALL)\n");
2173 #endif
2174     exit(EINVAL);
2175 }
2176
2177 /* ------------------------------------------------------- */
2178
2179 /* split URL into parts */
2180
2181 static int parse_url(const char *url)
2182 {
2183     char *cp;
2184     char *h;
2185     char *scope_id;
2186     apr_status_t rv;
2187
2188     /* Save a copy for the proxy */
2189     fullurl = apr_pstrdup(cntxt, url);
2190
2191     if (strlen(url) > 7 && strncmp(url, "http://", 7) == 0) {
2192         url += 7;
2193 #ifdef USE_SSL
2194         is_ssl = 0;
2195 #endif
2196     }
2197     else
2198 #ifdef USE_SSL
2199     if (strlen(url) > 8 && strncmp(url, "https://", 8) == 0) {
2200         url += 8;
2201         is_ssl = 1;
2202     }
2203 #else
2204     if (strlen(url) > 8 && strncmp(url, "https://", 8) == 0) {
2205         fprintf(stderr, "SSL not compiled in; no https support\n");
2206         exit(1);
2207     }
2208 #endif
2209
2210     if ((cp = strchr(url, '/')) == NULL)
2211         return 1;
2212     h = apr_pstrmemdup(cntxt, url, cp - url);
2213     rv = apr_parse_addr_port(&hostname, &scope_id, &port, h, cntxt);
2214     if (rv != APR_SUCCESS || !hostname || scope_id) {
2215         return 1;
2216     }
2217     path = apr_pstrdup(cntxt, cp);
2218     *cp = '\0';
2219     if (*url == '[') {      /* IPv6 numeric address string */
2220         host_field = apr_psprintf(cntxt, "[%s]", hostname);
2221     }
2222     else {
2223         host_field = hostname;
2224     }
2225
2226     if (port == 0) {        /* no port specified */
2227 #ifdef USE_SSL
2228         if (is_ssl)
2229             port = 443;
2230         else
2231 #endif
2232         port = 80;
2233     }
2234
2235     if ((
2236 #ifdef USE_SSL
2237          is_ssl && (port != 443)) || (!is_ssl &&
2238 #endif
2239          (port != 80)))
2240     {
2241         colonhost = apr_psprintf(cntxt,":%d",port);
2242     } else
2243         colonhost = "";
2244     return 0;
2245 }
2246
2247 /* ------------------------------------------------------- */
2248
2249 /* read data to POST/PUT from file, save contents and length */
2250
2251 static apr_status_t open_postfile(const char *pfile)
2252 {
2253     apr_file_t *postfd;
2254     apr_finfo_t finfo;
2255     apr_status_t rv;
2256     char errmsg[120];
2257
2258     rv = apr_file_open(&postfd, pfile, APR_READ, APR_OS_DEFAULT, cntxt);
2259     if (rv != APR_SUCCESS) {
2260         fprintf(stderr, "ab: Could not open POST data file (%s): %s\n", pfile,
2261                 apr_strerror(rv, errmsg, sizeof errmsg));
2262         return rv;
2263     }
2264
2265     rv = apr_file_info_get(&finfo, APR_FINFO_NORM, postfd);
2266     if (rv != APR_SUCCESS) {
2267         fprintf(stderr, "ab: Could not stat POST data file (%s): %s\n", pfile,
2268                 apr_strerror(rv, errmsg, sizeof errmsg));
2269         return rv;
2270     }
2271     postlen = (apr_size_t)finfo.size;
2272     postdata = xmalloc(postlen);
2273     rv = apr_file_read_full(postfd, postdata, postlen, NULL);
2274     if (rv != APR_SUCCESS) {
2275         fprintf(stderr, "ab: Could not read POST data file: %s\n",
2276                 apr_strerror(rv, errmsg, sizeof errmsg));
2277         return rv;
2278     }
2279     apr_file_close(postfd);
2280     return APR_SUCCESS;
2281 }
2282
2283 /* ------------------------------------------------------- */
2284
2285 /* sort out command-line args and call test */
2286 int main(int argc, const char * const argv[])
2287 {
2288     int l;
2289     char tmp[1024];
2290     apr_status_t status;
2291     apr_getopt_t *opt;
2292     const char *opt_arg;
2293     char c;
2294 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
2295     int max_prot = TLS1_2_VERSION;
2296 #ifndef OPENSSL_NO_SSL3
2297     int min_prot = SSL3_VERSION;
2298 #else
2299     int min_prot = TLS1_VERSION;
2300 #endif
2301 #endif /* #if OPENSSL_VERSION_NUMBER >= 0x10100000L */
2302 #ifdef USE_SSL
2303     AB_SSL_METHOD_CONST SSL_METHOD *meth = SSLv23_client_method();
2304 #endif
2305
2306     /* table defaults  */
2307     tablestring = "";
2308     trstring = "";
2309     tdstring = "bgcolor=white";
2310     cookie = "";
2311     auth = "";
2312     proxyhost = "";
2313     hdrs = "";
2314
2315     apr_app_initialize(&argc, &argv, NULL);
2316     atexit(apr_terminate);
2317     apr_pool_create(&cntxt, NULL);
2318     apr_pool_abort_set(abort_on_oom, cntxt);
2319
2320 #ifdef NOT_ASCII
2321     status = apr_xlate_open(&to_ascii, "ISO-8859-1", APR_DEFAULT_CHARSET, cntxt);
2322     if (status) {
2323         fprintf(stderr, "apr_xlate_open(to ASCII)->%d\n", status);
2324         exit(1);
2325     }
2326     status = apr_xlate_open(&from_ascii, APR_DEFAULT_CHARSET, "ISO-8859-1", cntxt);
2327     if (status) {
2328         fprintf(stderr, "apr_xlate_open(from ASCII)->%d\n", status);
2329         exit(1);
2330     }
2331     status = apr_base64init_ebcdic(to_ascii, from_ascii);
2332     if (status) {
2333         fprintf(stderr, "apr_base64init_ebcdic()->%d\n", status);
2334         exit(1);
2335     }
2336 #endif
2337
2338     myhost = NULL; /* 0.0.0.0 or :: */
2339
2340     apr_getopt_init(&opt, cntxt, argc, argv);
2341     while ((status = apr_getopt(opt, "n:c:t:s:b:T:p:u:v:lrkVhwiIx:y:z:C:H:P:A:g:X:de:SqB:m:"
2342 #ifdef USE_SSL
2343             "Z:f:"
2344 #endif
2345             ,&c, &opt_arg)) == APR_SUCCESS) {
2346         switch (c) {
2347             case 'n':
2348                 requests = atoi(opt_arg);
2349                 if (requests <= 0) {
2350                     err("Invalid number of requests\n");
2351                 }
2352                 break;
2353             case 'k':
2354                 keepalive = 1;
2355                 break;
2356             case 'q':
2357                 heartbeatres = 0;
2358                 break;
2359             case 'c':
2360                 concurrency = atoi(opt_arg);
2361                 break;
2362             case 'b':
2363                 windowsize = atoi(opt_arg);
2364                 break;
2365             case 'i':
2366                 if (method != NO_METH)
2367                     err("Cannot mix HEAD with other methods\n");
2368                 method = HEAD;
2369                 break;
2370             case 'g':
2371                 gnuplot = xstrdup(opt_arg);
2372                 break;
2373             case 'd':
2374                 percentile = 0;
2375                 break;
2376             case 'e':
2377                 csvperc = xstrdup(opt_arg);
2378                 break;
2379             case 'S':
2380                 confidence = 0;
2381                 break;
2382             case 's':
2383                 aprtimeout = apr_time_from_sec(atoi(opt_arg)); /* timeout value */
2384                 break;
2385             case 'p':
2386                 if (method != NO_METH)
2387                     err("Cannot mix POST with other methods\n");
2388                 if (open_postfile(opt_arg) != APR_SUCCESS) {
2389                     exit(1);
2390                 }
2391                 method = POST;
2392                 send_body = 1;
2393                 break;
2394             case 'u':
2395                 if (method != NO_METH)
2396                     err("Cannot mix PUT with other methods\n");
2397                 if (open_postfile(opt_arg) != APR_SUCCESS) {
2398                     exit(1);
2399                 }
2400                 method = PUT;
2401                 send_body = 1;
2402                 break;
2403             case 'l':
2404                 nolength = 1;
2405                 break;
2406             case 'r':
2407                 recverrok = 1;
2408                 break;
2409             case 'v':
2410                 verbosity = atoi(opt_arg);
2411                 break;
2412             case 't':
2413                 tlimit = atoi(opt_arg);
2414                 requests = MAX_REQUESTS;    /* need to size data array on
2415                                              * something */
2416                 break;
2417             case 'T':
2418                 content_type = apr_pstrdup(cntxt, opt_arg);
2419                 break;
2420             case 'C':
2421                 cookie = apr_pstrcat(cntxt, "Cookie: ", opt_arg, "\r\n", NULL);
2422                 break;
2423             case 'A':
2424                 /*
2425                  * assume username passwd already to be in colon separated form.
2426                  * Ready to be uu-encoded.
2427                  */
2428                 while (apr_isspace(*opt_arg))
2429                     opt_arg++;
2430                 if (apr_base64_encode_len(strlen(opt_arg)) > sizeof(tmp)) {
2431                     err("Authentication credentials too long\n");
2432                 }
2433                 l = apr_base64_encode(tmp, opt_arg, strlen(opt_arg));
2434                 tmp[l] = '\0';
2435
2436                 auth = apr_pstrcat(cntxt, auth, "Authorization: Basic ", tmp,
2437                                        "\r\n", NULL);
2438                 break;
2439             case 'P':
2440                 /*
2441                  * assume username passwd already to be in colon separated form.
2442                  */
2443                 while (apr_isspace(*opt_arg))
2444                 opt_arg++;
2445                 if (apr_base64_encode_len(strlen(opt_arg)) > sizeof(tmp)) {
2446                     err("Proxy credentials too long\n");
2447                 }
2448                 l = apr_base64_encode(tmp, opt_arg, strlen(opt_arg));
2449                 tmp[l] = '\0';
2450
2451                 auth = apr_pstrcat(cntxt, auth, "Proxy-Authorization: Basic ",
2452                                        tmp, "\r\n", NULL);
2453                 break;
2454             case 'H':
2455                 hdrs = apr_pstrcat(cntxt, hdrs, opt_arg, "\r\n", NULL);
2456                 /*
2457                  * allow override of some of the common headers that ab adds
2458                  */
2459                 if (strncasecmp(opt_arg, "Host:", 5) == 0) {
2460                     char *host;
2461                     apr_size_t len;
2462                     opt_arg += 5;
2463                     while (apr_isspace(*opt_arg))
2464                         opt_arg++;
2465                     len = strlen(opt_arg);
2466                     host = strdup(opt_arg);
2467                     while (len && apr_isspace(host[len-1]))
2468                         host[--len] = '\0';
2469                     opt_host = host;
2470                 } else if (strncasecmp(opt_arg, "Accept:", 7) == 0) {
2471                     opt_accept = 1;
2472                 } else if (strncasecmp(opt_arg, "User-Agent:", 11) == 0) {
2473                     opt_useragent = 1;
2474                 }
2475                 break;
2476             case 'w':
2477                 use_html = 1;
2478                 break;
2479                 /*
2480                  * if any of the following three are used, turn on html output
2481                  * automatically
2482                  */
2483             case 'x':
2484                 use_html = 1;
2485                 tablestring = opt_arg;
2486                 break;
2487             case 'X':
2488                 {
2489                     char *p;
2490                     /*
2491                      * assume proxy-name[:port]
2492                      */
2493                     if ((p = strchr(opt_arg, ':'))) {
2494                         *p = '\0';
2495                         p++;
2496                         proxyport = atoi(p);
2497                     }
2498                     proxyhost = apr_pstrdup(cntxt, opt_arg);
2499                     isproxy = 1;
2500                 }
2501                 break;
2502             case 'y':
2503                 use_html = 1;
2504                 trstring = opt_arg;
2505                 break;
2506             case 'z':
2507                 use_html = 1;
2508                 tdstring = opt_arg;
2509                 break;
2510             case 'h':
2511                 usage(argv[0]);
2512                 break;
2513             case 'V':
2514                 copyright();
2515                 return 0;
2516             case 'B':
2517                 myhost = apr_pstrdup(cntxt, opt_arg);
2518                 break;
2519             case 'm':
2520                 method = CUSTOM_METHOD;
2521                 method_str[CUSTOM_METHOD] = strdup(opt_arg);
2522                 break;
2523 #ifdef USE_SSL
2524             case 'Z':
2525                 ssl_cipher = strdup(opt_arg);
2526                 break;
2527             case 'f':
2528 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2529                 if (strncasecmp(opt_arg, "ALL", 3) == 0) {
2530                     meth = SSLv23_client_method();
2531 #ifndef OPENSSL_NO_SSL2
2532                 } else if (strncasecmp(opt_arg, "SSL2", 4) == 0) {
2533                     meth = SSLv2_client_method();
2534 #ifdef HAVE_TLSEXT
2535                     tls_use_sni = 0;
2536 #endif
2537 #endif
2538 #ifndef OPENSSL_NO_SSL3
2539                 } else if (strncasecmp(opt_arg, "SSL3", 4) == 0) {
2540                     meth = SSLv3_client_method();
2541 #ifdef HAVE_TLSEXT
2542                     tls_use_sni = 0;
2543 #endif
2544 #endif
2545 #ifdef HAVE_TLSV1_X
2546                 } else if (strncasecmp(opt_arg, "TLS1.1", 6) == 0) {
2547                     meth = TLSv1_1_client_method();
2548                 } else if (strncasecmp(opt_arg, "TLS1.2", 6) == 0) {
2549                     meth = TLSv1_2_client_method();
2550 #endif
2551                 } else if (strncasecmp(opt_arg, "TLS1", 4) == 0) {
2552                     meth = TLSv1_client_method();
2553                 }
2554 #else /* #if OPENSSL_VERSION_NUMBER < 0x10100000L */
2555                 meth = TLS_client_method();
2556                 if (strncasecmp(opt_arg, "ALL", 3) == 0) {
2557                     max_prot = TLS1_2_VERSION;
2558 #ifndef OPENSSL_NO_SSL3
2559                     min_prot = SSL3_VERSION;
2560 #else
2561                     min_prot = TLS1_VERSION;
2562 #endif
2563 #ifndef OPENSSL_NO_SSL3
2564                 } else if (strncasecmp(opt_arg, "SSL3", 4) == 0) {
2565                     max_prot = SSL3_VERSION;
2566                     min_prot = SSL3_VERSION;
2567 #endif
2568                 } else if (strncasecmp(opt_arg, "TLS1.1", 6) == 0) {
2569                     max_prot = TLS1_1_VERSION;
2570                     min_prot = TLS1_1_VERSION;
2571                 } else if (strncasecmp(opt_arg, "TLS1.2", 6) == 0) {
2572                     max_prot = TLS1_2_VERSION;
2573                     min_prot = TLS1_2_VERSION;
2574                 } else if (strncasecmp(opt_arg, "TLS1", 4) == 0) {
2575                     max_prot = TLS1_VERSION;
2576                     min_prot = TLS1_VERSION;
2577                 }
2578 #endif /* #if OPENSSL_VERSION_NUMBER < 0x10100000L */
2579                 break;
2580 #ifdef HAVE_TLSEXT
2581             case 'I':
2582                 tls_use_sni = 0;
2583                 break;
2584 #endif
2585 #endif
2586         }
2587     }
2588
2589     if (opt->ind != argc - 1) {
2590         fprintf(stderr, "%s: wrong number of arguments\n", argv[0]);
2591         usage(argv[0]);
2592     }
2593
2594     if (method == NO_METH) {
2595         method = GET;
2596     }
2597
2598     if (parse_url(apr_pstrdup(cntxt, opt->argv[opt->ind++]))) {
2599         fprintf(stderr, "%s: invalid URL\n", argv[0]);
2600         usage(argv[0]);
2601     }
2602
2603     if ((concurrency < 0) || (concurrency > MAX_CONCURRENCY)) {
2604         fprintf(stderr, "%s: Invalid Concurrency [Range 0..%d]\n",
2605                 argv[0], MAX_CONCURRENCY);
2606         usage(argv[0]);
2607     }
2608
2609     if (concurrency > requests) {
2610         fprintf(stderr, "%s: Cannot use concurrency level greater than "
2611                 "total number of requests\n", argv[0]);
2612         usage(argv[0]);
2613     }
2614
2615     if ((heartbeatres) && (requests > 150)) {
2616         heartbeatres = requests / 10;   /* Print line every 10% of requests */
2617         if (heartbeatres < 100)
2618             heartbeatres = 100; /* but never more often than once every 100
2619                                  * connections. */
2620     }
2621     else
2622         heartbeatres = 0;
2623
2624 #ifdef USE_SSL
2625 #ifdef RSAREF
2626     R_malloc_init();
2627 #else
2628 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2629     CRYPTO_malloc_init();
2630 #endif
2631 #endif
2632     SSL_load_error_strings();
2633     SSL_library_init();
2634     bio_out=BIO_new_fp(stdout,BIO_NOCLOSE);
2635     bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
2636
2637     if (!(ssl_ctx = SSL_CTX_new(meth))) {
2638         BIO_printf(bio_err, "Could not initialize SSL Context.\n");
2639         ERR_print_errors(bio_err);
2640         exit(1);
2641     }
2642     SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL);
2643 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
2644     SSL_CTX_set_max_proto_version(ssl_ctx, max_prot);
2645     SSL_CTX_set_min_proto_version(ssl_ctx, min_prot);
2646 #endif
2647 #ifdef SSL_MODE_RELEASE_BUFFERS
2648     /* Keep memory usage as low as possible */
2649     SSL_CTX_set_mode (ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
2650 #endif
2651     if (ssl_cipher != NULL) {
2652         if (!SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher)) {
2653             fprintf(stderr, "error setting cipher list [%s]\n", ssl_cipher);
2654         ERR_print_errors_fp(stderr);
2655         exit(1);
2656     }
2657     }
2658     if (verbosity >= 3) {
2659         SSL_CTX_set_info_callback(ssl_ctx, ssl_state_cb);
2660     }
2661 #endif
2662 #ifdef SIGPIPE
2663     apr_signal(SIGPIPE, SIG_IGN);       /* Ignore writes to connections that
2664                                          * have been closed at the other end. */
2665 #endif
2666     copyright();
2667     test();
2668     apr_pool_destroy(cntxt);
2669
2670     return 0;
2671 }