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