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