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