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