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