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