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