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