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