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