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
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_recv() (thereby allowing AB to
65 ** manage its entire set of socket descriptors).
66 ** - Any error returned from apr_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 /* Note: this version string should start with \d+[\d\.]* and be a valid
86 * string for an HTTP Agent: header when prefixed with 'ApacheBench/'.
87 * It should reflect the version of AB - and not that of the apache server
88 * it happens to accompany. And it should be updated or changed whenever
89 * the results are no longer fundamentally comparable to the results of
90 * a previous version of ab. Either due to a change in the logic of
91 * ab - or to due to a change in the distribution it is compiled with
92 * (such as an APR change in for example blocking).
94 #define AP_AB_BASEREVISION "2.0.41-dev"
100 * - has various other poor buffer attacks related to the lazy parsing of
101 * response headers from the server
102 * - doesn't implement much of HTTP/1.x, only accepts certain forms of
104 * - (performance problem) heavy use of strstr shows up top in profile
105 * only an issue for loopback usage
108 /* -------------------------------------------------------------------- */
111 /* Hmmm... This source code isn't being compiled in ASCII.
112 * In order for data that flows over the network to make
113 * sense, we need to translate to/from ASCII.
118 /* affects include files on Solaris */
122 #include "apr_signal.h"
123 #include "apr_strings.h"
124 #include "apr_network_io.h"
125 #include "apr_file_io.h"
126 #include "apr_time.h"
127 #include "apr_getopt.h"
128 #include "apr_general.h"
130 #include "apr_portable.h"
131 #include "ap_release.h"
132 #include "apr_poll.h"
134 #define APR_WANT_STRFUNC
135 #include "apr_want.h"
137 #include "apr_base64.h"
139 #include "apr_xlate.h"
144 #if APR_HAVE_STDLIB_H
148 #if ((!(RSAREF)) && (!(SYSSSL)))
149 /* Libraries on most systems.. */
150 #include <openssl/rsa.h>
151 #include <openssl/crypto.h>
152 #include <openssl/x509.h>
153 #include <openssl/pem.h>
154 #include <openssl/err.h>
155 #include <openssl/ssl.h>
156 #include <openssl/rand.h>
158 /* Libraries for RSAref and SYSSSL */
175 /* ------------------- DEFINITIONS -------------------------- */
178 #define AB_MAX APR_INT64_C(0x7fffffffffffffff)
180 #define AB_MAX LLONG_MAX
183 /* maximum number of requests on a time limited test */
184 #define MAX_REQUESTS 50000
186 /* good old state hostname */
187 #define STATE_UNCONNECTED 0
188 #define STATE_CONNECTING 1 /* TCP connect initiated, but we don't
189 * know if it worked yet
191 #define STATE_CONNECTED 2 /* we know TCP connect completed */
194 #define CBUFFSIZE (2048)
198 apr_socket_t *aprsock;
200 apr_size_t read; /* amount of bytes read */
201 apr_size_t bread; /* amount of body read */
202 apr_size_t rwrite, rwrote; /* keep pointers in what we write - across
204 apr_size_t length; /* Content-Length value used for keep-alive */
205 char cbuff[CBUFFSIZE]; /* a buffer to store server response header */
206 int cbx; /* offset in cbuffer */
207 int keepalive; /* non-zero if a keep-alive request */
208 int gotheader; /* non-zero if we have the entire header in
210 apr_time_t start, /* Start of connection */
211 connect, /* Connected, start writing */
212 endwrite, /* Request written */
213 beginread, /* First byte of input */
214 done; /* Connection closed */
224 /* XXXX insert SSL timings */
226 int read; /* number of bytes read */
227 apr_time_t starttime; /* start time of connection in seconds since
229 apr_interval_time_t waittime; /* Between writing request and reading
231 apr_interval_time_t ctime; /* time in ms to connect */
232 apr_interval_time_t time; /* time in ms for connection */
235 #define ap_min(a,b) ((a)<(b))?(a):(b)
236 #define ap_max(a,b) ((a)>(b))?(a):(b)
237 #define MAX_CONCURRENCY 20000
239 /* --------------------- GLOBALS ---------------------------- */
241 int verbosity = 0; /* no verbosity by default */
242 int posting = 0; /* GET by default */
243 int requests = 1; /* Number of requests to make */
244 int heartbeatres = 100; /* How often do we say we're alive */
245 int concurrency = 1; /* Number of multiple requests to make */
246 int percentile = 1; /* Show percentile served */
247 int confidence = 1; /* Show confidence estimator and warnings */
248 int tlimit = 0; /* time limit in secs */
249 int keepalive = 0; /* try and do keepalive connections */
250 char servername[1024]; /* name that server reports */
251 char *hostname; /* host name from URL */
252 char *host_field; /* value of "Host:" header field */
253 char *path; /* path name */
254 char postfile[1024]; /* name of file containing post data */
255 char *postdata; /* *buffer containing data from postfile */
256 apr_size_t postlen = 0; /* length of data to be POSTed */
257 char content_type[1024]; /* content type to put in POST header */
258 char *cookie, /* optional cookie line */
259 *auth, /* optional (basic/uuencoded) auhentication */
260 *hdrs; /* optional arbitrary headers */
261 apr_port_t port; /* port number */
262 char proxyhost[1024]; /* proxy host name */
263 int proxyport = 0; /* proxy port */
265 apr_port_t connectport;
266 char *gnuplot; /* GNUplot file */
267 char *csvperc; /* CSV Percentile file */
269 char * fullurl, * colonhost;
271 apr_interval_time_t aprtimeout = apr_time_from_sec(30); /* timeout value */
273 * XXX - this is now a per read/write transact type of value
276 int use_html = 0; /* use html in the report */
277 const char *tablestring;
278 const char *trstring;
279 const char *tdstring;
281 apr_size_t doclen = 0; /* the length the document should be */
282 long started = 0; /* number of requests started, so no excess */
283 long totalread = 0; /* total number of bytes read */
284 long totalbread = 0; /* totoal amount of entity body read */
285 long totalposted = 0; /* total number of bytes posted, inc. headers */
286 long done = 0; /* number of requests we have done */
287 long doneka = 0; /* number of keep alive connections done */
288 long good = 0, bad = 0; /* number of good and bad requests */
289 long epipe = 0; /* number of broken pipe writes */
294 BIO *bio_out,*bio_err;
295 static void write_request(struct connection * c);
298 /* store error cases */
299 int err_length = 0, err_conn = 0, err_except = 0;
300 int err_response = 0;
302 apr_time_t start, endtime;
304 /* global request (and its length) */
306 char *request = _request;
309 /* one global throw-away buffer to read stuff into */
312 /* interesting percentiles */
313 int percs[] = {50, 66, 75, 80, 90, 95, 98, 99, 100};
315 struct connection *con; /* connection array */
316 struct data *stats; /* date for each request */
319 apr_pollset_t *readbits;
321 apr_sockaddr_t *destsa;
324 apr_xlate_t *from_ascii, *to_ascii;
327 static void close_connection(struct connection * c);
328 /* --------------------------------------------------------- */
330 /* simple little function to write an error string and exit */
332 static void err(char *s)
334 fprintf(stderr, "%s\n", s);
336 printf("Total of %ld requests completed\n" , done);
340 /* simple little function to write an APR error string and exit */
342 static void apr_err(char *s, apr_status_t rv)
348 s, apr_strerror(rv, buf, sizeof buf), rv);
350 printf("Total of %ld requests completed\n" , done);
354 #if defined(USE_SSL) && USE_THREADS
356 * To ensure thread-safetyness in OpenSSL - work in progress
359 static apr_thread_mutex_t **lock_cs;
360 static int lock_num_locks;
362 static void ssl_util_thr_lock(int mode, int type,
363 const char *file, int line)
365 if (type < lock_num_locks) {
366 if (mode & CRYPTO_LOCK) {
367 apr_thread_mutex_lock(lock_cs[type]);
370 apr_thread_mutex_unlock(lock_cs[type]);
375 static unsigned long ssl_util_thr_id(void)
377 /* OpenSSL needs this to return an unsigned long. On OS/390, the pthread
378 * id is a structure twice that big. Use the TCB pointer instead as a
379 * unique unsigned long.
384 unsigned long PSATOLD;
387 return psaptr->PSATOLD;
389 return (unsigned long) apr_os_thread_current();
393 static apr_status_t ssl_util_thread_cleanup(void *data)
395 CRYPTO_set_locking_callback(NULL);
397 /* Let the registered mutex cleanups do their own thing
402 void ssl_util_thread_setup(apr_pool_t *p)
406 lock_num_locks = CRYPTO_num_locks();
407 lock_cs = apr_palloc(p, lock_num_locks * sizeof(*lock_cs));
409 for (i = 0; i < lock_num_locks; i++) {
410 apr_thread_mutex_create(&(lock_cs[i]), APR_THREAD_MUTEX_DEFAULT, p);
413 CRYPTO_set_id_callback(ssl_util_thr_id);
415 CRYPTO_set_locking_callback(ssl_util_thr_lock);
417 apr_pool_cleanup_register(p, NULL, ssl_util_thread_cleanup,
418 apr_pool_cleanup_null);
422 /* --------------------------------------------------------- */
423 /* write out request to a connection - assumes we can write
424 * (small) request out in one go into our new socket buffer
428 long ssl_print_cb(BIO *bio,int cmd,const char *argp,int argi,long argl,long ret)
432 out=(BIO *)BIO_get_callback_arg(bio);
433 if (out == NULL) return(ret);
435 if (cmd == (BIO_CB_READ|BIO_CB_RETURN))
437 BIO_printf(out,"read from %08X [%08lX] (%d bytes => %ld (0x%X))\n",
438 bio,argp,argi,ret,ret);
439 BIO_dump(out,(char *)argp,(int)ret);
442 else if (cmd == (BIO_CB_WRITE|BIO_CB_RETURN))
444 BIO_printf(out,"write to %08X [%08lX] (%d bytes => %ld (0x%X))\n",
445 bio,argp,argi,ret,ret);
446 BIO_dump(out,(char *)argp,(int)ret);
453 #define RAND_MAX INT_MAX
456 static int ssl_rand_choosenum(int l, int h)
461 srand((unsigned int)time(NULL));
462 apr_snprintf(buf, sizeof(buf), "%.0f",
463 (((double)(rand()%RAND_MAX)/RAND_MAX)*(h-l)));
476 unsigned char stackdata[256];
479 * seed in the current time (usually just 4 bytes)
483 RAND_seed((unsigned char *)&t, l);
487 * seed in the current process id (usually just 4 bytes)
491 RAND_seed((unsigned char *)&pid, l);
495 * seed in some current state of the run-time stack (128 bytes)
497 n = ssl_rand_choosenum(0, sizeof(stackdata)-128-1);
498 RAND_seed(stackdata+n, 128);
502 int ssl_print_connection_info(bio,ssl)
509 c=SSL_get_current_cipher(ssl);
510 BIO_printf(bio,"Cipher Suite Protocol :%s\n", SSL_CIPHER_get_version(c));
511 BIO_printf(bio,"Cipher Suite Name :%s\n",SSL_CIPHER_get_name(c));
513 bits=SSL_CIPHER_get_bits(c,&alg_bits);
514 BIO_printf(bio,"Cipher Suite Cipher Bits:%d (%d)\n",bits,alg_bits);
519 int ssl_print_cert_info(bio,x509cert)
526 BIO_printf(bio,"Certificate version: %d\n",X509_get_version(x509cert)+1);
528 BIO_printf(bio,"Valid from: ");
529 ASN1_UTCTIME_print(bio, X509_get_notBefore(x509cert));
530 BIO_printf(bio,"\n");
532 BIO_printf(bio,"Valid to : ");
533 ASN1_UTCTIME_print(bio, X509_get_notAfter(x509cert));
534 BIO_printf(bio,"\n");
536 BIO_printf(bio,"Public key is %d bits\n",
537 EVP_PKEY_bits(X509_get_pubkey(x509cert)));
539 dn=X509_get_issuer_name(x509cert);
540 X509_NAME_oneline(dn, buf, BUFSIZ);
541 BIO_printf(bio,"The issuer name is %s\n", buf);
543 dn=X509_get_subject_name(x509cert);
544 X509_NAME_oneline(dn, buf, BUFSIZ);
545 BIO_printf(bio,"The subject name is %s\n", buf);
547 /* dump the extension list too */
548 BIO_printf(bio,"Extension Count: %d\n",X509_get_ext_count(x509cert));
553 void ssl_start_connect(struct connection * c)
562 int i, count, hdone = 0;
563 char ssl_hostname[80];
565 /* XXX - Verify if it's okay - TBD */
566 if (requests < concurrency)
567 requests = concurrency;
569 if (!(started < requests))
579 apr_pool_destroy(c->ctx);
580 apr_pool_create(&c->ctx, cntxt);
582 if ((c->ssl=SSL_new(ctx)) == NULL)
584 BIO_printf(bio_err,"SSL_new failed\n");
590 c->start = apr_time_now();
591 memset(ssl_hostname, 0, 80);
592 sprintf(ssl_hostname, "%s:%d", hostname, port);
594 if ((bio = BIO_new_connect(ssl_hostname)) == NULL)
596 BIO_printf(bio_err,"BIO_new_connect failed\n");
599 SSL_set_bio(c->ssl,bio,bio);
600 SSL_set_connect_state(c->ssl);
604 BIO_set_callback(bio,ssl_print_cb);
605 BIO_set_callback_arg(bio,(void*)bio_err);
610 i = SSL_do_handshake(c->ssl);
612 switch (SSL_get_error(c->ssl,i))
618 case SSL_ERROR_SYSCALL:
619 BIO_printf(bio_err,"SSL connection failed\n");
621 c->state = STATE_UNCONNECTED;
624 BIO_printf(bio_err,"\nTest aborted after 10 failures\n\n");
628 case SSL_ERROR_WANT_READ:
629 case SSL_ERROR_WANT_WRITE:
630 case SSL_ERROR_WANT_CONNECT:
631 BIO_printf(bio_err, "Waiting .. sleep(1)\n");
632 apr_sleep(apr_time_from_sec(1));
633 c->state = STATE_CONNECTED;
636 case SSL_ERROR_ZERO_RETURN:
637 BIO_printf(bio_err,"socket closed\n");
644 BIO_printf(bio_err, "\n");
645 sk = SSL_get_peer_cert_chain(c->ssl);
647 if ((count = sk_num(sk)) > 0)
649 if ((count = sk_X509_num(sk)) > 0)
652 for (i=1; i<count; i++)
655 x509cert = (X509 *)sk_value(sk,i);
657 x509cert = (X509 *)sk_X509_value(sk,i);
659 ssl_print_cert_info(bio_out,x509cert);
664 x509cert = SSL_get_peer_certificate(c->ssl);
665 if (x509cert == NULL)
666 BIO_printf(bio_out, "Anon DH\n");
669 BIO_printf(bio_out, "Peer certificate\n");
670 ssl_print_cert_info(bio_out,x509cert);
674 ssl_print_connection_info(bio_err,c->ssl);
675 SSL_SESSION_print(bio_err,SSL_get_session(c->ssl));
678 /* connected first time */
684 static void write_request(struct connection * c)
687 apr_time_t tnow = apr_time_now();
688 apr_size_t l = c->rwrite;
694 if (c->rwrite == 0) {
698 apr_socket_timeout_set(c->aprsock, 0);
703 c->rwrite += postlen;
705 else if (tnow > c->connect + aprtimeout) {
706 printf("Send request timed out!\n");
714 e_ssl = SSL_write(c->ssl,request + c->rwrote, l);
717 printf("SSL write failed - closing connection\n");
718 close_connection (c);
725 e = apr_send(c->aprsock, request + c->rwrote, &l);
728 * Bail early on the most common case
736 if (e != APR_SUCCESS) {
738 * Let's hope this traps EWOULDBLOCK too !
740 if (!APR_STATUS_IS_EAGAIN(e)) {
742 printf("Send request failed!\n");
751 totalposted += c->rwrite;
752 c->state = STATE_READ;
753 c->endwrite = apr_time_now();
758 apr_pollfd_t new_pollfd;
759 new_pollfd.desc_type = APR_POLL_SOCKET;
760 new_pollfd.reqevents = APR_POLLIN;
761 new_pollfd.desc.s = c->aprsock;
762 new_pollfd.client_data = c;
763 apr_pollset_add(readbits, &new_pollfd);
767 /* --------------------------------------------------------- */
769 /* calculate and output results */
771 static int compradre(struct data * a, struct data * b)
773 if ((a->ctime) < (b->ctime))
775 if ((a->ctime) > (b->ctime))
780 static int comprando(struct data * a, struct data * b)
782 if ((a->time) < (b->time))
784 if ((a->time) > (b->time))
789 static int compri(struct data * a, struct data * b)
791 apr_interval_time_t p = a->time - a->ctime;
792 apr_interval_time_t q = b->time - b->ctime;
800 static int compwait(struct data * a, struct data * b)
802 if ((a->waittime) < (b->waittime))
804 if ((a->waittime) > (b->waittime))
809 static void output_results(void)
811 apr_interval_time_t timetakenusec;
814 endtime = apr_time_now();
815 timetakenusec = endtime - start;
816 timetaken = ((float)apr_time_sec(timetakenusec)) +
817 ((float)apr_time_usec(timetakenusec)) / 1000000.0F;
820 printf("Server Software: %s\n", servername);
821 printf("Server Hostname: %s\n", hostname);
822 printf("Server Port: %hd\n", port);
824 printf("Document Path: %s\n", path);
825 printf("Document Length: %" APR_SIZE_T_FMT " bytes\n", doclen);
827 printf("Concurrency Level: %d\n", concurrency);
828 printf("Time taken for tests: %ld.%03ld seconds\n",
829 (long) apr_time_sec(timetakenusec),
830 (long) apr_time_usec(timetakenusec));
831 printf("Complete requests: %ld\n", done);
832 printf("Failed requests: %ld\n", bad);
834 printf(" (Connect: %d, Length: %d, Exceptions: %d)\n",
835 err_conn, err_length, err_except);
836 printf("Write errors: %ld\n", epipe);
838 printf("Non-2xx responses: %d\n", err_response);
840 printf("Keep-Alive requests: %ld\n", doneka);
841 printf("Total transferred: %ld bytes\n", totalread);
843 printf("Total POSTed: %ld\n", totalposted);
844 printf("HTML transferred: %ld bytes\n", totalbread);
846 /* avoid divide by zero */
848 printf("Requests per second: %.2f [#/sec] (mean)\n",
849 (float) (done / timetaken));
850 printf("Time per request: %.3f [ms] (mean)\n",
851 (float) (1000 * concurrency * timetaken / done));
852 printf("Time per request: %.3f [ms] (mean, across all concurrent requests)\n",
853 (float) (1000 * timetaken / done));
854 printf("Transfer rate: %.2f [Kbytes/sec] received\n",
855 (float) (totalread / 1024 / timetaken));
857 printf(" %.2f kb/s sent\n",
858 (float) (totalposted / timetaken / 1024));
859 printf(" %.2f kb/s total\n",
860 (float) ((totalread + totalposted) / timetaken / 1024));
865 /* work out connection times */
867 apr_time_t totalcon = 0, total = 0, totald = 0, totalwait = 0;
868 apr_time_t meancon, meantot, meand, meanwait;
869 apr_interval_time_t mincon = AB_MAX, mintot = AB_MAX, mind = AB_MAX,
871 apr_interval_time_t maxcon = 0, maxtot = 0, maxd = 0, maxwait = 0;
872 apr_interval_time_t mediancon = 0, mediantot = 0, mediand = 0, medianwait = 0;
873 double sdtot = 0, sdcon = 0, sdd = 0, sdwait = 0;
875 for (i = 0; i < requests; i++) {
876 struct data s = stats[i];
877 mincon = ap_min(mincon, s.ctime);
878 mintot = ap_min(mintot, s.time);
879 mind = ap_min(mind, s.time - s.ctime);
880 minwait = ap_min(minwait, s.waittime);
882 maxcon = ap_max(maxcon, s.ctime);
883 maxtot = ap_max(maxtot, s.time);
884 maxd = ap_max(maxd, s.time - s.ctime);
885 maxwait = ap_max(maxwait, s.waittime);
889 totald += s.time - s.ctime;
890 totalwait += s.waittime;
892 meancon = totalcon / requests;
893 meantot = total / requests;
894 meand = totald / requests;
895 meanwait = totalwait / requests;
897 /* calculating the sample variance: the sum of the squared deviations, divided by n-1 */
898 for (i = 0; i < requests; i++) {
899 struct data s = stats[i];
901 a = ((double)s.time - meantot);
903 a = ((double)s.ctime - meancon);
905 a = ((double)s.time - (double)s.ctime - meand);
907 a = ((double)s.waittime - meanwait);
911 sdtot = (requests > 1) ? sqrt(sdtot / (requests - 1)) : 0;
912 sdcon = (requests > 1) ? sqrt(sdcon / (requests - 1)) : 0;
913 sdd = (requests > 1) ? sqrt(sdd / (requests - 1)) : 0;
914 sdwait = (requests > 1) ? sqrt(sdwait / (requests - 1)) : 0;
917 FILE *out = fopen(gnuplot, "w");
920 char tmstring[1024];/* XXXX */
922 perror("Cannot open gnuplot output file");
925 fprintf(out, "starttime\tseconds\tctime\tdtime\tttime\twait\n");
926 for (i = 0; i < requests; i++) {
927 apr_time_t diff = stats[i].time - stats[i].ctime;
929 sttime = stats[i].starttime;
930 (void) apr_ctime(tmstring, sttime);
931 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",
942 * XXX: what is better; this hideous cast of the compradre function; or
943 * the four warnings during compile ? dirkx just does not know and
946 qsort(stats, requests, sizeof(struct data),
947 (int (*) (const void *, const void *)) compradre);
948 if ((requests > 1) && (requests % 2))
949 mediancon = (stats[requests / 2].ctime + stats[requests / 2 + 1].ctime) / 2;
951 mediancon = stats[requests / 2].ctime;
953 qsort(stats, requests, sizeof(struct data),
954 (int (*) (const void *, const void *)) compri);
955 if ((requests > 1) && (requests % 2))
956 mediand = (stats[requests / 2].time + stats[requests / 2 + 1].time \
957 -stats[requests / 2].ctime - stats[requests / 2 + 1].ctime) / 2;
959 mediand = stats[requests / 2].time - stats[requests / 2].ctime;
961 qsort(stats, requests, sizeof(struct data),
962 (int (*) (const void *, const void *)) compwait);
963 if ((requests > 1) && (requests % 2))
964 medianwait = (stats[requests / 2].waittime + stats[requests / 2 + 1].waittime) / 2;
966 medianwait = stats[requests / 2].waittime;
968 qsort(stats, requests, sizeof(struct data),
969 (int (*) (const void *, const void *)) comprando);
970 if ((requests > 1) && (requests % 2))
971 mediantot = (stats[requests / 2].time + stats[requests / 2 + 1].time) / 2;
973 mediantot = stats[requests / 2].time;
975 printf("\nConnection Times (ms)\n");
978 #define CONF_FMT_STRING "%5" APR_TIME_T_FMT " %4d %5.1f %6" APR_TIME_T_FMT " %7" APR_TIME_T_FMT "\n"
979 printf(" min mean[+/-sd] median max\n");
980 printf("Connect: " CONF_FMT_STRING,
981 mincon, (int) (meancon + 0.5), sdcon, mediancon, maxcon);
982 printf("Processing: " CONF_FMT_STRING,
983 mind, (int) (meand + 0.5), sdd, mediand, maxd);
984 printf("Waiting: " CONF_FMT_STRING,
985 minwait, (int) (meanwait + 0.5), sdwait, medianwait, maxwait);
986 printf("Total: " CONF_FMT_STRING,
987 mintot, (int) (meantot + 0.5), sdtot, mediantot, maxtot);
988 #undef CONF_FMT_STRING
990 #define SANE(what,mean,median,sd) \
992 double d = (double)mean - median; \
995 printf("ERROR: The median and mean for " what " are more than twice the standard\n" \
996 " deviation apart. These results are NOT reliable.\n"); \
998 printf("WARNING: The median and mean for " what " are not within a normal deviation\n" \
999 " These results are probably not that reliable.\n"); \
1001 SANE("the initial connection time", meancon, mediancon, sdcon);
1002 SANE("the processing time", meand, mediand, sdd);
1003 SANE("the waiting time", meanwait, medianwait, sdwait);
1004 SANE("the total time", meantot, mediantot, sdtot);
1007 printf(" min avg max\n");
1008 #define CONF_FMT_STRING "%5" APR_TIME_T_FMT " %5" APR_TIME_T_FMT "%5" APR_TIME_T_FMT "\n"
1009 printf("Connect: " CONF_FMT_STRING,
1010 mincon, meancon, maxcon);
1011 printf("Processing: " CONF_FMT_STRING,
1012 mintot - mincon, meantot - meancon, maxtot - maxcon);
1013 printf("Total: " CONF_FMT_STRING,
1014 mintot, meantot, maxtot);
1015 #undef CONF_FMT_STRING
1019 /* Sorted on total connect times */
1020 if (percentile && (requests > 1)) {
1021 printf("\nPercentage of the requests served within a certain time (ms)\n");
1022 for (i = 0; i < sizeof(percs) / sizeof(int); i++)
1024 printf(" 0%% <0> (never)\n");
1025 else if (percs[i] >= 100)
1026 printf(" 100%% %5" APR_TIME_T_FMT " (longest request)\n",
1027 stats[requests - 1].time);
1029 printf(" %d%% %5" APR_TIME_T_FMT "\n", percs[i],
1030 stats[(int) (requests * percs[i] / 100)].time);
1033 FILE *out = fopen(csvperc, "w");
1036 perror("Cannot open CSV output file");
1039 fprintf(out, "" "Percentage served" "," "Time in ms" "\n");
1040 for (i = 0; i < 100; i++) {
1045 t = stats[requests - 1].time;
1047 t = stats[(int) (0.5 + requests * i / 100.0)].time;
1048 fprintf(out, "%d,%e\n", i, (double)t);
1056 /* --------------------------------------------------------- */
1058 /* calculate and output results in HTML */
1060 static void output_html_results(void)
1064 endtime = apr_time_now();
1065 timetaken = (long)((endtime - start) / 1000);
1067 printf("\n\n<table %s>\n", tablestring);
1068 printf("<tr %s><th colspan=2 %s>Server Software:</th>"
1069 "<td colspan=2 %s>%s</td></tr>\n",
1070 trstring, tdstring, tdstring, servername);
1071 printf("<tr %s><th colspan=2 %s>Server Hostname:</th>"
1072 "<td colspan=2 %s>%s</td></tr>\n",
1073 trstring, tdstring, tdstring, hostname);
1074 printf("<tr %s><th colspan=2 %s>Server Port:</th>"
1075 "<td colspan=2 %s>%hd</td></tr>\n",
1076 trstring, tdstring, tdstring, port);
1077 printf("<tr %s><th colspan=2 %s>Document Path:</th>"
1078 "<td colspan=2 %s>%s</td></tr>\n",
1079 trstring, tdstring, tdstring, path);
1080 printf("<tr %s><th colspan=2 %s>Document Length:</th>"
1081 "<td colspan=2 %s>%" APR_SIZE_T_FMT " bytes</td></tr>\n",
1082 trstring, tdstring, tdstring, doclen);
1083 printf("<tr %s><th colspan=2 %s>Concurrency Level:</th>"
1084 "<td colspan=2 %s>%d</td></tr>\n",
1085 trstring, tdstring, tdstring, concurrency);
1086 printf("<tr %s><th colspan=2 %s>Time taken for tests:</th>"
1087 "<td colspan=2 %s>%" APR_INT64_T_FMT ".%03ld seconds</td></tr>\n",
1088 trstring, tdstring, tdstring, apr_time_sec(timetaken),
1089 (long)apr_time_usec(timetaken));
1090 printf("<tr %s><th colspan=2 %s>Complete requests:</th>"
1091 "<td colspan=2 %s>%ld</td></tr>\n",
1092 trstring, tdstring, tdstring, done);
1093 printf("<tr %s><th colspan=2 %s>Failed requests:</th>"
1094 "<td colspan=2 %s>%ld</td></tr>\n",
1095 trstring, tdstring, tdstring, bad);
1097 printf("<tr %s><td colspan=4 %s > (Connect: %d, Length: %d, Exceptions: %d)</td></tr>\n",
1098 trstring, tdstring, err_conn, err_length, err_except);
1100 printf("<tr %s><th colspan=2 %s>Non-2xx responses:</th>"
1101 "<td colspan=2 %s>%d</td></tr>\n",
1102 trstring, tdstring, tdstring, err_response);
1104 printf("<tr %s><th colspan=2 %s>Keep-Alive requests:</th>"
1105 "<td colspan=2 %s>%ld</td></tr>\n",
1106 trstring, tdstring, tdstring, doneka);
1107 printf("<tr %s><th colspan=2 %s>Total transferred:</th>"
1108 "<td colspan=2 %s>%ld bytes</td></tr>\n",
1109 trstring, tdstring, tdstring, totalread);
1111 printf("<tr %s><th colspan=2 %s>Total POSTed:</th>"
1112 "<td colspan=2 %s>%ld</td></tr>\n",
1113 trstring, tdstring, tdstring, totalposted);
1114 printf("<tr %s><th colspan=2 %s>HTML transferred:</th>"
1115 "<td colspan=2 %s>%ld bytes</td></tr>\n",
1116 trstring, tdstring, tdstring, totalbread);
1118 /* avoid divide by zero */
1120 printf("<tr %s><th colspan=2 %s>Requests per second:</th>"
1121 "<td colspan=2 %s>%.2f</td></tr>\n",
1122 trstring, tdstring, tdstring, 1000 * (float) (done) / timetaken);
1123 printf("<tr %s><th colspan=2 %s>Transfer rate:</th>"
1124 "<td colspan=2 %s>%.2f kb/s received</td></tr>\n",
1125 trstring, tdstring, tdstring, (float) (totalread) / timetaken);
1127 printf("<tr %s><td colspan=2 %s> </td>"
1128 "<td colspan=2 %s>%.2f kb/s sent</td></tr>\n",
1129 trstring, tdstring, tdstring,
1130 (float) (totalposted) / timetaken);
1131 printf("<tr %s><td colspan=2 %s> </td>"
1132 "<td colspan=2 %s>%.2f kb/s total</td></tr>\n",
1133 trstring, tdstring, tdstring,
1134 (float) (totalread + totalposted) / timetaken);
1137 /* work out connection times */
1139 apr_interval_time_t totalcon = 0, total = 0;
1140 apr_interval_time_t mincon = AB_MAX, mintot = AB_MAX;
1141 apr_interval_time_t maxcon = 0, maxtot = 0;
1143 for (i = 0; i < requests; i++) {
1144 struct data s = stats[i];
1145 mincon = ap_min(mincon, s.ctime);
1146 mintot = ap_min(mintot, s.time);
1147 maxcon = ap_max(maxcon, s.ctime);
1148 maxtot = ap_max(maxtot, s.time);
1149 totalcon += s.ctime;
1153 if (requests > 0) { /* avoid division by zero (if 0 requests) */
1154 printf("<tr %s><th %s colspan=4>Connnection Times (ms)</th></tr>\n",
1155 trstring, tdstring);
1156 printf("<tr %s><th %s> </th> <th %s>min</th> <th %s>avg</th> <th %s>max</th></tr>\n",
1157 trstring, tdstring, tdstring, tdstring, tdstring);
1158 printf("<tr %s><th %s>Connect:</th>"
1159 "<td %s>%5" APR_TIME_T_FMT "</td>"
1160 "<td %s>%5" APR_TIME_T_FMT "</td>"
1161 "<td %s>%5" APR_TIME_T_FMT "</td></tr>\n",
1162 trstring, tdstring, tdstring, mincon, tdstring, totalcon / requests, tdstring, maxcon);
1163 printf("<tr %s><th %s>Processing:</th>"
1164 "<td %s>%5" APR_TIME_T_FMT "</td>"
1165 "<td %s>%5" APR_TIME_T_FMT "</td>"
1166 "<td %s>%5" APR_TIME_T_FMT "</td></tr>\n",
1167 trstring, tdstring, tdstring, mintot - mincon, tdstring,
1168 (total / requests) - (totalcon / requests), tdstring, maxtot - maxcon);
1169 printf("<tr %s><th %s>Total:</th>"
1170 "<td %s>%5" APR_TIME_T_FMT "</td>"
1171 "<td %s>%5" APR_TIME_T_FMT "</td>"
1172 "<td %s>%5" APR_TIME_T_FMT "</td></tr>\n",
1173 trstring, tdstring, tdstring, mintot, tdstring, total / requests, tdstring, maxtot);
1175 printf("</table>\n");
1179 /* --------------------------------------------------------- */
1181 /* start asnchronous non-blocking connection */
1183 static void start_connect(struct connection * c)
1189 ssl_start_connect(c);
1194 if (!(started < requests))
1204 apr_pool_destroy(c->ctx);
1205 apr_pool_create(&c->ctx, cntxt);
1207 if ((rv = apr_socket_create(&c->aprsock, destsa->family,
1208 SOCK_STREAM, c->ctx)) != APR_SUCCESS) {
1209 apr_err("socket", rv);
1211 if ((rv = apr_socket_opt_set(c->aprsock, APR_SO_NONBLOCK, 1))
1213 apr_err("socket nonblock", rv);
1215 c->start = apr_time_now();
1216 if ((rv = apr_connect(c->aprsock, destsa)) != APR_SUCCESS) {
1217 if (APR_STATUS_IS_EINPROGRESS(rv)) {
1218 apr_pollfd_t new_pollfd;
1219 c->state = STATE_CONNECTING;
1221 new_pollfd.desc_type = APR_POLL_SOCKET;
1222 new_pollfd.reqevents = APR_POLLOUT;
1223 new_pollfd.desc.s = c->aprsock;
1224 new_pollfd.client_data = c;
1225 apr_pollset_add(readbits, &new_pollfd);
1229 apr_pollfd_t remove_pollfd;
1230 remove_pollfd.desc_type = APR_POLL_SOCKET;
1231 remove_pollfd.desc.s = c->aprsock;
1232 apr_pollset_remove(readbits, &remove_pollfd);
1233 apr_socket_close(c->aprsock);
1237 "\nTest aborted after 10 failures\n\n");
1238 apr_err("apr_connect()", rv);
1240 c->state = STATE_UNCONNECTED;
1246 /* connected first time */
1247 c->state = STATE_CONNECTED;
1252 /* --------------------------------------------------------- */
1254 /* close down connection and save stats */
1256 static void close_connection(struct connection * c)
1258 if (c->read == 0 && c->keepalive) {
1260 * server has legitimately shut down an idle keep alive request
1263 good--; /* connection never happened */
1267 /* first time here */
1270 else if (c->bread != doclen) {
1275 if (done < requests) {
1277 if ((done) && heartbeatres && !(done % heartbeatres)) {
1278 fprintf(stderr, "Completed %ld requests\n", done);
1281 c->done = apr_time_now();
1283 s.starttime = c->start;
1284 s.ctime = (c->connect - c->start) / 1000;
1285 s.time = (c->done - c->start) / 1000;
1286 s.waittime = (c->beginread - c->endwrite) / 1000;
1293 SSL_shutdown(c->ssl);
1299 apr_pollfd_t remove_pollfd;
1300 remove_pollfd.desc_type = APR_POLL_SOCKET;
1301 remove_pollfd.desc.s = c->aprsock;
1302 apr_pollset_remove(readbits, &remove_pollfd);
1303 apr_socket_close(c->aprsock);
1305 c->state = STATE_UNCONNECTED;
1312 /* --------------------------------------------------------- */
1314 /* read data from connection */
1316 static void read_connection(struct connection * c)
1319 apr_status_t status;
1321 char respcode[4]; /* 3 digits and null */
1327 status = SSL_read (c->ssl, buffer, r);
1329 good++; c->read = 0;
1330 if (status < 0) printf("SSL read failed - closing connection\n");
1331 close_connection(c);
1338 status = apr_recv(c->aprsock, buffer, &r);
1339 if (APR_STATUS_IS_EAGAIN(status))
1341 else if (r == 0 && APR_STATUS_IS_EOF(status)) {
1343 close_connection(c);
1346 /* catch legitimate fatal apr_recv errors */
1347 else if (status != APR_SUCCESS) {
1348 err_except++; /* XXX: is this the right error counter? */
1349 /* XXX: Should errors here be fatal, or should we allow a
1350 * certain number of them before completely failing? -aaron */
1351 apr_err("apr_recv", status);
1359 c->beginread = apr_time_now();
1364 if (!c->gotheader) {
1367 apr_size_t space = CBUFFSIZE - c->cbx - 1; /* -1 allows for \0 term */
1368 int tocopy = (space < r) ? space : r;
1370 apr_size_t inbytes_left = space, outbytes_left = space;
1372 status = apr_xlate_conv_buffer(from_ascii, buffer, &inbytes_left,
1373 c->cbuff + c->cbx, &outbytes_left);
1374 if (status || inbytes_left || outbytes_left) {
1375 fprintf(stderr, "only simple translation is supported (%d/%u/%u)\n",
1376 status, inbytes_left, outbytes_left);
1380 memcpy(c->cbuff + c->cbx, buffer, space);
1381 #endif /* NOT_ASCII */
1384 c->cbuff[c->cbx] = 0; /* terminate for benefit of strstr */
1385 if (verbosity >= 2) {
1386 printf("LOG: header received:\n%s\n", c->cbuff);
1388 s = strstr(c->cbuff, "\r\n\r\n");
1390 * this next line is so that we talk to NCSA 1.5 which blatantly
1391 * breaks the http specifaction
1394 s = strstr(c->cbuff, "\n\n");
1399 /* read rest next time */
1404 /* header is in invalid or too big - close connection */
1405 apr_pollfd_t remove_pollfd;
1406 remove_pollfd.desc_type = APR_POLL_SOCKET;
1407 remove_pollfd.desc.s = c->aprsock;
1408 apr_pollset_remove(readbits, &remove_pollfd);
1409 apr_socket_close(c->aprsock);
1412 err("\nTest aborted after 10 failures\n\n");
1418 /* have full header */
1421 * this is first time, extract some interesting info
1424 p = strstr(c->cbuff, "Server:");
1434 * XXX: this parsing isn't even remotely HTTP compliant... but in
1435 * the interest of speed it doesn't totally have to be, it just
1436 * needs to be extended to handle whatever servers folks want to
1437 * test against. -djg
1440 /* check response code */
1441 part = strstr(c->cbuff, "HTTP"); /* really HTTP/1.x_ */
1442 if (part && strlen(part) > strlen("HTTP/1.x_")) {
1443 strncpy(respcode, (part + strlen("HTTP/1.x_")), 3);
1447 strcpy(respcode, "500");
1450 if (respcode[0] != '2') {
1453 printf("WARNING: Response code not 2xx (%s)\n", respcode);
1455 else if (verbosity >= 3) {
1456 printf("LOG: Response code = %s\n", respcode);
1459 *s = 0; /* terminate at end of header */
1461 (strstr(c->cbuff, "Keep-Alive")
1462 || strstr(c->cbuff, "keep-alive"))) { /* for benefit of MSIIS */
1464 cl = strstr(c->cbuff, "Content-Length:");
1465 /* handle NCSA, which sends Content-length: */
1467 cl = strstr(c->cbuff, "Content-length:");
1470 c->length = atoi(cl + 16);
1473 c->bread += c->cbx - (s + l - c->cbuff) + r - tocopy;
1474 totalbread += c->bread;
1478 /* outside header, everything we have read is entity body */
1483 if (c->keepalive && (c->bread >= c->length)) {
1484 /* finished a keep-alive connection */
1488 /* first time here */
1491 else if (c->bread != doclen) {
1495 if (done < requests) {
1498 if (done && heartbeatres && !(done % heartbeatres)) {
1499 fprintf(stderr, "Completed %ld requests\n", done);
1502 c->done = apr_time_now();
1504 s.starttime = c->start;
1505 s.ctime = (c->connect - c->start) / 1000;
1506 s.waittime = (c->beginread - c->endwrite) / 1000;
1507 s.time = (c->done - c->start) / 1000;
1514 c->read = c->bread = 0;
1515 c->start = c->connect = apr_time_now(); /* zero connect time with keep-alive */
1520 /* --------------------------------------------------------- */
1524 static void test(void)
1529 apr_status_t status;
1531 apr_size_t inbytes_left, outbytes_left;
1535 connecthost = apr_pstrdup(cntxt, proxyhost);
1536 connectport = proxyport;
1539 connecthost = apr_pstrdup(cntxt, hostname);
1544 printf("Benchmarking %s ", hostname);
1546 printf("[through %s:%d] ", proxyhost, proxyport);
1547 printf("(be patient)%s",
1548 (heartbeatres ? "\n" : "..."));
1552 now = apr_time_now();
1554 con = calloc(concurrency * sizeof(struct connection), 1);
1556 stats = calloc(requests * sizeof(struct data), 1);
1558 if ((status = apr_pollset_create(&readbits, concurrency, cntxt, 0)) != APR_SUCCESS) {
1559 apr_err("apr_pollset_create failed", status);
1564 sprintf(request, "%s %s HTTP/1.0\r\n"
1565 "User-Agent: ApacheBench/%s\r\n"
1570 (posting == 0) ? "GET" : "HEAD",
1571 (isproxy) ? fullurl : path,
1573 keepalive ? "Connection: Keep-Alive\r\n" : "",
1574 cookie, auth, host_field, colonhost, hdrs);
1577 sprintf(request, "POST %s HTTP/1.0\r\n"
1578 "User-Agent: ApacheBench/%s\r\n"
1582 "Content-length: %" APR_SIZE_T_FMT "\r\n"
1583 "Content-type: %s\r\n"
1586 (isproxy) ? fullurl : path,
1588 keepalive ? "Connection: Keep-Alive\r\n" : "",
1590 host_field, colonhost, postlen,
1591 (content_type[0]) ? content_type : "text/plain", hdrs);
1595 printf("INFO: POST header == \n---\n%s\n---\n", request);
1597 reqlen = strlen(request);
1600 * Combine headers and (optional) post file into one contineous buffer
1603 char *buff = malloc(postlen + reqlen + 1);
1605 fprintf(stderr, "error creating request buffer: out of memory\n");
1608 strcpy(buff, request);
1609 strcpy(buff + reqlen, postdata);
1614 inbytes_left = outbytes_left = reqlen;
1615 status = apr_xlate_conv_buffer(to_ascii, request, &inbytes_left,
1616 request, &outbytes_left);
1617 if (status || inbytes_left || outbytes_left) {
1618 fprintf(stderr, "only simple translation is supported (%d/%u/%u)\n",
1619 status, inbytes_left, outbytes_left);
1622 #endif /* NOT_ASCII */
1624 /* This only needs to be done once */
1628 if ((rv = apr_sockaddr_info_get(&destsa, connecthost, APR_UNSPEC, connectport, 0, cntxt))
1631 apr_snprintf(buf, sizeof(buf),
1632 "apr_sockaddr_info_get() for %s", connecthost);
1636 /* ok - lets start */
1637 start = apr_time_now();
1639 /* initialise lots of requests */
1640 for (i = 0; i < concurrency; i++) {
1642 start_connect(&con[i]);
1645 while (done < requests) {
1648 const apr_pollfd_t *pollresults;
1650 /* check for time limit expiry */
1651 now = apr_time_now();
1652 timed = (apr_int32_t)apr_time_sec(now - start);
1653 if (tlimit && timed >= tlimit) {
1654 requests = done; /* so stats are correct */
1655 break; /* no need to do another round */
1661 status = APR_SUCCESS;
1664 status = apr_pollset_poll(readbits, aprtimeout, &n, &pollresults);
1665 if (status != APR_SUCCESS)
1666 apr_err("apr_poll", status);
1669 err("\nServer timed out\n\n");
1672 for (i = 0; i < n; i++) {
1673 const apr_pollfd_t *next_fd = &(pollresults[i]);
1674 struct connection *c = next_fd->client_data;
1677 * If the connection isn't connected how can we check it?
1679 if (c->state == STATE_UNCONNECTED)
1687 rv = next_fd->rtnevents;
1690 * Notes: APR_POLLHUP is set after FIN is received on some
1691 * systems, so treat that like APR_POLLIN so that we try to read
1694 * Some systems return APR_POLLERR with APR_POLLHUP. We need to
1695 * call read_connection() for APR_POLLHUP, so check for
1696 * APR_POLLHUP first so that a closed connection isn't treated
1697 * like an I/O error. If it is, we never figure out that the
1698 * connection is done and we loop here endlessly calling
1701 if ((rv & APR_POLLIN) || (rv & APR_POLLPRI) || (rv & APR_POLLHUP))
1703 if ((rv & APR_POLLERR) || (rv & APR_POLLNVAL)) {
1709 if (rv & APR_POLLOUT) {
1710 if (c->state == STATE_CONNECTING) {
1711 apr_pollfd_t remove_pollfd;
1712 rv = apr_connect(c->aprsock, destsa);
1713 remove_pollfd.desc_type = APR_POLL_SOCKET;
1714 remove_pollfd.desc.s = c->aprsock;
1715 apr_pollset_remove(readbits, &remove_pollfd);
1716 if (rv != APR_SUCCESS) {
1717 apr_socket_close(c->aprsock);
1721 "\nTest aborted after 10 failures\n\n");
1722 apr_err("apr_connect()", rv);
1724 c->state = STATE_UNCONNECTED;
1729 c->state = STATE_CONNECTED;
1739 * When using a select based poll every time we check the bits
1740 * are reset. In 1.3's ab we copied the FD_SET's each time
1741 * through, but here we're going to check the state and if the
1742 * connection is in STATE_READ or STATE_CONNECTING we'll add the
1743 * socket back in as APR_POLLIN.
1748 if (c->state == STATE_READ) {
1749 apr_pollfd_t new_pollfd;
1750 new_pollfd.desc_type = APR_POLL_SOCKET;
1751 new_pollfd.reqevents = APR_POLLIN;
1752 new_pollfd.desc.s = c->aprsock;
1753 new_pollfd.client_data = c;
1754 apr_pollset_add(readbits, &new_pollfd);
1760 fprintf(stderr, "Finished %ld requests\n", done);
1765 output_html_results();
1770 /* ------------------------------------------------------- */
1772 /* display copyright information */
1773 static void copyright(void)
1776 printf("This is ApacheBench, Version %s\n", AP_AB_BASEREVISION " <$Revision: 1.121.2.12 $> apache-2.0");
1777 printf("Copyright (c) 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\n");
1778 printf("Copyright (c) 2006 The Apache Software Foundation, http://www.apache.org/\n");
1783 printf(" This is ApacheBench, Version %s <i><%s></i> apache-2.0<br>\n", AP_AB_BASEREVISION, "$Revision: 1.121.2.12 $");
1784 printf(" Copyright (c) 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/<br>\n");
1785 printf(" Copyright (c) 2006 The Apache Software Foundation, http://www.apache.org/<br>\n");
1786 printf("</p>\n<p>\n");
1790 /* display usage information */
1791 static void usage(const char *progname)
1793 fprintf(stderr, "Usage: %s [options] [http"
1797 "://]hostname[:port]/path\n", progname);
1798 fprintf(stderr, "Options are:\n");
1799 fprintf(stderr, " -n requests Number of requests to perform\n");
1800 fprintf(stderr, " -c concurrency Number of multiple requests to make\n");
1801 fprintf(stderr, " -t timelimit Seconds to max. wait for responses\n");
1802 fprintf(stderr, " -p postfile File containing data to POST\n");
1803 fprintf(stderr, " -T content-type Content-type header for POSTing\n");
1804 fprintf(stderr, " -v verbosity How much troubleshooting info to print\n");
1805 fprintf(stderr, " -w Print out results in HTML tables\n");
1806 fprintf(stderr, " -i Use HEAD instead of GET\n");
1807 fprintf(stderr, " -x attributes String to insert as table attributes\n");
1808 fprintf(stderr, " -y attributes String to insert as tr attributes\n");
1809 fprintf(stderr, " -z attributes String to insert as td or th attributes\n");
1810 fprintf(stderr, " -C attribute Add cookie, eg. 'Apache=1234. (repeatable)\n");
1811 fprintf(stderr, " -H attribute Add Arbitrary header line, eg. 'Accept-Encoding: gzip'\n");
1812 fprintf(stderr, " Inserted after all normal header lines. (repeatable)\n");
1813 fprintf(stderr, " -A attribute Add Basic WWW Authentication, the attributes\n");
1814 fprintf(stderr, " are a colon separated username and password.\n");
1815 fprintf(stderr, " -P attribute Add Basic Proxy Authentication, the attributes\n");
1816 fprintf(stderr, " are a colon separated username and password.\n");
1817 fprintf(stderr, " -X proxy:port Proxyserver and port number to use\n");
1818 fprintf(stderr, " -V Print version number and exit\n");
1819 fprintf(stderr, " -k Use HTTP KeepAlive feature\n");
1820 fprintf(stderr, " -d Do not show percentiles served table.\n");
1821 fprintf(stderr, " -S Do not show confidence estimators and warnings.\n");
1822 fprintf(stderr, " -g filename Output collected data to gnuplot format file.\n");
1823 fprintf(stderr, " -e filename Output CSV file with percentages served\n");
1825 fprintf(stderr, " -s Use httpS instead of HTTP (SSL)\n");
1827 fprintf(stderr, " -h Display usage information (this message)\n");
1831 /* ------------------------------------------------------- */
1833 /* split URL into parts */
1835 static int parse_url(char *url)
1842 /* Save a copy for the proxy */
1843 fullurl = apr_pstrdup(cntxt, url);
1845 if (strlen(url) > 7 && strncmp(url, "http://", 7) == 0) {
1853 if (strlen(url) > 8 && strncmp(url, "https://", 8) == 0) {
1858 if (strlen(url) > 8 && strncmp(url, "https://", 8) == 0) {
1859 fprintf(stderr, "SSL not compiled in; no https support\n");
1864 if ((cp = strchr(url, '/')) == NULL)
1866 h = apr_palloc(cntxt, cp - url + 1);
1867 memcpy(h, url, cp - url);
1869 rv = apr_parse_addr_port(&hostname, &scope_id, &port, h, cntxt);
1870 if (rv != APR_SUCCESS || !hostname || scope_id) {
1873 path = apr_pstrdup(cntxt, cp);
1875 if (*url == '[') { /* IPv6 numeric address string */
1876 host_field = apr_psprintf(cntxt, "[%s]", hostname);
1879 host_field = hostname;
1882 if (port == 0) { /* no port specified */
1893 (ssl == 1) && (port != 443)) || (( ssl == 0 ) &&
1897 colonhost = apr_psprintf(cntxt,":%d",port);
1903 /* ------------------------------------------------------- */
1905 /* read data to POST from file, save contents and length */
1907 static int open_postfile(const char *pfile)
1909 apr_file_t *postfd = NULL;
1911 apr_fileperms_t mode = APR_OS_DEFAULT;
1916 rv = apr_file_open(&postfd, pfile, APR_READ, mode, cntxt);
1917 if (rv != APR_SUCCESS) {
1918 printf("Invalid postfile name (%s): %s\n", pfile,
1919 apr_strerror(rv, errmsg, sizeof errmsg));
1923 apr_file_info_get(&finfo, APR_FINFO_NORM, postfd);
1924 postlen = (apr_size_t)finfo.size;
1925 postdata = (char *) malloc(postlen);
1927 printf("Can\'t alloc postfile buffer\n");
1931 rv = apr_file_read(postfd, postdata, &length);
1932 if (rv != APR_SUCCESS) {
1933 printf("error reading postfile: %s\n",
1934 apr_strerror(rv, errmsg, sizeof errmsg));
1937 if (length != postlen) {
1938 printf("error reading postfile: read only %"
1939 APR_SIZE_T_FMT " bytes",
1943 apr_file_close(postfd);
1947 /* ------------------------------------------------------- */
1949 /* sort out command-line args and call test */
1950 int main(int argc, const char * const argv[])
1954 apr_status_t status;
1959 /* table defaults */
1962 tdstring = "bgcolor=white";
1965 proxyhost[0] = '\0';
1968 apr_app_initialize(&argc, &argv, NULL);
1969 atexit(apr_terminate);
1970 apr_pool_create(&cntxt, NULL);
1973 status = apr_xlate_open(&to_ascii, "ISO8859-1", APR_DEFAULT_CHARSET, cntxt);
1975 fprintf(stderr, "apr_xlate_open(to ASCII)->%d\n", status);
1978 status = apr_xlate_open(&from_ascii, APR_DEFAULT_CHARSET, "ISO8859-1", cntxt);
1980 fprintf(stderr, "apr_xlate_open(from ASCII)->%d\n", status);
1983 status = apr_base64init_ebcdic(to_ascii, from_ascii);
1985 fprintf(stderr, "apr_base64init_ebcdic()->%d\n", status);
1990 apr_getopt_init(&opt, cntxt, argc, argv);
1991 while ((status = apr_getopt(opt, "n:c:t:T:p:v:kVhwix:y:z:C:H:P:A:g:X:de:Sq"
1995 ,&c, &optarg)) == APR_SUCCESS) {
2002 fprintf(stderr, "SSL not compiled in; no https support\n");
2006 requests = atoi(optarg);
2008 err("Invalid number of requests\n");
2018 concurrency = atoi(optarg);
2022 err("Cannot mix POST and HEAD\n");
2026 gnuplot = strdup(optarg);
2032 csvperc = strdup(optarg);
2039 err("Cannot mix POST and HEAD\n");
2041 if (0 == (r = open_postfile(optarg))) {
2044 else if (postdata) {
2049 verbosity = atoi(optarg);
2052 tlimit = atoi(optarg);
2053 requests = MAX_REQUESTS; /* need to size data array on
2057 strcpy(content_type, optarg);
2060 cookie = apr_pstrcat(cntxt, "Cookie: ", optarg, "\r\n", NULL);
2064 * assume username passwd already to be in colon separated form.
2065 * Ready to be uu-encoded.
2067 while (apr_isspace(*optarg))
2069 if (apr_base64_encode_len(strlen(optarg)) > sizeof(tmp)) {
2070 err("Authentication credentials too long\n");
2072 l = apr_base64_encode(tmp, optarg, strlen(optarg));
2075 auth = apr_pstrcat(cntxt, auth, "Authorization: Basic ", tmp,
2080 * assume username passwd already to be in colon separated form.
2082 while (apr_isspace(*optarg))
2084 if (apr_base64_encode_len(strlen(optarg)) > sizeof(tmp)) {
2085 err("Proxy credentials too long\n");
2087 l = apr_base64_encode(tmp, optarg, strlen(optarg));
2090 auth = apr_pstrcat(cntxt, auth, "Proxy-Authorization: Basic ",
2094 hdrs = apr_pstrcat(cntxt, hdrs, optarg, "\r\n", NULL);
2100 * if any of the following three are used, turn on html output
2105 tablestring = optarg;
2111 * assume proxy-name[:port]
2113 if ((p = strchr(optarg, ':'))) {
2116 proxyport = atoi(p);
2118 strcpy(proxyhost, optarg);
2139 if (opt->ind != argc - 1) {
2140 fprintf(stderr, "%s: wrong number of arguments\n", argv[0]);
2144 if (parse_url(apr_pstrdup(cntxt, opt->argv[opt->ind++]))) {
2145 fprintf(stderr, "%s: invalid URL\n", argv[0]);
2149 if ((concurrency < 0) || (concurrency > MAX_CONCURRENCY)) {
2150 fprintf(stderr, "%s: Invalid Concurrency [Range 0..%d]\n",
2151 argv[0], MAX_CONCURRENCY);
2155 if ((heartbeatres) && (requests > 150)) {
2156 heartbeatres = requests / 10; /* Print line every 10% of requests */
2157 if (heartbeatres < 100)
2158 heartbeatres = 100; /* but never more often than once every 100
2168 CRYPTO_malloc_init();
2170 SSL_load_error_strings();
2172 bio_out=BIO_new_fp(stdout,BIO_NOCLOSE);
2173 bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
2175 /* TODO: Allow force SSLv2_client_method() (TLSv1?) */
2176 if (!(ctx = SSL_CTX_new(SSLv23_client_method()))) {
2177 fprintf(stderr, "Could not init SSL CTX");
2178 ERR_print_errors_fp(stderr);
2181 SSL_CTX_set_options(ctx, SSL_OP_ALL);
2183 ssl_util_thread_setup(cntxt);
2187 apr_signal(SIGPIPE, SIG_IGN); /* Ignore writes to connections that
2188 * have been closed at the other end. */
2192 apr_pool_destroy(cntxt);