1 /* Copyright 1996-2005 The Apache Software Foundation or its licensors, as
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
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/
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.
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
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
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
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
71 ** Internalized the version string - this string is part
72 ** of the Agent: header and the result output.
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.
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
85 ** SIGINT now triggers output_results().
86 ** Conributed by colm, March 30, 2006
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).
98 #define AP_AB_BASEREVISION "2.3"
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
108 * - (performance problem) heavy use of strstr shows up top in profile
109 * only an issue for loopback usage
112 /* -------------------------------------------------------------------- */
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.
122 /* affects include files on Solaris */
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"
134 #include "apr_portable.h"
135 #include "ap_release.h"
136 #include "apr_poll.h"
138 #define APR_WANT_STRFUNC
139 #include "apr_want.h"
141 #include "apr_base64.h"
143 #include "apr_xlate.h"
148 #if APR_HAVE_STDLIB_H
151 #if APR_HAVE_UNISTD_H
152 #include <unistd.h> /* for getpid() */
155 #if !defined(WIN32) && !defined(NETWARE)
156 #include "ap_config_auto.h"
159 #if defined(HAVE_SSLC)
161 /* Libraries for RSA SSL-C */
171 #define SK_NUM(x) sk_num(x)
172 #define SK_VALUE(x,y) sk_value(x,y)
173 typedef STACK X509_STACK_TYPE;
175 #elif defined(HAVE_OPENSSL)
177 /* Libraries on most systems.. */
178 #include <openssl/rsa.h>
179 #include <openssl/crypto.h>
180 #include <openssl/x509.h>
181 #include <openssl/pem.h>
182 #include <openssl/err.h>
183 #include <openssl/ssl.h>
184 #include <openssl/rand.h>
186 #define SK_NUM(x) sk_X509_num(x)
187 #define SK_VALUE(x,y) sk_X509_value(x,y)
188 typedef STACK_OF(X509) X509_STACK_TYPE;
197 /* ------------------- DEFINITIONS -------------------------- */
200 #define AB_MAX APR_INT64_C(0x7fffffffffffffff)
202 #define AB_MAX LLONG_MAX
205 /* maximum number of requests on a time limited test */
206 #define MAX_REQUESTS 50000
208 /* good old state hostname */
209 #define STATE_UNCONNECTED 0
210 #define STATE_CONNECTING 1 /* TCP connect initiated, but we don't
211 * know if it worked yet
213 #define STATE_CONNECTED 2 /* we know TCP connect completed */
216 #define CBUFFSIZE (2048)
220 apr_socket_t *aprsock;
222 apr_size_t read; /* amount of bytes read */
223 apr_size_t bread; /* amount of body read */
224 apr_size_t rwrite, rwrote; /* keep pointers in what we write - across
226 apr_size_t length; /* Content-Length value used for keep-alive */
227 char cbuff[CBUFFSIZE]; /* a buffer to store server response header */
228 int cbx; /* offset in cbuffer */
229 int keepalive; /* non-zero if a keep-alive request */
230 int gotheader; /* non-zero if we have the entire header in
232 apr_time_t start, /* Start of connection */
233 connect, /* Connected, start writing */
234 endwrite, /* Request written */
235 beginread, /* First byte of input */
236 done; /* Connection closed */
245 int read; /* number of bytes read */
246 apr_time_t starttime; /* start time of connection in seconds since
248 apr_interval_time_t waittime; /* Between writing request and reading
250 apr_interval_time_t ctime; /* time in ms to connect */
251 apr_interval_time_t time; /* time in ms for connection */
254 #define ap_min(a,b) ((a)<(b))?(a):(b)
255 #define ap_max(a,b) ((a)>(b))?(a):(b)
256 #define MAX_CONCURRENCY 20000
258 /* --------------------- GLOBALS ---------------------------- */
260 int verbosity = 0; /* no verbosity by default */
261 int posting = 0; /* GET by default */
262 int requests = 1; /* Number of requests to make */
263 int heartbeatres = 100; /* How often do we say we're alive */
264 int concurrency = 1; /* Number of multiple requests to make */
265 int percentile = 1; /* Show percentile served */
266 int confidence = 1; /* Show confidence estimator and warnings */
267 int tlimit = 0; /* time limit in secs */
268 int keepalive = 0; /* try and do keepalive connections */
269 int windowsize = 0; /* we use the OS default window size */
270 char servername[1024]; /* name that server reports */
271 char *hostname; /* host name from URL */
272 char *host_field; /* value of "Host:" header field */
273 char *path; /* path name */
274 char postfile[1024]; /* name of file containing post data */
275 char *postdata; /* *buffer containing data from postfile */
276 apr_size_t postlen = 0; /* length of data to be POSTed */
277 char content_type[1024];/* content type to put in POST header */
278 char *cookie, /* optional cookie line */
279 *auth, /* optional (basic/uuencoded) auhentication */
280 *hdrs; /* optional arbitrary headers */
281 apr_port_t port; /* port number */
282 char proxyhost[1024]; /* proxy host name */
283 int proxyport = 0; /* proxy port */
285 apr_port_t connectport;
286 char *gnuplot; /* GNUplot file */
287 char *csvperc; /* CSV Percentile file */
289 char * fullurl, * colonhost;
291 apr_interval_time_t aprtimeout = apr_time_from_sec(30); /* timeout value */
293 * XXX - this is now a per read/write transact type of value
296 int use_html = 0; /* use html in the report */
297 const char *tablestring;
298 const char *trstring;
299 const char *tdstring;
301 apr_size_t doclen = 0; /* the length the document should be */
302 long started = 0; /* number of requests started, so no excess */
303 long totalread = 0; /* total number of bytes read */
304 long totalbread = 0; /* totoal amount of entity body read */
305 long totalposted = 0; /* total number of bytes posted, inc. headers */
306 long done = 0; /* number of requests we have done */
307 long doneka = 0; /* number of keep alive connections done */
308 long good = 0, bad = 0; /* number of good and bad requests */
309 long epipe = 0; /* number of broken pipe writes */
314 char *ssl_cipher = NULL;
315 char *ssl_info = NULL;
316 BIO *bio_out,*bio_err;
319 /* store error cases */
320 int err_length = 0, err_conn = 0, err_except = 0;
321 int err_response = 0;
323 apr_time_t start, endtime;
325 /* global request (and its length) */
327 char *request = _request;
330 /* one global throw-away buffer to read stuff into */
333 /* interesting percentiles */
334 int percs[] = {50, 66, 75, 80, 90, 95, 98, 99, 100};
336 struct connection *con; /* connection array */
337 struct data *stats; /* date for each request */
340 apr_pollset_t *readbits;
342 apr_sockaddr_t *destsa;
345 apr_xlate_t *from_ascii, *to_ascii;
348 static void write_request(struct connection * c);
349 static void close_connection(struct connection * c);
351 /* --------------------------------------------------------- */
353 /* simple little function to write an error string and exit */
355 static void err(char *s)
357 fprintf(stderr, "%s\n", s);
359 printf("Total of %ld requests completed\n" , done);
363 /* simple little function to write an APR error string and exit */
365 static void apr_err(char *s, apr_status_t rv)
371 s, apr_strerror(rv, buf, sizeof buf), rv);
373 printf("Total of %ld requests completed\n" , done);
377 /* --------------------------------------------------------- */
378 /* write out request to a connection - assumes we can write
379 * (small) request out in one go into our new socket buffer
383 static long ssl_print_cb(BIO *bio,int cmd,const char *argp,int argi,long argl,long ret)
387 out=(BIO *)BIO_get_callback_arg(bio);
388 if (out == NULL) return(ret);
390 if (cmd == (BIO_CB_READ|BIO_CB_RETURN)) {
391 BIO_printf(out,"read from %p [%p] (%d bytes => %ld (0x%lX))\n",
392 bio, argp, argi, ret, ret);
393 BIO_dump(out,(char *)argp,(int)ret);
396 else if (cmd == (BIO_CB_WRITE|BIO_CB_RETURN)) {
397 BIO_printf(out,"write to %p [%p] (%d bytes => %ld (0x%lX))\n",
398 bio, argp, argi, ret, ret);
399 BIO_dump(out,(char *)argp,(int)ret);
404 static void ssl_state_cb(const SSL *s, int w, int r)
406 if (w & SSL_CB_ALERT) {
407 BIO_printf(bio_err, "SSL/TLS Alert [%s] %s:%s\n",
408 (w & SSL_CB_READ ? "read" : "write"),
409 SSL_alert_type_string_long(r),
410 SSL_alert_desc_string_long(r));
411 } else if (w & SSL_CB_LOOP) {
412 BIO_printf(bio_err, "SSL/TLS State [%s] %s\n",
413 (SSL_in_connect_init((SSL*)s) ? "connect" : "-"),
414 SSL_state_string_long(s));
415 } else if (w & (SSL_CB_HANDSHAKE_START|SSL_CB_HANDSHAKE_DONE)) {
416 BIO_printf(bio_err, "SSL/TLS Handshake [%s] %s\n",
417 (w & SSL_CB_HANDSHAKE_START ? "Start" : "Done"),
418 SSL_state_string_long(s));
424 #define RAND_MAX INT_MAX
427 static int ssl_rand_choosenum(int l, int h)
432 srand((unsigned int)time(NULL));
433 apr_snprintf(buf, sizeof(buf), "%.0f",
434 (((double)(rand()%RAND_MAX)/RAND_MAX)*(h-l)));
441 static void ssl_rand_seed(void)
447 unsigned char stackdata[256];
450 * seed in the current time (usually just 4 bytes)
454 RAND_seed((unsigned char *)&t, l);
458 * seed in the current process id (usually just 4 bytes)
462 RAND_seed((unsigned char *)&pid, l);
466 * seed in some current state of the run-time stack (128 bytes)
468 n = ssl_rand_choosenum(0, sizeof(stackdata)-128-1);
469 RAND_seed(stackdata+n, 128);
473 static int ssl_print_connection_info(BIO *bio, SSL *ssl)
478 c = SSL_get_current_cipher(ssl);
479 BIO_printf(bio,"Cipher Suite Protocol :%s\n", SSL_CIPHER_get_version(c));
480 BIO_printf(bio,"Cipher Suite Name :%s\n",SSL_CIPHER_get_name(c));
482 bits = SSL_CIPHER_get_bits(c,&alg_bits);
483 BIO_printf(bio,"Cipher Suite Cipher Bits:%d (%d)\n",bits,alg_bits);
488 static void ssl_print_cert_info(BIO *bio, X509 *cert)
493 BIO_printf(bio, "Certificate version: %ld\n", X509_get_version(cert)+1);
494 BIO_printf(bio,"Valid from: ");
495 ASN1_UTCTIME_print(bio, X509_get_notBefore(cert));
496 BIO_printf(bio,"\n");
498 BIO_printf(bio,"Valid to : ");
499 ASN1_UTCTIME_print(bio, X509_get_notAfter(cert));
500 BIO_printf(bio,"\n");
502 BIO_printf(bio,"Public key is %d bits\n",
503 EVP_PKEY_bits(X509_get_pubkey(cert)));
505 dn = X509_get_issuer_name(cert);
506 X509_NAME_oneline(dn, buf, sizeof(buf));
507 BIO_printf(bio,"The issuer name is %s\n", buf);
509 dn=X509_get_subject_name(cert);
510 X509_NAME_oneline(dn, buf, sizeof(buf));
511 BIO_printf(bio,"The subject name is %s\n", buf);
513 /* dump the extension list too */
514 BIO_printf(bio, "Extension Count: %d\n", X509_get_ext_count(cert));
517 static void ssl_print_info(struct connection *c)
523 BIO_printf(bio_err, "\n");
524 sk = SSL_get_peer_cert_chain(c->ssl);
525 if ((count = SK_NUM(sk)) > 0) {
527 for (i=1; i<count; i++) {
528 cert = (X509 *)SK_VALUE(sk, i);
529 ssl_print_cert_info(bio_out, cert);
533 cert = SSL_get_peer_certificate(c->ssl);
535 BIO_printf(bio_out, "Anon DH\n");
537 BIO_printf(bio_out, "Peer certificate\n");
538 ssl_print_cert_info(bio_out, cert);
541 ssl_print_connection_info(bio_err,c->ssl);
542 SSL_SESSION_print(bio_err, SSL_get_session(c->ssl));
545 static void ssl_proceed_handshake(struct connection *c)
551 apr_pollfd_t new_pollfd;
553 ret = SSL_do_handshake(c->ssl);
554 ecode = SSL_get_error(c->ssl, ret);
560 if (ssl_info == NULL) {
563 int sk_bits, pk_bits, swork;
565 ci = SSL_get_current_cipher(c->ssl);
566 sk_bits = SSL_CIPHER_get_bits(ci, &swork);
567 cert = SSL_get_peer_certificate(c->ssl);
569 pk_bits = EVP_PKEY_bits(X509_get_pubkey(cert));
571 pk_bits = 0; /* Anon DH */
573 ssl_info = malloc(128);
574 apr_snprintf(ssl_info, 128, "%s,%s,%d,%d",
575 SSL_CIPHER_get_version(ci),
576 SSL_CIPHER_get_name(ci),
582 case SSL_ERROR_WANT_READ:
583 new_pollfd.desc_type = APR_POLL_SOCKET;
584 new_pollfd.reqevents = APR_POLLIN;
585 new_pollfd.desc.s = c->aprsock;
586 new_pollfd.client_data = c;
587 apr_pollset_add(readbits, &new_pollfd);
590 case SSL_ERROR_WANT_WRITE:
594 case SSL_ERROR_WANT_CONNECT:
596 case SSL_ERROR_SYSCALL:
597 /* Unexpected result */
598 BIO_printf(bio_err, "SSL handshake failed (%d).\n", ecode);
599 ERR_print_errors(bio_err);
609 static void write_request(struct connection * c)
612 apr_time_t tnow = apr_time_now();
613 apr_size_t l = c->rwrite;
614 apr_status_t e = APR_SUCCESS; /* prevent gcc warning */
619 if (c->rwrite == 0) {
620 apr_socket_timeout_set(c->aprsock, 0);
625 c->rwrite += postlen;
627 else if (tnow > c->connect + aprtimeout) {
628 printf("Send request timed out!\n");
636 e_ssl = SSL_write(c->ssl,request + c->rwrote, l);
638 BIO_printf(bio_err, "SSL write failed - closing connection\n");
639 ERR_print_errors(bio_err);
640 close_connection (c);
648 e = apr_socket_send(c->aprsock, request + c->rwrote, &l);
651 * Bail early on the most common case
656 if (e != APR_SUCCESS) {
658 * Let's hope this traps EWOULDBLOCK too !
660 if (!APR_STATUS_IS_EAGAIN(e)) {
662 printf("Send request failed!\n");
671 totalposted += c->rwrite;
672 c->state = STATE_READ;
673 c->endwrite = apr_time_now();
675 apr_pollfd_t new_pollfd;
676 new_pollfd.desc_type = APR_POLL_SOCKET;
677 new_pollfd.reqevents = APR_POLLIN;
678 new_pollfd.desc.s = c->aprsock;
679 new_pollfd.client_data = c;
680 apr_pollset_add(readbits, &new_pollfd);
684 /* --------------------------------------------------------- */
686 /* calculate and output results */
688 static int compradre(struct data * a, struct data * b)
690 if ((a->ctime) < (b->ctime))
692 if ((a->ctime) > (b->ctime))
697 static int comprando(struct data * a, struct data * b)
699 if ((a->time) < (b->time))
701 if ((a->time) > (b->time))
706 static int compri(struct data * a, struct data * b)
708 apr_interval_time_t p = a->time - a->ctime;
709 apr_interval_time_t q = b->time - b->ctime;
717 static int compwait(struct data * a, struct data * b)
719 if ((a->waittime) < (b->waittime))
721 if ((a->waittime) > (b->waittime))
726 static void output_results(int sig)
728 apr_interval_time_t timetakenusec;
731 endtime = apr_time_now();
732 timetakenusec = endtime - start;
733 timetaken = ((float)apr_time_sec(timetakenusec)) +
734 ((float)apr_time_usec(timetakenusec)) / 1000000.0F;
737 printf("Server Software: %s\n", servername);
738 printf("Server Hostname: %s\n", hostname);
739 printf("Server Port: %hd\n", port);
741 if (is_ssl && ssl_info) {
742 printf("SSL/TLS Protocol: %s\n", ssl_info);
746 printf("Document Path: %s\n", path);
747 printf("Document Length: %" APR_SIZE_T_FMT " bytes\n", doclen);
749 printf("Concurrency Level: %d\n", concurrency);
750 printf("Time taken for tests: %ld.%03ld seconds\n",
751 (long) apr_time_sec(timetakenusec),
752 (long) apr_time_usec(timetakenusec));
753 printf("Complete requests: %ld\n", done);
754 printf("Failed requests: %ld\n", bad);
756 printf(" (Connect: %d, Length: %d, Exceptions: %d)\n",
757 err_conn, err_length, err_except);
758 printf("Write errors: %ld\n", epipe);
760 printf("Non-2xx responses: %d\n", err_response);
762 printf("Keep-Alive requests: %ld\n", doneka);
763 printf("Total transferred: %ld bytes\n", totalread);
765 printf("Total POSTed: %ld\n", totalposted);
766 printf("HTML transferred: %ld bytes\n", totalbread);
768 /* avoid divide by zero */
770 printf("Requests per second: %.2f [#/sec] (mean)\n",
771 (float) (done / timetaken));
772 printf("Time per request: %.3f [ms] (mean)\n",
773 (float) (1000 * concurrency * timetaken / done));
774 printf("Time per request: %.3f [ms] (mean, across all concurrent requests)\n",
775 (float) (1000 * timetaken / done));
776 printf("Transfer rate: %.2f [Kbytes/sec] received\n",
777 (float) (totalread / 1024 / timetaken));
779 printf(" %.2f kb/s sent\n",
780 (float) (totalposted / timetaken / 1024));
781 printf(" %.2f kb/s total\n",
782 (float) ((totalread + totalposted) / timetaken / 1024));
787 /* work out connection times */
789 apr_time_t totalcon = 0, total = 0, totald = 0, totalwait = 0;
790 apr_time_t meancon, meantot, meand, meanwait;
791 apr_interval_time_t mincon = AB_MAX, mintot = AB_MAX, mind = AB_MAX,
793 apr_interval_time_t maxcon = 0, maxtot = 0, maxd = 0, maxwait = 0;
794 apr_interval_time_t mediancon = 0, mediantot = 0, mediand = 0, medianwait = 0;
795 double sdtot = 0, sdcon = 0, sdd = 0, sdwait = 0;
797 for (i = 0; i < requests; i++) {
798 struct data s = stats[i];
799 mincon = ap_min(mincon, s.ctime);
800 mintot = ap_min(mintot, s.time);
801 mind = ap_min(mind, s.time - s.ctime);
802 minwait = ap_min(minwait, s.waittime);
804 maxcon = ap_max(maxcon, s.ctime);
805 maxtot = ap_max(maxtot, s.time);
806 maxd = ap_max(maxd, s.time - s.ctime);
807 maxwait = ap_max(maxwait, s.waittime);
811 totald += s.time - s.ctime;
812 totalwait += s.waittime;
814 meancon = totalcon / requests;
815 meantot = total / requests;
816 meand = totald / requests;
817 meanwait = totalwait / requests;
819 /* calculating the sample variance: the sum of the squared deviations, divided by n-1 */
820 for (i = 0; i < requests; i++) {
821 struct data s = stats[i];
823 a = ((double)s.time - meantot);
825 a = ((double)s.ctime - meancon);
827 a = ((double)s.time - (double)s.ctime - meand);
829 a = ((double)s.waittime - meanwait);
833 sdtot = (requests > 1) ? sqrt(sdtot / (requests - 1)) : 0;
834 sdcon = (requests > 1) ? sqrt(sdcon / (requests - 1)) : 0;
835 sdd = (requests > 1) ? sqrt(sdd / (requests - 1)) : 0;
836 sdwait = (requests > 1) ? sqrt(sdwait / (requests - 1)) : 0;
839 FILE *out = fopen(gnuplot, "w");
842 char tmstring[1024];/* XXXX */
844 perror("Cannot open gnuplot output file");
847 fprintf(out, "starttime\tseconds\tctime\tdtime\tttime\twait\n");
848 for (i = 0; i < requests; i++) {
849 apr_time_t diff = stats[i].time - stats[i].ctime;
851 sttime = stats[i].starttime;
852 (void) apr_ctime(tmstring, sttime);
853 fprintf(out, "%s\t%" APR_TIME_T_FMT "\t%" APR_TIME_T_FMT "\t%" APR_TIME_T_FMT "\t%" APR_TIME_T_FMT "\t%" APR_TIME_T_FMT "\n",
864 * XXX: what is better; this hideous cast of the compradre function; or
865 * the four warnings during compile ? dirkx just does not know and
868 qsort(stats, requests, sizeof(struct data),
869 (int (*) (const void *, const void *)) compradre);
870 if ((requests > 1) && (requests % 2))
871 mediancon = (stats[requests / 2].ctime + stats[requests / 2 + 1].ctime) / 2;
873 mediancon = stats[requests / 2].ctime;
875 qsort(stats, requests, sizeof(struct data),
876 (int (*) (const void *, const void *)) compri);
877 if ((requests > 1) && (requests % 2))
878 mediand = (stats[requests / 2].time + stats[requests / 2 + 1].time \
879 -stats[requests / 2].ctime - stats[requests / 2 + 1].ctime) / 2;
881 mediand = stats[requests / 2].time - stats[requests / 2].ctime;
883 qsort(stats, requests, sizeof(struct data),
884 (int (*) (const void *, const void *)) compwait);
885 if ((requests > 1) && (requests % 2))
886 medianwait = (stats[requests / 2].waittime + stats[requests / 2 + 1].waittime) / 2;
888 medianwait = stats[requests / 2].waittime;
890 qsort(stats, requests, sizeof(struct data),
891 (int (*) (const void *, const void *)) comprando);
892 if ((requests > 1) && (requests % 2))
893 mediantot = (stats[requests / 2].time + stats[requests / 2 + 1].time) / 2;
895 mediantot = stats[requests / 2].time;
897 printf("\nConnection Times (ms)\n");
900 #define CONF_FMT_STRING "%5" APR_TIME_T_FMT " %4d %5.1f %6" APR_TIME_T_FMT " %7" APR_TIME_T_FMT "\n"
901 printf(" min mean[+/-sd] median max\n");
902 printf("Connect: " CONF_FMT_STRING,
903 mincon, (int) (meancon + 0.5), sdcon, mediancon, maxcon);
904 printf("Processing: " CONF_FMT_STRING,
905 mind, (int) (meand + 0.5), sdd, mediand, maxd);
906 printf("Waiting: " CONF_FMT_STRING,
907 minwait, (int) (meanwait + 0.5), sdwait, medianwait, maxwait);
908 printf("Total: " CONF_FMT_STRING,
909 mintot, (int) (meantot + 0.5), sdtot, mediantot, maxtot);
910 #undef CONF_FMT_STRING
912 #define SANE(what,mean,median,sd) \
914 double d = (double)mean - median; \
917 printf("ERROR: The median and mean for " what " are more than twice the standard\n" \
918 " deviation apart. These results are NOT reliable.\n"); \
920 printf("WARNING: The median and mean for " what " are not within a normal deviation\n" \
921 " These results are probably not that reliable.\n"); \
923 SANE("the initial connection time", meancon, mediancon, sdcon);
924 SANE("the processing time", meand, mediand, sdd);
925 SANE("the waiting time", meanwait, medianwait, sdwait);
926 SANE("the total time", meantot, mediantot, sdtot);
929 printf(" min avg max\n");
930 #define CONF_FMT_STRING "%5" APR_TIME_T_FMT " %5" APR_TIME_T_FMT "%5" APR_TIME_T_FMT "\n"
931 printf("Connect: " CONF_FMT_STRING,
932 mincon, meancon, maxcon);
933 printf("Processing: " CONF_FMT_STRING,
934 mintot - mincon, meantot - meancon, maxtot - maxcon);
935 printf("Total: " CONF_FMT_STRING,
936 mintot, meantot, maxtot);
937 #undef CONF_FMT_STRING
941 /* Sorted on total connect times */
942 if (percentile && (requests > 1)) {
943 printf("\nPercentage of the requests served within a certain time (ms)\n");
944 for (i = 0; i < sizeof(percs) / sizeof(int); i++) {
946 printf(" 0%% <0> (never)\n");
947 else if (percs[i] >= 100)
948 printf(" 100%% %5" APR_TIME_T_FMT " (longest request)\n",
949 stats[requests - 1].time);
951 printf(" %d%% %5" APR_TIME_T_FMT "\n", percs[i],
952 stats[(int) (requests * percs[i] / 100)].time);
956 FILE *out = fopen(csvperc, "w");
959 perror("Cannot open CSV output file");
962 fprintf(out, "" "Percentage served" "," "Time in ms" "\n");
963 for (i = 0; i < 100; i++) {
968 t = stats[requests - 1].time;
970 t = stats[(int) (0.5 + requests * i / 100.0)].time;
971 fprintf(out, "%d,%e\n", i, (double)t);
983 /* --------------------------------------------------------- */
985 /* calculate and output results in HTML */
987 static void output_html_results(void)
991 endtime = apr_time_now();
992 timetaken = (long)((endtime - start) / 1000);
994 printf("\n\n<table %s>\n", tablestring);
995 printf("<tr %s><th colspan=2 %s>Server Software:</th>"
996 "<td colspan=2 %s>%s</td></tr>\n",
997 trstring, tdstring, tdstring, servername);
998 printf("<tr %s><th colspan=2 %s>Server Hostname:</th>"
999 "<td colspan=2 %s>%s</td></tr>\n",
1000 trstring, tdstring, tdstring, hostname);
1001 printf("<tr %s><th colspan=2 %s>Server Port:</th>"
1002 "<td colspan=2 %s>%hd</td></tr>\n",
1003 trstring, tdstring, tdstring, port);
1004 printf("<tr %s><th colspan=2 %s>Document Path:</th>"
1005 "<td colspan=2 %s>%s</td></tr>\n",
1006 trstring, tdstring, tdstring, path);
1007 printf("<tr %s><th colspan=2 %s>Document Length:</th>"
1008 "<td colspan=2 %s>%" APR_SIZE_T_FMT " bytes</td></tr>\n",
1009 trstring, tdstring, tdstring, doclen);
1010 printf("<tr %s><th colspan=2 %s>Concurrency Level:</th>"
1011 "<td colspan=2 %s>%d</td></tr>\n",
1012 trstring, tdstring, tdstring, concurrency);
1013 printf("<tr %s><th colspan=2 %s>Time taken for tests:</th>"
1014 "<td colspan=2 %s>%" APR_INT64_T_FMT ".%03ld seconds</td></tr>\n",
1015 trstring, tdstring, tdstring, apr_time_sec(timetaken),
1016 (long)apr_time_usec(timetaken));
1017 printf("<tr %s><th colspan=2 %s>Complete requests:</th>"
1018 "<td colspan=2 %s>%ld</td></tr>\n",
1019 trstring, tdstring, tdstring, done);
1020 printf("<tr %s><th colspan=2 %s>Failed requests:</th>"
1021 "<td colspan=2 %s>%ld</td></tr>\n",
1022 trstring, tdstring, tdstring, bad);
1024 printf("<tr %s><td colspan=4 %s > (Connect: %d, Length: %d, Exceptions: %d)</td></tr>\n",
1025 trstring, tdstring, err_conn, err_length, err_except);
1027 printf("<tr %s><th colspan=2 %s>Non-2xx responses:</th>"
1028 "<td colspan=2 %s>%d</td></tr>\n",
1029 trstring, tdstring, tdstring, err_response);
1031 printf("<tr %s><th colspan=2 %s>Keep-Alive requests:</th>"
1032 "<td colspan=2 %s>%ld</td></tr>\n",
1033 trstring, tdstring, tdstring, doneka);
1034 printf("<tr %s><th colspan=2 %s>Total transferred:</th>"
1035 "<td colspan=2 %s>%ld bytes</td></tr>\n",
1036 trstring, tdstring, tdstring, totalread);
1038 printf("<tr %s><th colspan=2 %s>Total POSTed:</th>"
1039 "<td colspan=2 %s>%ld</td></tr>\n",
1040 trstring, tdstring, tdstring, totalposted);
1041 printf("<tr %s><th colspan=2 %s>HTML transferred:</th>"
1042 "<td colspan=2 %s>%ld bytes</td></tr>\n",
1043 trstring, tdstring, tdstring, totalbread);
1045 /* avoid divide by zero */
1047 printf("<tr %s><th colspan=2 %s>Requests per second:</th>"
1048 "<td colspan=2 %s>%.2f</td></tr>\n",
1049 trstring, tdstring, tdstring, 1000 * (float) (done) / timetaken);
1050 printf("<tr %s><th colspan=2 %s>Transfer rate:</th>"
1051 "<td colspan=2 %s>%.2f kb/s received</td></tr>\n",
1052 trstring, tdstring, tdstring, (float) (totalread) / timetaken);
1054 printf("<tr %s><td colspan=2 %s> </td>"
1055 "<td colspan=2 %s>%.2f kb/s sent</td></tr>\n",
1056 trstring, tdstring, tdstring,
1057 (float) (totalposted) / timetaken);
1058 printf("<tr %s><td colspan=2 %s> </td>"
1059 "<td colspan=2 %s>%.2f kb/s total</td></tr>\n",
1060 trstring, tdstring, tdstring,
1061 (float) (totalread + totalposted) / timetaken);
1065 /* work out connection times */
1067 apr_interval_time_t totalcon = 0, total = 0;
1068 apr_interval_time_t mincon = AB_MAX, mintot = AB_MAX;
1069 apr_interval_time_t maxcon = 0, maxtot = 0;
1071 for (i = 0; i < requests; i++) {
1072 struct data s = stats[i];
1073 mincon = ap_min(mincon, s.ctime);
1074 mintot = ap_min(mintot, s.time);
1075 maxcon = ap_max(maxcon, s.ctime);
1076 maxtot = ap_max(maxtot, s.time);
1077 totalcon += s.ctime;
1081 if (requests > 0) { /* avoid division by zero (if 0 requests) */
1082 printf("<tr %s><th %s colspan=4>Connnection Times (ms)</th></tr>\n",
1083 trstring, tdstring);
1084 printf("<tr %s><th %s> </th> <th %s>min</th> <th %s>avg</th> <th %s>max</th></tr>\n",
1085 trstring, tdstring, tdstring, tdstring, tdstring);
1086 printf("<tr %s><th %s>Connect:</th>"
1087 "<td %s>%5" APR_TIME_T_FMT "</td>"
1088 "<td %s>%5" APR_TIME_T_FMT "</td>"
1089 "<td %s>%5" APR_TIME_T_FMT "</td></tr>\n",
1090 trstring, tdstring, tdstring, mincon, tdstring, totalcon / requests, tdstring, maxcon);
1091 printf("<tr %s><th %s>Processing:</th>"
1092 "<td %s>%5" APR_TIME_T_FMT "</td>"
1093 "<td %s>%5" APR_TIME_T_FMT "</td>"
1094 "<td %s>%5" APR_TIME_T_FMT "</td></tr>\n",
1095 trstring, tdstring, tdstring, mintot - mincon, tdstring,
1096 (total / requests) - (totalcon / requests), tdstring, maxtot - maxcon);
1097 printf("<tr %s><th %s>Total:</th>"
1098 "<td %s>%5" APR_TIME_T_FMT "</td>"
1099 "<td %s>%5" APR_TIME_T_FMT "</td>"
1100 "<td %s>%5" APR_TIME_T_FMT "</td></tr>\n",
1101 trstring, tdstring, tdstring, mintot, tdstring, total / requests, tdstring, maxtot);
1103 printf("</table>\n");
1107 /* --------------------------------------------------------- */
1109 /* start asnchronous non-blocking connection */
1111 static void start_connect(struct connection * c)
1115 if (!(started < requests))
1125 apr_pool_destroy(c->ctx);
1126 apr_pool_create(&c->ctx, cntxt);
1128 if ((rv = apr_socket_create(&c->aprsock, destsa->family,
1129 SOCK_STREAM, 0, c->ctx)) != APR_SUCCESS) {
1130 apr_err("socket", rv);
1132 if ((rv = apr_socket_opt_set(c->aprsock, APR_SO_NONBLOCK, 1))
1134 apr_err("socket nonblock", rv);
1137 if (windowsize != 0) {
1138 rv = apr_socket_opt_set(c->aprsock, APR_SO_SNDBUF,
1140 if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
1141 apr_err("socket send buffer", rv);
1143 rv = apr_socket_opt_set(c->aprsock, APR_SO_RCVBUF,
1145 if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
1146 apr_err("socket receive buffer", rv);
1150 c->start = apr_time_now();
1156 if ((c->ssl = SSL_new(ssl_ctx)) == NULL) {
1157 BIO_printf(bio_err, "SSL_new failed.\n");
1158 ERR_print_errors(bio_err);
1162 apr_os_sock_get(&fd, c->aprsock);
1163 bio = BIO_new_socket(fd, BIO_NOCLOSE);
1164 SSL_set_bio(c->ssl, bio, bio);
1165 SSL_set_connect_state(c->ssl);
1166 if (verbosity >= 4) {
1167 BIO_set_callback(bio, ssl_print_cb);
1168 BIO_set_callback_arg(bio, bio_err);
1174 if ((rv = apr_socket_connect(c->aprsock, destsa)) != APR_SUCCESS) {
1175 if (APR_STATUS_IS_EINPROGRESS(rv)) {
1176 apr_pollfd_t new_pollfd;
1177 c->state = STATE_CONNECTING;
1179 new_pollfd.desc_type = APR_POLL_SOCKET;
1180 new_pollfd.reqevents = APR_POLLOUT;
1181 new_pollfd.desc.s = c->aprsock;
1182 new_pollfd.client_data = c;
1183 apr_pollset_add(readbits, &new_pollfd);
1187 apr_pollfd_t remove_pollfd;
1188 remove_pollfd.desc_type = APR_POLL_SOCKET;
1189 remove_pollfd.desc.s = c->aprsock;
1190 apr_pollset_remove(readbits, &remove_pollfd);
1191 apr_socket_close(c->aprsock);
1195 "\nTest aborted after 10 failures\n\n");
1196 apr_err("apr_socket_connect()", rv);
1198 c->state = STATE_UNCONNECTED;
1204 /* connected first time */
1205 c->state = STATE_CONNECTED;
1209 ssl_proceed_handshake(c);
1217 /* --------------------------------------------------------- */
1219 /* close down connection and save stats */
1221 static void close_connection(struct connection * c)
1223 if (c->read == 0 && c->keepalive) {
1225 * server has legitimately shut down an idle keep alive request
1228 good--; /* connection never happened */
1232 /* first time here */
1235 else if (c->bread != doclen) {
1240 if (done < requests) {
1242 if ((done) && heartbeatres && !(done % heartbeatres)) {
1243 fprintf(stderr, "Completed %ld requests\n", done);
1246 c->done = apr_time_now();
1248 s.starttime = c->start;
1249 s.ctime = ap_max(0, (c->connect - c->start) / 1000);
1250 s.time = ap_max(0, (c->done - c->start) / 1000);
1251 s.waittime = ap_max(0, (c->beginread - c->endwrite) / 1000);
1257 apr_pollfd_t remove_pollfd;
1258 remove_pollfd.desc_type = APR_POLL_SOCKET;
1259 remove_pollfd.desc.s = c->aprsock;
1260 apr_pollset_remove(readbits, &remove_pollfd);
1263 SSL_shutdown(c->ssl);
1268 apr_socket_close(c->aprsock);
1270 c->state = STATE_UNCONNECTED;
1277 /* --------------------------------------------------------- */
1279 /* read data from connection */
1281 static void read_connection(struct connection * c)
1284 apr_status_t status;
1286 char respcode[4]; /* 3 digits and null */
1291 status = SSL_read(c->ssl, buffer, r);
1293 int scode = SSL_get_error(c->ssl, status);
1295 if (scode == SSL_ERROR_ZERO_RETURN) {
1296 /* connection closed cleanly: */
1298 close_connection(c);
1300 else if (scode != SSL_ERROR_WANT_WRITE
1301 && scode != SSL_ERROR_WANT_READ) {
1302 /* some fatal error: */
1304 BIO_printf(bio_err, "SSL read failed - closing connection\n");
1305 ERR_print_errors(bio_err);
1306 close_connection(c);
1315 status = apr_socket_recv(c->aprsock, buffer, &r);
1316 if (APR_STATUS_IS_EAGAIN(status))
1318 else if (r == 0 && APR_STATUS_IS_EOF(status)) {
1320 close_connection(c);
1323 /* catch legitimate fatal apr_socket_recv errors */
1324 else if (status != APR_SUCCESS) {
1325 err_except++; /* XXX: is this the right error counter? */
1326 /* XXX: Should errors here be fatal, or should we allow a
1327 * certain number of them before completely failing? -aaron */
1328 apr_err("apr_socket_recv", status);
1334 c->beginread = apr_time_now();
1339 if (!c->gotheader) {
1342 apr_size_t space = CBUFFSIZE - c->cbx - 1; /* -1 allows for \0 term */
1343 int tocopy = (space < r) ? space : r;
1345 apr_size_t inbytes_left = space, outbytes_left = space;
1347 status = apr_xlate_conv_buffer(from_ascii, buffer, &inbytes_left,
1348 c->cbuff + c->cbx, &outbytes_left);
1349 if (status || inbytes_left || outbytes_left) {
1350 fprintf(stderr, "only simple translation is supported (%d/%u/%u)\n",
1351 status, inbytes_left, outbytes_left);
1355 memcpy(c->cbuff + c->cbx, buffer, space);
1356 #endif /* NOT_ASCII */
1359 c->cbuff[c->cbx] = 0; /* terminate for benefit of strstr */
1360 if (verbosity >= 2) {
1361 printf("LOG: header received:\n%s\n", c->cbuff);
1363 s = strstr(c->cbuff, "\r\n\r\n");
1365 * this next line is so that we talk to NCSA 1.5 which blatantly
1366 * breaks the http specifaction
1369 s = strstr(c->cbuff, "\n\n");
1374 /* read rest next time */
1379 /* header is in invalid or too big - close connection */
1380 apr_pollfd_t remove_pollfd;
1381 remove_pollfd.desc_type = APR_POLL_SOCKET;
1382 remove_pollfd.desc.s = c->aprsock;
1383 apr_pollset_remove(readbits, &remove_pollfd);
1384 apr_socket_close(c->aprsock);
1387 err("\nTest aborted after 10 failures\n\n");
1393 /* have full header */
1396 * this is first time, extract some interesting info
1399 p = strstr(c->cbuff, "Server:");
1409 * XXX: this parsing isn't even remotely HTTP compliant... but in
1410 * the interest of speed it doesn't totally have to be, it just
1411 * needs to be extended to handle whatever servers folks want to
1412 * test against. -djg
1415 /* check response code */
1416 part = strstr(c->cbuff, "HTTP"); /* really HTTP/1.x_ */
1417 if (part && strlen(part) > strlen("HTTP/1.x_")) {
1418 strncpy(respcode, (part + strlen("HTTP/1.x_")), 3);
1422 strcpy(respcode, "500");
1425 if (respcode[0] != '2') {
1428 printf("WARNING: Response code not 2xx (%s)\n", respcode);
1430 else if (verbosity >= 3) {
1431 printf("LOG: Response code = %s\n", respcode);
1434 *s = 0; /* terminate at end of header */
1436 (strstr(c->cbuff, "Keep-Alive")
1437 || strstr(c->cbuff, "keep-alive"))) { /* for benefit of MSIIS */
1439 cl = strstr(c->cbuff, "Content-Length:");
1440 /* handle NCSA, which sends Content-length: */
1442 cl = strstr(c->cbuff, "Content-length:");
1445 c->length = atoi(cl + 16);
1448 c->bread += c->cbx - (s + l - c->cbuff) + r - tocopy;
1449 totalbread += c->bread;
1453 /* outside header, everything we have read is entity body */
1458 if (c->keepalive && (c->bread >= c->length)) {
1459 /* finished a keep-alive connection */
1463 /* first time here */
1466 else if (c->bread != doclen) {
1470 if (done < requests) {
1473 if (done && heartbeatres && !(done % heartbeatres)) {
1474 fprintf(stderr, "Completed %ld requests\n", done);
1477 c->done = apr_time_now();
1479 s.starttime = c->start;
1480 s.ctime = ap_max(0, (c->connect - c->start) / 1000);
1481 s.waittime = ap_max(0, (c->beginread - c->endwrite) / 1000);
1482 s.time = ap_max(0, (c->done - c->start) / 1000);
1489 c->read = c->bread = 0;
1490 c->start = c->connect = apr_time_now(); /* zero connect time with keep-alive */
1495 /* --------------------------------------------------------- */
1499 static void test(void)
1504 apr_status_t status;
1505 int snprintf_res = 0;
1507 apr_size_t inbytes_left, outbytes_left;
1511 connecthost = apr_pstrdup(cntxt, proxyhost);
1512 connectport = proxyport;
1515 connecthost = apr_pstrdup(cntxt, hostname);
1520 printf("Benchmarking %s ", hostname);
1522 printf("[through %s:%d] ", proxyhost, proxyport);
1523 printf("(be patient)%s",
1524 (heartbeatres ? "\n" : "..."));
1528 now = apr_time_now();
1530 con = calloc(concurrency, sizeof(struct connection));
1532 stats = calloc(requests, sizeof(struct data));
1534 if ((status = apr_pollset_create(&readbits, concurrency, cntxt, 0)) != APR_SUCCESS) {
1535 apr_err("apr_pollset_create failed", status);
1540 snprintf_res = apr_snprintf(request, sizeof(_request),
1541 "%s %s HTTP/1.0\r\n"
1542 "User-Agent: ApacheBench/%s\r\n"
1547 (posting == 0) ? "GET" : "HEAD",
1548 (isproxy) ? fullurl : path,
1550 keepalive ? "Connection: Keep-Alive\r\n" : "",
1551 cookie, auth, host_field, colonhost, hdrs);
1554 snprintf_res = apr_snprintf(request, sizeof(_request),
1555 "POST %s HTTP/1.0\r\n"
1556 "User-Agent: ApacheBench/%s\r\n"
1560 "Content-length: %" APR_SIZE_T_FMT "\r\n"
1561 "Content-type: %s\r\n"
1564 (isproxy) ? fullurl : path,
1566 keepalive ? "Connection: Keep-Alive\r\n" : "",
1568 host_field, colonhost, postlen,
1569 (content_type[0]) ? content_type : "text/plain", hdrs);
1571 if (snprintf_res >= sizeof(_request)) {
1572 err("Request too long\n");
1576 printf("INFO: POST header == \n---\n%s\n---\n", request);
1578 reqlen = strlen(request);
1581 * Combine headers and (optional) post file into one contineous buffer
1584 char *buff = malloc(postlen + reqlen + 1);
1586 fprintf(stderr, "error creating request buffer: out of memory\n");
1589 strcpy(buff, request);
1590 memcpy(buff + reqlen, postdata, postlen);
1595 inbytes_left = outbytes_left = reqlen;
1596 status = apr_xlate_conv_buffer(to_ascii, request, &inbytes_left,
1597 request, &outbytes_left);
1598 if (status || inbytes_left || outbytes_left) {
1599 fprintf(stderr, "only simple translation is supported (%d/%u/%u)\n",
1600 status, inbytes_left, outbytes_left);
1603 #endif /* NOT_ASCII */
1605 /* This only needs to be done once */
1606 if ((rv = apr_sockaddr_info_get(&destsa, connecthost, APR_UNSPEC, connectport, 0, cntxt))
1609 apr_snprintf(buf, sizeof(buf),
1610 "apr_sockaddr_info_get() for %s", connecthost);
1614 /* ok - lets start */
1615 start = apr_time_now();
1618 /* Output the results if the user terminates the run early. */
1619 apr_signal(SIGINT, output_results);
1622 /* initialise lots of requests */
1623 for (i = 0; i < concurrency; i++) {
1625 start_connect(&con[i]);
1628 while (done < requests) {
1631 const apr_pollfd_t *pollresults;
1633 /* check for time limit expiry */
1634 now = apr_time_now();
1635 timed = (apr_int32_t)apr_time_sec(now - start);
1636 if (tlimit && timed >= tlimit) {
1637 requests = done; /* so stats are correct */
1638 break; /* no need to do another round */
1642 status = apr_pollset_poll(readbits, aprtimeout, &n, &pollresults);
1643 if (status != APR_SUCCESS)
1644 apr_err("apr_poll", status);
1647 err("\nServer timed out\n\n");
1650 for (i = 0; i < n; i++) {
1651 const apr_pollfd_t *next_fd = &(pollresults[i]);
1652 struct connection *c;
1654 c = next_fd->client_data;
1657 * If the connection isn't connected how can we check it?
1659 if (c->state == STATE_UNCONNECTED)
1662 rv = next_fd->rtnevents;
1665 if (c->state == STATE_CONNECTED && c->ssl && SSL_in_init(c->ssl)) {
1666 ssl_proceed_handshake(c);
1672 * Notes: APR_POLLHUP is set after FIN is received on some
1673 * systems, so treat that like APR_POLLIN so that we try to read
1676 * Some systems return APR_POLLERR with APR_POLLHUP. We need to
1677 * call read_connection() for APR_POLLHUP, so check for
1678 * APR_POLLHUP first so that a closed connection isn't treated
1679 * like an I/O error. If it is, we never figure out that the
1680 * connection is done and we loop here endlessly calling
1683 if ((rv & APR_POLLIN) || (rv & APR_POLLPRI) || (rv & APR_POLLHUP))
1685 if ((rv & APR_POLLERR) || (rv & APR_POLLNVAL)) {
1691 if (rv & APR_POLLOUT) {
1692 if (c->state == STATE_CONNECTING) {
1693 apr_pollfd_t remove_pollfd;
1694 rv = apr_socket_connect(c->aprsock, destsa);
1695 remove_pollfd.desc_type = APR_POLL_SOCKET;
1696 remove_pollfd.desc.s = c->aprsock;
1697 apr_pollset_remove(readbits, &remove_pollfd);
1698 if (rv != APR_SUCCESS) {
1699 apr_socket_close(c->aprsock);
1703 "\nTest aborted after 10 failures\n\n");
1704 apr_err("apr_socket_connect()", rv);
1706 c->state = STATE_UNCONNECTED;
1711 c->state = STATE_CONNECTED;
1715 ssl_proceed_handshake(c);
1727 * When using a select based poll every time we check the bits
1728 * are reset. In 1.3's ab we copied the FD_SET's each time
1729 * through, but here we're going to check the state and if the
1730 * connection is in STATE_READ or STATE_CONNECTING we'll add the
1731 * socket back in as APR_POLLIN.
1733 if (c->state == STATE_READ) {
1734 apr_pollfd_t new_pollfd;
1735 new_pollfd.desc_type = APR_POLL_SOCKET;
1736 new_pollfd.reqevents = APR_POLLIN;
1737 new_pollfd.desc.s = c->aprsock;
1738 new_pollfd.client_data = c;
1739 apr_pollset_add(readbits, &new_pollfd);
1745 fprintf(stderr, "Finished %ld requests\n", done);
1750 output_html_results();
1755 /* ------------------------------------------------------- */
1757 /* display copyright information */
1758 static void copyright(void)
1761 printf("This is ApacheBench, Version %s\n", AP_AB_BASEREVISION " <$Revision$>");
1762 printf("Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\n");
1763 printf("Copyright 1997-2005 The Apache Software Foundation, http://www.apache.org/\n");
1768 printf(" This is ApacheBench, Version %s <i><%s></i><br>\n", AP_AB_BASEREVISION, "$Revision$");
1769 printf(" Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/<br>\n");
1770 printf(" Copyright 1997-2005 The Apache Software Foundation, http://www.apache.org/<br>\n");
1771 printf("</p>\n<p>\n");
1775 /* display usage information */
1776 static void usage(const char *progname)
1778 fprintf(stderr, "Usage: %s [options] [http"
1782 "://]hostname[:port]/path\n", progname);
1783 fprintf(stderr, "Options are:\n");
1784 fprintf(stderr, " -n requests Number of requests to perform\n");
1785 fprintf(stderr, " -c concurrency Number of multiple requests to make\n");
1786 fprintf(stderr, " -t timelimit Seconds to max. wait for responses\n");
1787 fprintf(stderr, " -b windowsize Size of TCP send/receive buffer, in bytes\n");
1788 fprintf(stderr, " -p postfile File containing data to POST\n");
1789 fprintf(stderr, " -T content-type Content-type header for POSTing\n");
1790 fprintf(stderr, " -v verbosity How much troubleshooting info to print\n");
1791 fprintf(stderr, " -w Print out results in HTML tables\n");
1792 fprintf(stderr, " -i Use HEAD instead of GET\n");
1793 fprintf(stderr, " -x attributes String to insert as table attributes\n");
1794 fprintf(stderr, " -y attributes String to insert as tr attributes\n");
1795 fprintf(stderr, " -z attributes String to insert as td or th attributes\n");
1796 fprintf(stderr, " -C attribute Add cookie, eg. 'Apache=1234. (repeatable)\n");
1797 fprintf(stderr, " -H attribute Add Arbitrary header line, eg. 'Accept-Encoding: gzip'\n");
1798 fprintf(stderr, " Inserted after all normal header lines. (repeatable)\n");
1799 fprintf(stderr, " -A attribute Add Basic WWW Authentication, the attributes\n");
1800 fprintf(stderr, " are a colon separated username and password.\n");
1801 fprintf(stderr, " -P attribute Add Basic Proxy Authentication, the attributes\n");
1802 fprintf(stderr, " are a colon separated username and password.\n");
1803 fprintf(stderr, " -X proxy:port Proxyserver and port number to use\n");
1804 fprintf(stderr, " -V Print version number and exit\n");
1805 fprintf(stderr, " -k Use HTTP KeepAlive feature\n");
1806 fprintf(stderr, " -d Do not show percentiles served table.\n");
1807 fprintf(stderr, " -S Do not show confidence estimators and warnings.\n");
1808 fprintf(stderr, " -g filename Output collected data to gnuplot format file.\n");
1809 fprintf(stderr, " -e filename Output CSV file with percentages served\n");
1810 fprintf(stderr, " -h Display usage information (this message)\n");
1812 fprintf(stderr, " -Z ciphersuite Specify SSL/TLS cipher suite (See openssl ciphers)\n");
1813 fprintf(stderr, " -f protocol Specify SSL/TLS protocol (SSL2, SSL3, TLS1, or ALL)\n");
1818 /* ------------------------------------------------------- */
1820 /* split URL into parts */
1822 static int parse_url(char *url)
1829 /* Save a copy for the proxy */
1830 fullurl = apr_pstrdup(cntxt, url);
1832 if (strlen(url) > 7 && strncmp(url, "http://", 7) == 0) {
1840 if (strlen(url) > 8 && strncmp(url, "https://", 8) == 0) {
1845 if (strlen(url) > 8 && strncmp(url, "https://", 8) == 0) {
1846 fprintf(stderr, "SSL not compiled in; no https support\n");
1851 if ((cp = strchr(url, '/')) == NULL)
1853 h = apr_palloc(cntxt, cp - url + 1);
1854 memcpy(h, url, cp - url);
1856 rv = apr_parse_addr_port(&hostname, &scope_id, &port, h, cntxt);
1857 if (rv != APR_SUCCESS || !hostname || scope_id) {
1860 path = apr_pstrdup(cntxt, cp);
1862 if (*url == '[') { /* IPv6 numeric address string */
1863 host_field = apr_psprintf(cntxt, "[%s]", hostname);
1866 host_field = hostname;
1869 if (port == 0) { /* no port specified */
1880 is_ssl && (port != 443)) || (!is_ssl &&
1884 colonhost = apr_psprintf(cntxt,":%d",port);
1890 /* ------------------------------------------------------- */
1892 /* read data to POST from file, save contents and length */
1894 static int open_postfile(const char *pfile)
1901 rv = apr_file_open(&postfd, pfile, APR_READ, APR_OS_DEFAULT, cntxt);
1902 if (rv != APR_SUCCESS) {
1903 fprintf(stderr, "ab: Could not open POST data file (%s): %s\n", pfile,
1904 apr_strerror(rv, errmsg, sizeof errmsg));
1908 apr_file_info_get(&finfo, APR_FINFO_NORM, postfd);
1909 postlen = (apr_size_t)finfo.size;
1910 postdata = malloc(postlen);
1912 fprintf(stderr, "ab: Could not allocate POST data buffer\n");
1915 rv = apr_file_read_full(postfd, postdata, postlen, NULL);
1916 if (rv != APR_SUCCESS) {
1917 fprintf(stderr, "ab: Could not read POST data file: %s\n",
1918 apr_strerror(rv, errmsg, sizeof errmsg));
1921 apr_file_close(postfd);
1925 /* ------------------------------------------------------- */
1927 /* sort out command-line args and call test */
1928 int main(int argc, const char * const argv[])
1932 apr_status_t status;
1937 SSL_METHOD *meth = SSLv23_client_method();
1940 /* table defaults */
1943 tdstring = "bgcolor=white";
1946 proxyhost[0] = '\0';
1949 apr_app_initialize(&argc, &argv, NULL);
1950 atexit(apr_terminate);
1951 apr_pool_create(&cntxt, NULL);
1954 status = apr_xlate_open(&to_ascii, "ISO-8859-1", APR_DEFAULT_CHARSET, cntxt);
1956 fprintf(stderr, "apr_xlate_open(to ASCII)->%d\n", status);
1959 status = apr_xlate_open(&from_ascii, APR_DEFAULT_CHARSET, "ISO-8859-1", cntxt);
1961 fprintf(stderr, "apr_xlate_open(from ASCII)->%d\n", status);
1964 status = apr_base64init_ebcdic(to_ascii, from_ascii);
1966 fprintf(stderr, "apr_base64init_ebcdic()->%d\n", status);
1971 apr_getopt_init(&opt, cntxt, argc, argv);
1972 while ((status = apr_getopt(opt, "n:c:t:b:T:p:v:kVhwix:y:z:C:H:P:A:g:X:de:Sq"
1976 ,&c, &optarg)) == APR_SUCCESS) {
1979 requests = atoi(optarg);
1981 err("Invalid number of requests\n");
1991 concurrency = atoi(optarg);
1994 windowsize = atoi(optarg);
1998 err("Cannot mix POST and HEAD\n");
2002 gnuplot = strdup(optarg);
2008 csvperc = strdup(optarg);
2015 err("Cannot mix POST and HEAD\n");
2016 if (0 == (r = open_postfile(optarg))) {
2019 else if (postdata) {
2024 verbosity = atoi(optarg);
2027 tlimit = atoi(optarg);
2028 requests = MAX_REQUESTS; /* need to size data array on
2032 strcpy(content_type, optarg);
2035 cookie = apr_pstrcat(cntxt, "Cookie: ", optarg, "\r\n", NULL);
2039 * assume username passwd already to be in colon separated form.
2040 * Ready to be uu-encoded.
2042 while (apr_isspace(*optarg))
2044 if (apr_base64_encode_len(strlen(optarg)) > sizeof(tmp)) {
2045 err("Authentication credentials too long\n");
2047 l = apr_base64_encode(tmp, optarg, strlen(optarg));
2050 auth = apr_pstrcat(cntxt, auth, "Authorization: Basic ", tmp,
2055 * assume username passwd already to be in colon separated form.
2057 while (apr_isspace(*optarg))
2059 if (apr_base64_encode_len(strlen(optarg)) > sizeof(tmp)) {
2060 err("Proxy credentials too long\n");
2062 l = apr_base64_encode(tmp, optarg, strlen(optarg));
2065 auth = apr_pstrcat(cntxt, auth, "Proxy-Authorization: Basic ",
2069 hdrs = apr_pstrcat(cntxt, hdrs, optarg, "\r\n", NULL);
2075 * if any of the following three are used, turn on html output
2080 tablestring = optarg;
2086 * assume proxy-name[:port]
2088 if ((p = strchr(optarg, ':'))) {
2091 proxyport = atoi(p);
2093 strcpy(proxyhost, optarg);
2113 ssl_cipher = strdup(optarg);
2116 if (strncasecmp(optarg, "ALL", 3) == 0) {
2117 meth = SSLv23_client_method();
2118 } else if (strncasecmp(optarg, "SSL2", 4) == 0) {
2119 meth = SSLv2_client_method();
2120 } else if (strncasecmp(optarg, "SSL3", 4) == 0) {
2121 meth = SSLv3_client_method();
2122 } else if (strncasecmp(optarg, "TLS1", 4) == 0) {
2123 meth = TLSv1_client_method();
2130 if (opt->ind != argc - 1) {
2131 fprintf(stderr, "%s: wrong number of arguments\n", argv[0]);
2135 if (parse_url(apr_pstrdup(cntxt, opt->argv[opt->ind++]))) {
2136 fprintf(stderr, "%s: invalid URL\n", argv[0]);
2140 if ((concurrency < 0) || (concurrency > MAX_CONCURRENCY)) {
2141 fprintf(stderr, "%s: Invalid Concurrency [Range 0..%d]\n",
2142 argv[0], MAX_CONCURRENCY);
2146 if (concurrency > requests) {
2147 fprintf(stderr, "%s: Cannot use concurrency level greater than "
2148 "total number of requests\n", argv[0]);
2152 if ((heartbeatres) && (requests > 150)) {
2153 heartbeatres = requests / 10; /* Print line every 10% of requests */
2154 if (heartbeatres < 100)
2155 heartbeatres = 100; /* but never more often than once every 100
2165 CRYPTO_malloc_init();
2167 SSL_load_error_strings();
2169 bio_out=BIO_new_fp(stdout,BIO_NOCLOSE);
2170 bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
2172 if (!(ssl_ctx = SSL_CTX_new(meth))) {
2173 BIO_printf(bio_err, "Could not initialize SSL Context.\n");
2174 ERR_print_errors(bio_err);
2177 SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL);
2178 if (ssl_cipher != NULL) {
2179 if (!SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher)) {
2180 fprintf(stderr, "error setting cipher list [%s]\n", ssl_cipher);
2181 ERR_print_errors_fp(stderr);
2185 if (verbosity >= 3) {
2186 SSL_CTX_set_info_callback(ssl_ctx, ssl_state_cb);
2190 apr_signal(SIGPIPE, SIG_IGN); /* Ignore writes to connections that
2191 * have been closed at the other end. */
2195 apr_pool_destroy(cntxt);