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