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