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