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