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_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
/* 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.40-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
147
#if APR_HAVE_UNISTD_H
148
#include <unistd.h> /* for getpid() */
151
#if !defined(WIN32) && !defined(NETWARE)
152
#include "ap_config_auto.h"
155
#if defined(HAVE_SSLC)
157
/* Libraries for RSA SSL-C */
167
#define SK_NUM(x) sk_num(x)
168
#define SK_VALUE(x,y) sk_value(x,y)
169
typedef STACK X509_STACK_TYPE;
171
#elif defined(HAVE_OPENSSL)
173
/* Libraries on most systems.. */
174
#include <openssl/rsa.h>
175
#include <openssl/crypto.h>
176
#include <openssl/x509.h>
177
#include <openssl/pem.h>
178
#include <openssl/err.h>
179
#include <openssl/ssl.h>
180
#include <openssl/rand.h>
182
#define SK_NUM(x) sk_X509_num(x)
183
#define SK_VALUE(x,y) sk_X509_value(x,y)
184
typedef STACK_OF(X509) X509_STACK_TYPE;
193
/* ------------------- DEFINITIONS -------------------------- */
196
#define AB_MAX APR_INT64_C(0x7fffffffffffffff)
198
#define AB_MAX LLONG_MAX
201
/* maximum number of requests on a time limited test */
202
#define MAX_REQUESTS 50000
204
/* good old state hostname */
205
#define STATE_UNCONNECTED 0
206
#define STATE_CONNECTING 1 /* TCP connect initiated, but we don't
207
* know if it worked yet
209
#define STATE_CONNECTED 2 /* we know TCP connect completed */
212
#define CBUFFSIZE (2048)
216
apr_socket_t *aprsock;
218
apr_size_t read; /* amount of bytes read */
219
apr_size_t bread; /* amount of body read */
220
apr_size_t rwrite, rwrote; /* keep pointers in what we write - across
222
apr_size_t length; /* Content-Length value used for keep-alive */
223
char cbuff[CBUFFSIZE]; /* a buffer to store server response header */
224
int cbx; /* offset in cbuffer */
225
int keepalive; /* non-zero if a keep-alive request */
226
int gotheader; /* non-zero if we have the entire header in
228
apr_time_t start, /* Start of connection */
229
connect, /* Connected, start writing */
230
endwrite, /* Request written */
231
beginread, /* First byte of input */
232
done; /* Connection closed */
241
int read; /* number of bytes read */
242
apr_time_t starttime; /* start time of connection in seconds since
244
apr_interval_time_t waittime; /* Between writing request and reading
246
apr_interval_time_t ctime; /* time in ms to connect */
247
apr_interval_time_t time; /* time in ms for connection */
250
#define ap_min(a,b) ((a)<(b))?(a):(b)
251
#define ap_max(a,b) ((a)>(b))?(a):(b)
252
#define MAX_CONCURRENCY 20000
254
/* --------------------- GLOBALS ---------------------------- */
256
int verbosity = 0; /* no verbosity by default */
257
int posting = 0; /* GET by default */
258
int requests = 1; /* Number of requests to make */
259
int heartbeatres = 100; /* How often do we say we're alive */
260
int concurrency = 1; /* Number of multiple requests to make */
261
int percentile = 1; /* Show percentile served */
262
int confidence = 1; /* Show confidence estimator and warnings */
263
int tlimit = 0; /* time limit in secs */
264
int keepalive = 0; /* try and do keepalive connections */
265
char servername[1024]; /* name that server reports */
266
char *hostname; /* host name from URL */
267
char *host_field; /* value of "Host:" header field */
268
char *path; /* path name */
269
char postfile[1024]; /* name of file containing post data */
270
char *postdata; /* *buffer containing data from postfile */
271
apr_size_t postlen = 0; /* length of data to be POSTed */
272
char content_type[1024];/* content type to put in POST header */
273
char *cookie, /* optional cookie line */
274
*auth, /* optional (basic/uuencoded) auhentication */
275
*hdrs; /* optional arbitrary headers */
276
apr_port_t port; /* port number */
277
char proxyhost[1024]; /* proxy host name */
278
int proxyport = 0; /* proxy port */
280
apr_port_t connectport;
281
char *gnuplot; /* GNUplot file */
282
char *csvperc; /* CSV Percentile file */
284
char * fullurl, * colonhost;
286
apr_interval_time_t aprtimeout = apr_time_from_sec(30); /* timeout value */
288
* XXX - this is now a per read/write transact type of value
291
int use_html = 0; /* use html in the report */
292
const char *tablestring;
293
const char *trstring;
294
const char *tdstring;
296
apr_size_t doclen = 0; /* the length the document should be */
297
long started = 0; /* number of requests started, so no excess */
298
long totalread = 0; /* total number of bytes read */
299
long totalbread = 0; /* totoal amount of entity body read */
300
long totalposted = 0; /* total number of bytes posted, inc. headers */
301
long done = 0; /* number of requests we have done */
302
long doneka = 0; /* number of keep alive connections done */
303
long good = 0, bad = 0; /* number of good and bad requests */
304
long epipe = 0; /* number of broken pipe writes */
309
char *ssl_cipher = NULL;
310
char *ssl_info = NULL;
311
BIO *bio_out,*bio_err;
314
/* store error cases */
315
int err_length = 0, err_conn = 0, err_except = 0;
316
int err_response = 0;
318
apr_time_t start, endtime;
320
/* global request (and its length) */
322
char *request = _request;
325
/* one global throw-away buffer to read stuff into */
328
/* interesting percentiles */
329
int percs[] = {50, 66, 75, 80, 90, 95, 98, 99, 100};
331
struct connection *con; /* connection array */
332
struct data *stats; /* date for each request */
335
apr_pollset_t *readbits;
337
apr_sockaddr_t *destsa;
340
apr_xlate_t *from_ascii, *to_ascii;
343
static void write_request(struct connection * c);
344
static void close_connection(struct connection * c);
346
/* --------------------------------------------------------- */
348
/* simple little function to write an error string and exit */
350
static void err(char *s)
352
fprintf(stderr, "%s\n", s);
354
printf("Total of %ld requests completed\n" , done);
358
/* simple little function to write an APR error string and exit */
360
static void apr_err(char *s, apr_status_t rv)
366
s, apr_strerror(rv, buf, sizeof buf), rv);
368
printf("Total of %ld requests completed\n" , done);
372
/* --------------------------------------------------------- */
373
/* write out request to a connection - assumes we can write
374
* (small) request out in one go into our new socket buffer
378
static long ssl_print_cb(BIO *bio,int cmd,const char *argp,int argi,long argl,long ret)
382
out=(BIO *)BIO_get_callback_arg(bio);
383
if (out == NULL) return(ret);
385
if (cmd == (BIO_CB_READ|BIO_CB_RETURN)) {
386
BIO_printf(out,"read from %p [%p] (%d bytes => %ld (0x%lX))\n",
387
bio, argp, argi, ret, ret);
388
BIO_dump(out,(char *)argp,(int)ret);
391
else if (cmd == (BIO_CB_WRITE|BIO_CB_RETURN)) {
392
BIO_printf(out,"write to %p [%p] (%d bytes => %ld (0x%lX))\n",
393
bio, argp, argi, ret, ret);
394
BIO_dump(out,(char *)argp,(int)ret);
399
static void ssl_state_cb(const SSL *s, int w, int r)
401
if (w & SSL_CB_ALERT) {
402
BIO_printf(bio_err, "SSL/TLS Alert [%s] %s:%s\n",
403
(w & SSL_CB_READ ? "read" : "write"),
404
SSL_alert_type_string_long(r),
405
SSL_alert_desc_string_long(r));
406
} else if (w & SSL_CB_LOOP) {
407
BIO_printf(bio_err, "SSL/TLS State [%s] %s\n",
408
(SSL_in_connect_init((SSL*)s) ? "connect" : "-"),
409
SSL_state_string_long(s));
410
} else if (w & (SSL_CB_HANDSHAKE_START|SSL_CB_HANDSHAKE_DONE)) {
411
BIO_printf(bio_err, "SSL/TLS Handshake [%s] %s\n",
412
(w & SSL_CB_HANDSHAKE_START ? "Start" : "Done"),
413
SSL_state_string_long(s));
419
#define RAND_MAX INT_MAX
422
static int ssl_rand_choosenum(int l, int h)
427
srand((unsigned int)time(NULL));
428
apr_snprintf(buf, sizeof(buf), "%.0f",
429
(((double)(rand()%RAND_MAX)/RAND_MAX)*(h-l)));
436
static void ssl_rand_seed(void)
442
unsigned char stackdata[256];
445
* seed in the current time (usually just 4 bytes)
449
RAND_seed((unsigned char *)&t, l);
453
* seed in the current process id (usually just 4 bytes)
457
RAND_seed((unsigned char *)&pid, l);
461
* seed in some current state of the run-time stack (128 bytes)
463
n = ssl_rand_choosenum(0, sizeof(stackdata)-128-1);
464
RAND_seed(stackdata+n, 128);
468
static int ssl_print_connection_info(BIO *bio, SSL *ssl)
473
c = SSL_get_current_cipher(ssl);
474
BIO_printf(bio,"Cipher Suite Protocol :%s\n", SSL_CIPHER_get_version(c));
475
BIO_printf(bio,"Cipher Suite Name :%s\n",SSL_CIPHER_get_name(c));
477
bits = SSL_CIPHER_get_bits(c,&alg_bits);
478
BIO_printf(bio,"Cipher Suite Cipher Bits:%d (%d)\n",bits,alg_bits);
483
static void ssl_print_cert_info(BIO *bio, X509 *cert)
488
BIO_printf(bio, "Certificate version: %ld\n", X509_get_version(cert)+1);
489
BIO_printf(bio,"Valid from: ");
490
ASN1_UTCTIME_print(bio, X509_get_notBefore(cert));
491
BIO_printf(bio,"\n");
493
BIO_printf(bio,"Valid to : ");
494
ASN1_UTCTIME_print(bio, X509_get_notAfter(cert));
495
BIO_printf(bio,"\n");
497
BIO_printf(bio,"Public key is %d bits\n",
498
EVP_PKEY_bits(X509_get_pubkey(cert)));
500
dn = X509_get_issuer_name(cert);
501
X509_NAME_oneline(dn, buf, sizeof(buf));
502
BIO_printf(bio,"The issuer name is %s\n", buf);
504
dn=X509_get_subject_name(cert);
505
X509_NAME_oneline(dn, buf, sizeof(buf));
506
BIO_printf(bio,"The subject name is %s\n", buf);
508
/* dump the extension list too */
509
BIO_printf(bio, "Extension Count: %d\n", X509_get_ext_count(cert));
512
static void ssl_print_info(struct connection *c)
518
BIO_printf(bio_err, "\n");
519
sk = SSL_get_peer_cert_chain(c->ssl);
520
if ((count = SK_NUM(sk)) > 0) {
522
for (i=1; i<count; i++) {
523
cert = (X509 *)SK_VALUE(sk, i);
524
ssl_print_cert_info(bio_out, cert);
528
cert = SSL_get_peer_certificate(c->ssl);
530
BIO_printf(bio_out, "Anon DH\n");
532
BIO_printf(bio_out, "Peer certificate\n");
533
ssl_print_cert_info(bio_out, cert);
536
ssl_print_connection_info(bio_err,c->ssl);
537
SSL_SESSION_print(bio_err, SSL_get_session(c->ssl));
540
static void ssl_proceed_handshake(struct connection *c)
546
apr_pollfd_t new_pollfd;
548
ret = SSL_do_handshake(c->ssl);
549
ecode = SSL_get_error(c->ssl, ret);
555
if (ssl_info == NULL) {
558
int sk_bits, pk_bits, swork;
560
ci = SSL_get_current_cipher(c->ssl);
561
sk_bits = SSL_CIPHER_get_bits(ci, &swork);
562
cert = SSL_get_peer_certificate(c->ssl);
564
pk_bits = EVP_PKEY_bits(X509_get_pubkey(cert));
566
pk_bits = 0; /* Anon DH */
568
ssl_info = malloc(128);
569
apr_snprintf(ssl_info, 128, "%s,%s,%d,%d",
570
SSL_CIPHER_get_version(ci),
571
SSL_CIPHER_get_name(ci),
577
case SSL_ERROR_WANT_READ:
578
new_pollfd.desc_type = APR_POLL_SOCKET;
579
new_pollfd.reqevents = APR_POLLIN;
580
new_pollfd.desc.s = c->aprsock;
581
new_pollfd.client_data = c;
582
apr_pollset_add(readbits, &new_pollfd);
585
case SSL_ERROR_WANT_WRITE:
589
case SSL_ERROR_WANT_CONNECT:
591
case SSL_ERROR_SYSCALL:
592
/* Unexpected result */
593
BIO_printf(bio_err, "SSL handshake failed (%d).\n", ecode);
594
ERR_print_errors(bio_err);
604
static void write_request(struct connection * c)
607
apr_time_t tnow = apr_time_now();
608
apr_size_t l = c->rwrite;
609
apr_status_t e = APR_SUCCESS; /* prevent gcc warning */
614
if (c->rwrite == 0) {
615
apr_socket_timeout_set(c->aprsock, 0);
620
c->rwrite += postlen;
622
else if (tnow > c->connect + aprtimeout) {
623
printf("Send request timed out!\n");
631
e_ssl = SSL_write(c->ssl,request + c->rwrote, l);
633
BIO_printf(bio_err, "SSL write failed - closing connection\n");
634
ERR_print_errors(bio_err);
635
close_connection (c);
643
e = apr_socket_send(c->aprsock, request + c->rwrote, &l);
646
* Bail early on the most common case
651
if (e != APR_SUCCESS) {
653
* Let's hope this traps EWOULDBLOCK too !
655
if (!APR_STATUS_IS_EAGAIN(e)) {
657
printf("Send request failed!\n");
666
totalposted += c->rwrite;
667
c->state = STATE_READ;
668
c->endwrite = apr_time_now();
670
apr_pollfd_t new_pollfd;
671
new_pollfd.desc_type = APR_POLL_SOCKET;
672
new_pollfd.reqevents = APR_POLLIN;
673
new_pollfd.desc.s = c->aprsock;
674
new_pollfd.client_data = c;
675
apr_pollset_add(readbits, &new_pollfd);
679
/* --------------------------------------------------------- */
681
/* calculate and output results */
683
static int compradre(struct data * a, struct data * b)
685
if ((a->ctime) < (b->ctime))
687
if ((a->ctime) > (b->ctime))
692
static int comprando(struct data * a, struct data * b)
694
if ((a->time) < (b->time))
696
if ((a->time) > (b->time))
701
static int compri(struct data * a, struct data * b)
703
apr_interval_time_t p = a->time - a->ctime;
704
apr_interval_time_t q = b->time - b->ctime;
712
static int compwait(struct data * a, struct data * b)
714
if ((a->waittime) < (b->waittime))
716
if ((a->waittime) > (b->waittime))
721
static void output_results(void)
723
apr_interval_time_t timetakenusec;
726
endtime = apr_time_now();
727
timetakenusec = endtime - start;
728
timetaken = ((float)apr_time_sec(timetakenusec)) +
729
((float)apr_time_usec(timetakenusec)) / 1000000.0F;
732
printf("Server Software: %s\n", servername);
733
printf("Server Hostname: %s\n", hostname);
734
printf("Server Port: %hd\n", port);
736
if (is_ssl && ssl_info) {
737
printf("SSL/TLS Protocol: %s\n", ssl_info);
741
printf("Document Path: %s\n", path);
742
printf("Document Length: %" APR_SIZE_T_FMT " bytes\n", doclen);
744
printf("Concurrency Level: %d\n", concurrency);
745
printf("Time taken for tests: %ld.%03ld seconds\n",
746
(long) apr_time_sec(timetakenusec),
747
(long) apr_time_usec(timetakenusec));
748
printf("Complete requests: %ld\n", done);
749
printf("Failed requests: %ld\n", bad);
751
printf(" (Connect: %d, Length: %d, Exceptions: %d)\n",
752
err_conn, err_length, err_except);
753
printf("Write errors: %ld\n", epipe);
755
printf("Non-2xx responses: %d\n", err_response);
757
printf("Keep-Alive requests: %ld\n", doneka);
758
printf("Total transferred: %ld bytes\n", totalread);
760
printf("Total POSTed: %ld\n", totalposted);
761
printf("HTML transferred: %ld bytes\n", totalbread);
763
/* avoid divide by zero */
765
printf("Requests per second: %.2f [#/sec] (mean)\n",
766
(float) (done / timetaken));
767
printf("Time per request: %.3f [ms] (mean)\n",
768
(float) (1000 * concurrency * timetaken / done));
769
printf("Time per request: %.3f [ms] (mean, across all concurrent requests)\n",
770
(float) (1000 * timetaken / done));
771
printf("Transfer rate: %.2f [Kbytes/sec] received\n",
772
(float) (totalread / 1024 / timetaken));
774
printf(" %.2f kb/s sent\n",
775
(float) (totalposted / timetaken / 1024));
776
printf(" %.2f kb/s total\n",
777
(float) ((totalread + totalposted) / timetaken / 1024));
782
/* work out connection times */
784
apr_time_t totalcon = 0, total = 0, totald = 0, totalwait = 0;
785
apr_time_t meancon, meantot, meand, meanwait;
786
apr_interval_time_t mincon = AB_MAX, mintot = AB_MAX, mind = AB_MAX,
788
apr_interval_time_t maxcon = 0, maxtot = 0, maxd = 0, maxwait = 0;
789
apr_interval_time_t mediancon = 0, mediantot = 0, mediand = 0, medianwait = 0;
790
double sdtot = 0, sdcon = 0, sdd = 0, sdwait = 0;
792
for (i = 0; i < requests; i++) {
793
struct data s = stats[i];
794
mincon = ap_min(mincon, s.ctime);
795
mintot = ap_min(mintot, s.time);
796
mind = ap_min(mind, s.time - s.ctime);
797
minwait = ap_min(minwait, s.waittime);
799
maxcon = ap_max(maxcon, s.ctime);
800
maxtot = ap_max(maxtot, s.time);
801
maxd = ap_max(maxd, s.time - s.ctime);
802
maxwait = ap_max(maxwait, s.waittime);
806
totald += s.time - s.ctime;
807
totalwait += s.waittime;
809
meancon = totalcon / requests;
810
meantot = total / requests;
811
meand = totald / requests;
812
meanwait = totalwait / requests;
814
/* calculating the sample variance: the sum of the squared deviations, divided by n-1 */
815
for (i = 0; i < requests; i++) {
816
struct data s = stats[i];
818
a = ((double)s.time - meantot);
820
a = ((double)s.ctime - meancon);
822
a = ((double)s.time - (double)s.ctime - meand);
824
a = ((double)s.waittime - meanwait);
828
sdtot = (requests > 1) ? sqrt(sdtot / (requests - 1)) : 0;
829
sdcon = (requests > 1) ? sqrt(sdcon / (requests - 1)) : 0;
830
sdd = (requests > 1) ? sqrt(sdd / (requests - 1)) : 0;
831
sdwait = (requests > 1) ? sqrt(sdwait / (requests - 1)) : 0;
834
FILE *out = fopen(gnuplot, "w");
837
char tmstring[1024];/* XXXX */
839
perror("Cannot open gnuplot output file");
842
fprintf(out, "starttime\tseconds\tctime\tdtime\tttime\twait\n");
843
for (i = 0; i < requests; i++) {
844
apr_time_t diff = stats[i].time - stats[i].ctime;
846
sttime = stats[i].starttime;
847
(void) apr_ctime(tmstring, sttime);
848
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",
859
* XXX: what is better; this hideous cast of the compradre function; or
860
* the four warnings during compile ? dirkx just does not know and
863
qsort(stats, requests, sizeof(struct data),
864
(int (*) (const void *, const void *)) compradre);
865
if ((requests > 1) && (requests % 2))
866
mediancon = (stats[requests / 2].ctime + stats[requests / 2 + 1].ctime) / 2;
868
mediancon = stats[requests / 2].ctime;
870
qsort(stats, requests, sizeof(struct data),
871
(int (*) (const void *, const void *)) compri);
872
if ((requests > 1) && (requests % 2))
873
mediand = (stats[requests / 2].time + stats[requests / 2 + 1].time \
874
-stats[requests / 2].ctime - stats[requests / 2 + 1].ctime) / 2;
876
mediand = stats[requests / 2].time - stats[requests / 2].ctime;
878
qsort(stats, requests, sizeof(struct data),
879
(int (*) (const void *, const void *)) compwait);
880
if ((requests > 1) && (requests % 2))
881
medianwait = (stats[requests / 2].waittime + stats[requests / 2 + 1].waittime) / 2;
883
medianwait = stats[requests / 2].waittime;
885
qsort(stats, requests, sizeof(struct data),
886
(int (*) (const void *, const void *)) comprando);
887
if ((requests > 1) && (requests % 2))
888
mediantot = (stats[requests / 2].time + stats[requests / 2 + 1].time) / 2;
890
mediantot = stats[requests / 2].time;
892
printf("\nConnection Times (ms)\n");
895
#define CONF_FMT_STRING "%5" APR_TIME_T_FMT " %4d %5.1f %6" APR_TIME_T_FMT " %7" APR_TIME_T_FMT "\n"
896
printf(" min mean[+/-sd] median max\n");
897
printf("Connect: " CONF_FMT_STRING,
898
mincon, (int) (meancon + 0.5), sdcon, mediancon, maxcon);
899
printf("Processing: " CONF_FMT_STRING,
900
mind, (int) (meand + 0.5), sdd, mediand, maxd);
901
printf("Waiting: " CONF_FMT_STRING,
902
minwait, (int) (meanwait + 0.5), sdwait, medianwait, maxwait);
903
printf("Total: " CONF_FMT_STRING,
904
mintot, (int) (meantot + 0.5), sdtot, mediantot, maxtot);
905
#undef CONF_FMT_STRING
907
#define SANE(what,mean,median,sd) \
909
double d = (double)mean - median; \
912
printf("ERROR: The median and mean for " what " are more than twice the standard\n" \
913
" deviation apart. These results are NOT reliable.\n"); \
915
printf("WARNING: The median and mean for " what " are not within a normal deviation\n" \
916
" These results are probably not that reliable.\n"); \
918
SANE("the initial connection time", meancon, mediancon, sdcon);
919
SANE("the processing time", meand, mediand, sdd);
920
SANE("the waiting time", meanwait, medianwait, sdwait);
921
SANE("the total time", meantot, mediantot, sdtot);
924
printf(" min avg max\n");
925
#define CONF_FMT_STRING "%5" APR_TIME_T_FMT " %5" APR_TIME_T_FMT "%5" APR_TIME_T_FMT "\n"
926
printf("Connect: " CONF_FMT_STRING,
927
mincon, meancon, maxcon);
928
printf("Processing: " CONF_FMT_STRING,
929
mintot - mincon, meantot - meancon, maxtot - maxcon);
930
printf("Total: " CONF_FMT_STRING,
931
mintot, meantot, maxtot);
932
#undef CONF_FMT_STRING
936
/* Sorted on total connect times */
937
if (percentile && (requests > 1)) {
938
printf("\nPercentage of the requests served within a certain time (ms)\n");
939
for (i = 0; i < sizeof(percs) / sizeof(int); i++) {
941
printf(" 0%% <0> (never)\n");
942
else if (percs[i] >= 100)
943
printf(" 100%% %5" APR_TIME_T_FMT " (longest request)\n",
944
stats[requests - 1].time);
946
printf(" %d%% %5" APR_TIME_T_FMT "\n", percs[i],
947
stats[(int) (requests * percs[i] / 100)].time);
951
FILE *out = fopen(csvperc, "w");
954
perror("Cannot open CSV output file");
957
fprintf(out, "" "Percentage served" "," "Time in ms" "\n");
958
for (i = 0; i < 100; i++) {
963
t = stats[requests - 1].time;
965
t = stats[(int) (0.5 + requests * i / 100.0)].time;
966
fprintf(out, "%d,%e\n", i, (double)t);
974
/* --------------------------------------------------------- */
976
/* calculate and output results in HTML */
978
static void output_html_results(void)
982
endtime = apr_time_now();
983
timetaken = (long)((endtime - start) / 1000);
985
printf("\n\n<table %s>\n", tablestring);
986
printf("<tr %s><th colspan=2 %s>Server Software:</th>"
987
"<td colspan=2 %s>%s</td></tr>\n",
988
trstring, tdstring, tdstring, servername);
989
printf("<tr %s><th colspan=2 %s>Server Hostname:</th>"
990
"<td colspan=2 %s>%s</td></tr>\n",
991
trstring, tdstring, tdstring, hostname);
992
printf("<tr %s><th colspan=2 %s>Server Port:</th>"
993
"<td colspan=2 %s>%hd</td></tr>\n",
994
trstring, tdstring, tdstring, port);
995
printf("<tr %s><th colspan=2 %s>Document Path:</th>"
996
"<td colspan=2 %s>%s</td></tr>\n",
997
trstring, tdstring, tdstring, path);
998
printf("<tr %s><th colspan=2 %s>Document Length:</th>"
999
"<td colspan=2 %s>%" APR_SIZE_T_FMT " bytes</td></tr>\n",
1000
trstring, tdstring, tdstring, doclen);
1001
printf("<tr %s><th colspan=2 %s>Concurrency Level:</th>"
1002
"<td colspan=2 %s>%d</td></tr>\n",
1003
trstring, tdstring, tdstring, concurrency);
1004
printf("<tr %s><th colspan=2 %s>Time taken for tests:</th>"
1005
"<td colspan=2 %s>%" APR_INT64_T_FMT ".%03ld seconds</td></tr>\n",
1006
trstring, tdstring, tdstring, apr_time_sec(timetaken),
1007
(long)apr_time_usec(timetaken));
1008
printf("<tr %s><th colspan=2 %s>Complete requests:</th>"
1009
"<td colspan=2 %s>%ld</td></tr>\n",
1010
trstring, tdstring, tdstring, done);
1011
printf("<tr %s><th colspan=2 %s>Failed requests:</th>"
1012
"<td colspan=2 %s>%ld</td></tr>\n",
1013
trstring, tdstring, tdstring, bad);
1015
printf("<tr %s><td colspan=4 %s > (Connect: %d, Length: %d, Exceptions: %d)</td></tr>\n",
1016
trstring, tdstring, err_conn, err_length, err_except);
1018
printf("<tr %s><th colspan=2 %s>Non-2xx responses:</th>"
1019
"<td colspan=2 %s>%d</td></tr>\n",
1020
trstring, tdstring, tdstring, err_response);
1022
printf("<tr %s><th colspan=2 %s>Keep-Alive requests:</th>"
1023
"<td colspan=2 %s>%ld</td></tr>\n",
1024
trstring, tdstring, tdstring, doneka);
1025
printf("<tr %s><th colspan=2 %s>Total transferred:</th>"
1026
"<td colspan=2 %s>%ld bytes</td></tr>\n",
1027
trstring, tdstring, tdstring, totalread);
1029
printf("<tr %s><th colspan=2 %s>Total POSTed:</th>"
1030
"<td colspan=2 %s>%ld</td></tr>\n",
1031
trstring, tdstring, tdstring, totalposted);
1032
printf("<tr %s><th colspan=2 %s>HTML transferred:</th>"
1033
"<td colspan=2 %s>%ld bytes</td></tr>\n",
1034
trstring, tdstring, tdstring, totalbread);
1036
/* avoid divide by zero */
1038
printf("<tr %s><th colspan=2 %s>Requests per second:</th>"
1039
"<td colspan=2 %s>%.2f</td></tr>\n",
1040
trstring, tdstring, tdstring, 1000 * (float) (done) / timetaken);
1041
printf("<tr %s><th colspan=2 %s>Transfer rate:</th>"
1042
"<td colspan=2 %s>%.2f kb/s received</td></tr>\n",
1043
trstring, tdstring, tdstring, (float) (totalread) / timetaken);
1045
printf("<tr %s><td colspan=2 %s> </td>"
1046
"<td colspan=2 %s>%.2f kb/s sent</td></tr>\n",
1047
trstring, tdstring, tdstring,
1048
(float) (totalposted) / timetaken);
1049
printf("<tr %s><td colspan=2 %s> </td>"
1050
"<td colspan=2 %s>%.2f kb/s total</td></tr>\n",
1051
trstring, tdstring, tdstring,
1052
(float) (totalread + totalposted) / timetaken);
1056
/* work out connection times */
1058
apr_interval_time_t totalcon = 0, total = 0;
1059
apr_interval_time_t mincon = AB_MAX, mintot = AB_MAX;
1060
apr_interval_time_t maxcon = 0, maxtot = 0;
1062
for (i = 0; i < requests; i++) {
1063
struct data s = stats[i];
1064
mincon = ap_min(mincon, s.ctime);
1065
mintot = ap_min(mintot, s.time);
1066
maxcon = ap_max(maxcon, s.ctime);
1067
maxtot = ap_max(maxtot, s.time);
1068
totalcon += s.ctime;
1072
if (requests > 0) { /* avoid division by zero (if 0 requests) */
1073
printf("<tr %s><th %s colspan=4>Connnection Times (ms)</th></tr>\n",
1074
trstring, tdstring);
1075
printf("<tr %s><th %s> </th> <th %s>min</th> <th %s>avg</th> <th %s>max</th></tr>\n",
1076
trstring, tdstring, tdstring, tdstring, tdstring);
1077
printf("<tr %s><th %s>Connect:</th>"
1078
"<td %s>%5" APR_TIME_T_FMT "</td>"
1079
"<td %s>%5" APR_TIME_T_FMT "</td>"
1080
"<td %s>%5" APR_TIME_T_FMT "</td></tr>\n",
1081
trstring, tdstring, tdstring, mincon, tdstring, totalcon / requests, tdstring, maxcon);
1082
printf("<tr %s><th %s>Processing:</th>"
1083
"<td %s>%5" APR_TIME_T_FMT "</td>"
1084
"<td %s>%5" APR_TIME_T_FMT "</td>"
1085
"<td %s>%5" APR_TIME_T_FMT "</td></tr>\n",
1086
trstring, tdstring, tdstring, mintot - mincon, tdstring,
1087
(total / requests) - (totalcon / requests), tdstring, maxtot - maxcon);
1088
printf("<tr %s><th %s>Total:</th>"
1089
"<td %s>%5" APR_TIME_T_FMT "</td>"
1090
"<td %s>%5" APR_TIME_T_FMT "</td>"
1091
"<td %s>%5" APR_TIME_T_FMT "</td></tr>\n",
1092
trstring, tdstring, tdstring, mintot, tdstring, total / requests, tdstring, maxtot);
1094
printf("</table>\n");
1098
/* --------------------------------------------------------- */
1100
/* start asnchronous non-blocking connection */
1102
static void start_connect(struct connection * c)
1106
if (!(started < requests))
1116
apr_pool_destroy(c->ctx);
1117
apr_pool_create(&c->ctx, cntxt);
1119
if ((rv = apr_socket_create(&c->aprsock, destsa->family,
1120
SOCK_STREAM, 0, c->ctx)) != APR_SUCCESS) {
1121
apr_err("socket", rv);
1123
if ((rv = apr_socket_opt_set(c->aprsock, APR_SO_NONBLOCK, 1))
1125
apr_err("socket nonblock", rv);
1127
c->start = apr_time_now();
1133
if ((c->ssl = SSL_new(ssl_ctx)) == NULL) {
1134
BIO_printf(bio_err, "SSL_new failed.\n");
1135
ERR_print_errors(bio_err);
1139
apr_os_sock_get(&fd, c->aprsock);
1140
bio = BIO_new_socket(fd, BIO_NOCLOSE);
1141
SSL_set_bio(c->ssl, bio, bio);
1142
SSL_set_connect_state(c->ssl);
1143
if (verbosity >= 4) {
1144
BIO_set_callback(bio, ssl_print_cb);
1145
BIO_set_callback_arg(bio, bio_err);
1151
if ((rv = apr_socket_connect(c->aprsock, destsa)) != APR_SUCCESS) {
1152
if (APR_STATUS_IS_EINPROGRESS(rv)) {
1153
apr_pollfd_t new_pollfd;
1154
c->state = STATE_CONNECTING;
1156
new_pollfd.desc_type = APR_POLL_SOCKET;
1157
new_pollfd.reqevents = APR_POLLOUT;
1158
new_pollfd.desc.s = c->aprsock;
1159
new_pollfd.client_data = c;
1160
apr_pollset_add(readbits, &new_pollfd);
1164
apr_pollfd_t remove_pollfd;
1165
remove_pollfd.desc_type = APR_POLL_SOCKET;
1166
remove_pollfd.desc.s = c->aprsock;
1167
apr_pollset_remove(readbits, &remove_pollfd);
1168
apr_socket_close(c->aprsock);
1172
"\nTest aborted after 10 failures\n\n");
1173
apr_err("apr_socket_connect()", rv);
1175
c->state = STATE_UNCONNECTED;
1181
/* connected first time */
1182
c->state = STATE_CONNECTED;
1186
ssl_proceed_handshake(c);
1194
/* --------------------------------------------------------- */
1196
/* close down connection and save stats */
1198
static void close_connection(struct connection * c)
1200
if (c->read == 0 && c->keepalive) {
1202
* server has legitimately shut down an idle keep alive request
1205
good--; /* connection never happened */
1209
/* first time here */
1212
else if (c->bread != doclen) {
1217
if (done < requests) {
1219
if ((done) && heartbeatres && !(done % heartbeatres)) {
1220
fprintf(stderr, "Completed %ld requests\n", done);
1223
c->done = apr_time_now();
1225
s.starttime = c->start;
1226
s.ctime = ap_max(0, (c->connect - c->start) / 1000);
1227
s.time = ap_max(0, (c->done - c->start) / 1000);
1228
s.waittime = ap_max(0, (c->beginread - c->endwrite) / 1000);
1234
apr_pollfd_t remove_pollfd;
1235
remove_pollfd.desc_type = APR_POLL_SOCKET;
1236
remove_pollfd.desc.s = c->aprsock;
1237
apr_pollset_remove(readbits, &remove_pollfd);
1240
SSL_shutdown(c->ssl);
1245
apr_socket_close(c->aprsock);
1247
c->state = STATE_UNCONNECTED;
1254
/* --------------------------------------------------------- */
1256
/* read data from connection */
1258
static void read_connection(struct connection * c)
1261
apr_status_t status;
1263
char respcode[4]; /* 3 digits and null */
1268
status = SSL_read(c->ssl, buffer, r);
1270
int scode = SSL_get_error(c->ssl, status);
1272
if (scode == SSL_ERROR_ZERO_RETURN) {
1273
/* connection closed cleanly: */
1275
close_connection(c);
1277
else if (scode != SSL_ERROR_WANT_WRITE
1278
&& scode != SSL_ERROR_WANT_READ) {
1279
/* some fatal error: */
1281
BIO_printf(bio_err, "SSL read failed - closing connection\n");
1282
ERR_print_errors(bio_err);
1283
close_connection(c);
1292
status = apr_socket_recv(c->aprsock, buffer, &r);
1293
if (APR_STATUS_IS_EAGAIN(status))
1295
else if (r == 0 && APR_STATUS_IS_EOF(status)) {
1297
close_connection(c);
1300
/* catch legitimate fatal apr_socket_recv errors */
1301
else if (status != APR_SUCCESS) {
1302
err_except++; /* XXX: is this the right error counter? */
1303
/* XXX: Should errors here be fatal, or should we allow a
1304
* certain number of them before completely failing? -aaron */
1305
apr_err("apr_socket_recv", status);
1311
c->beginread = apr_time_now();
1316
if (!c->gotheader) {
1319
apr_size_t space = CBUFFSIZE - c->cbx - 1; /* -1 allows for \0 term */
1320
int tocopy = (space < r) ? space : r;
1322
apr_size_t inbytes_left = space, outbytes_left = space;
1324
status = apr_xlate_conv_buffer(from_ascii, buffer, &inbytes_left,
1325
c->cbuff + c->cbx, &outbytes_left);
1326
if (status || inbytes_left || outbytes_left) {
1327
fprintf(stderr, "only simple translation is supported (%d/%u/%u)\n",
1328
status, inbytes_left, outbytes_left);
1332
memcpy(c->cbuff + c->cbx, buffer, space);
1333
#endif /* NOT_ASCII */
1336
c->cbuff[c->cbx] = 0; /* terminate for benefit of strstr */
1337
if (verbosity >= 2) {
1338
printf("LOG: header received:\n%s\n", c->cbuff);
1340
s = strstr(c->cbuff, "\r\n\r\n");
1342
* this next line is so that we talk to NCSA 1.5 which blatantly
1343
* breaks the http specifaction
1346
s = strstr(c->cbuff, "\n\n");
1351
/* read rest next time */
1356
/* header is in invalid or too big - close connection */
1357
apr_pollfd_t remove_pollfd;
1358
remove_pollfd.desc_type = APR_POLL_SOCKET;
1359
remove_pollfd.desc.s = c->aprsock;
1360
apr_pollset_remove(readbits, &remove_pollfd);
1361
apr_socket_close(c->aprsock);
1364
err("\nTest aborted after 10 failures\n\n");
1370
/* have full header */
1373
* this is first time, extract some interesting info
1376
p = strstr(c->cbuff, "Server:");
1386
* XXX: this parsing isn't even remotely HTTP compliant... but in
1387
* the interest of speed it doesn't totally have to be, it just
1388
* needs to be extended to handle whatever servers folks want to
1389
* test against. -djg
1392
/* check response code */
1393
part = strstr(c->cbuff, "HTTP"); /* really HTTP/1.x_ */
1394
if (part && strlen(part) > strlen("HTTP/1.x_")) {
1395
strncpy(respcode, (part + strlen("HTTP/1.x_")), 3);
1399
strcpy(respcode, "500");
1402
if (respcode[0] != '2') {
1405
printf("WARNING: Response code not 2xx (%s)\n", respcode);
1407
else if (verbosity >= 3) {
1408
printf("LOG: Response code = %s\n", respcode);
1411
*s = 0; /* terminate at end of header */
1413
(strstr(c->cbuff, "Keep-Alive")
1414
|| strstr(c->cbuff, "keep-alive"))) { /* for benefit of MSIIS */
1416
cl = strstr(c->cbuff, "Content-Length:");
1417
/* handle NCSA, which sends Content-length: */
1419
cl = strstr(c->cbuff, "Content-length:");
1422
c->length = atoi(cl + 16);
1425
c->bread += c->cbx - (s + l - c->cbuff) + r - tocopy;
1426
totalbread += c->bread;
1430
/* outside header, everything we have read is entity body */
1435
if (c->keepalive && (c->bread >= c->length)) {
1436
/* finished a keep-alive connection */
1440
/* first time here */
1443
else if (c->bread != doclen) {
1447
if (done < requests) {
1450
if (done && heartbeatres && !(done % heartbeatres)) {
1451
fprintf(stderr, "Completed %ld requests\n", done);
1454
c->done = apr_time_now();
1456
s.starttime = c->start;
1457
s.ctime = ap_max(0, (c->connect - c->start) / 1000);
1458
s.waittime = ap_max(0, (c->beginread - c->endwrite) / 1000);
1459
s.time = ap_max(0, (c->done - c->start) / 1000);
1466
c->read = c->bread = 0;
1467
c->start = c->connect = apr_time_now(); /* zero connect time with keep-alive */
1472
/* --------------------------------------------------------- */
1476
static void test(void)
1481
apr_status_t status;
1482
int snprintf_res = 0;
1484
apr_size_t inbytes_left, outbytes_left;
1488
connecthost = apr_pstrdup(cntxt, proxyhost);
1489
connectport = proxyport;
1492
connecthost = apr_pstrdup(cntxt, hostname);
1497
printf("Benchmarking %s ", hostname);
1499
printf("[through %s:%d] ", proxyhost, proxyport);
1500
printf("(be patient)%s",
1501
(heartbeatres ? "\n" : "..."));
1505
now = apr_time_now();
1507
con = calloc(concurrency, sizeof(struct connection));
1509
stats = calloc(requests, sizeof(struct data));
1511
if ((status = apr_pollset_create(&readbits, concurrency, cntxt, 0)) != APR_SUCCESS) {
1512
apr_err("apr_pollset_create failed", status);
1517
snprintf_res = apr_snprintf(request, sizeof(_request),
1518
"%s %s HTTP/1.0\r\n"
1519
"User-Agent: ApacheBench/%s\r\n"
1524
(posting == 0) ? "GET" : "HEAD",
1525
(isproxy) ? fullurl : path,
1527
keepalive ? "Connection: Keep-Alive\r\n" : "",
1528
cookie, auth, host_field, colonhost, hdrs);
1531
snprintf_res = apr_snprintf(request, sizeof(_request),
1532
"POST %s HTTP/1.0\r\n"
1533
"User-Agent: ApacheBench/%s\r\n"
1537
"Content-length: %" APR_SIZE_T_FMT "\r\n"
1538
"Content-type: %s\r\n"
1541
(isproxy) ? fullurl : path,
1543
keepalive ? "Connection: Keep-Alive\r\n" : "",
1545
host_field, colonhost, postlen,
1546
(content_type[0]) ? content_type : "text/plain", hdrs);
1548
if (snprintf_res >= sizeof(_request)) {
1549
err("Request too long\n");
1553
printf("INFO: POST header == \n---\n%s\n---\n", request);
1555
reqlen = strlen(request);
1558
* Combine headers and (optional) post file into one contineous buffer
1561
char *buff = malloc(postlen + reqlen + 1);
1563
fprintf(stderr, "error creating request buffer: out of memory\n");
1566
strcpy(buff, request);
1567
memcpy(buff + reqlen, postdata, postlen);
1572
inbytes_left = outbytes_left = reqlen;
1573
status = apr_xlate_conv_buffer(to_ascii, request, &inbytes_left,
1574
request, &outbytes_left);
1575
if (status || inbytes_left || outbytes_left) {
1576
fprintf(stderr, "only simple translation is supported (%d/%u/%u)\n",
1577
status, inbytes_left, outbytes_left);
1580
#endif /* NOT_ASCII */
1582
/* This only needs to be done once */
1583
if ((rv = apr_sockaddr_info_get(&destsa, connecthost, APR_UNSPEC, connectport, 0, cntxt))
1586
apr_snprintf(buf, sizeof(buf),
1587
"apr_sockaddr_info_get() for %s", connecthost);
1591
/* ok - lets start */
1592
start = apr_time_now();
1594
/* initialise lots of requests */
1595
for (i = 0; i < concurrency; i++) {
1597
start_connect(&con[i]);
1600
while (done < requests) {
1603
const apr_pollfd_t *pollresults;
1605
/* check for time limit expiry */
1606
now = apr_time_now();
1607
timed = (apr_int32_t)apr_time_sec(now - start);
1608
if (tlimit && timed >= tlimit) {
1609
requests = done; /* so stats are correct */
1610
break; /* no need to do another round */
1614
status = apr_pollset_poll(readbits, aprtimeout, &n, &pollresults);
1615
if (status != APR_SUCCESS)
1616
apr_err("apr_poll", status);
1619
err("\nServer timed out\n\n");
1622
for (i = 0; i < n; i++) {
1623
const apr_pollfd_t *next_fd = &(pollresults[i]);
1624
struct connection *c;
1626
c = next_fd->client_data;
1629
* If the connection isn't connected how can we check it?
1631
if (c->state == STATE_UNCONNECTED)
1634
rv = next_fd->rtnevents;
1637
if (c->state == STATE_CONNECTED && c->ssl && SSL_in_init(c->ssl)) {
1638
ssl_proceed_handshake(c);
1644
* Notes: APR_POLLHUP is set after FIN is received on some
1645
* systems, so treat that like APR_POLLIN so that we try to read
1648
* Some systems return APR_POLLERR with APR_POLLHUP. We need to
1649
* call read_connection() for APR_POLLHUP, so check for
1650
* APR_POLLHUP first so that a closed connection isn't treated
1651
* like an I/O error. If it is, we never figure out that the
1652
* connection is done and we loop here endlessly calling
1655
if ((rv & APR_POLLIN) || (rv & APR_POLLPRI) || (rv & APR_POLLHUP))
1657
if ((rv & APR_POLLERR) || (rv & APR_POLLNVAL)) {
1663
if (rv & APR_POLLOUT) {
1664
if (c->state == STATE_CONNECTING) {
1665
apr_pollfd_t remove_pollfd;
1666
rv = apr_socket_connect(c->aprsock, destsa);
1667
remove_pollfd.desc_type = APR_POLL_SOCKET;
1668
remove_pollfd.desc.s = c->aprsock;
1669
apr_pollset_remove(readbits, &remove_pollfd);
1670
if (rv != APR_SUCCESS) {
1671
apr_socket_close(c->aprsock);
1675
"\nTest aborted after 10 failures\n\n");
1676
apr_err("apr_socket_connect()", rv);
1678
c->state = STATE_UNCONNECTED;
1683
c->state = STATE_CONNECTED;
1687
ssl_proceed_handshake(c);
1699
* When using a select based poll every time we check the bits
1700
* are reset. In 1.3's ab we copied the FD_SET's each time
1701
* through, but here we're going to check the state and if the
1702
* connection is in STATE_READ or STATE_CONNECTING we'll add the
1703
* socket back in as APR_POLLIN.
1705
if (c->state == STATE_READ) {
1706
apr_pollfd_t new_pollfd;
1707
new_pollfd.desc_type = APR_POLL_SOCKET;
1708
new_pollfd.reqevents = APR_POLLIN;
1709
new_pollfd.desc.s = c->aprsock;
1710
new_pollfd.client_data = c;
1711
apr_pollset_add(readbits, &new_pollfd);
1717
fprintf(stderr, "Finished %ld requests\n", done);
1722
output_html_results();
1727
/* ------------------------------------------------------- */
1729
/* display copyright information */
1730
static void copyright(void)
1733
printf("This is ApacheBench, Version %s\n", AP_AB_BASEREVISION " <$Revision: 1.146 $> apache-2.0");
1734
printf("Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\n");
1735
printf("Copyright 2006 The Apache Software Foundation, http://www.apache.org/\n");
1740
printf(" This is ApacheBench, Version %s <i><%s></i> apache-2.0<br>\n", AP_AB_BASEREVISION, "$Revision: 1.146 $");
1741
printf(" Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/<br>\n");
1742
printf(" Copyright 2006 The Apache Software Foundation, http://www.apache.org/<br>\n");
1743
printf("</p>\n<p>\n");
1747
/* display usage information */
1748
static void usage(const char *progname)
1750
fprintf(stderr, "Usage: %s [options] [http"
1754
"://]hostname[:port]/path\n", progname);
1755
fprintf(stderr, "Options are:\n");
1756
fprintf(stderr, " -n requests Number of requests to perform\n");
1757
fprintf(stderr, " -c concurrency Number of multiple requests to make\n");
1758
fprintf(stderr, " -t timelimit Seconds to max. wait for responses\n");
1759
fprintf(stderr, " -p postfile File containing data to POST\n");
1760
fprintf(stderr, " -T content-type Content-type header for POSTing\n");
1761
fprintf(stderr, " -v verbosity How much troubleshooting info to print\n");
1762
fprintf(stderr, " -w Print out results in HTML tables\n");
1763
fprintf(stderr, " -i Use HEAD instead of GET\n");
1764
fprintf(stderr, " -x attributes String to insert as table attributes\n");
1765
fprintf(stderr, " -y attributes String to insert as tr attributes\n");
1766
fprintf(stderr, " -z attributes String to insert as td or th attributes\n");
1767
fprintf(stderr, " -C attribute Add cookie, eg. 'Apache=1234. (repeatable)\n");
1768
fprintf(stderr, " -H attribute Add Arbitrary header line, eg. 'Accept-Encoding: gzip'\n");
1769
fprintf(stderr, " Inserted after all normal header lines. (repeatable)\n");
1770
fprintf(stderr, " -A attribute Add Basic WWW Authentication, the attributes\n");
1771
fprintf(stderr, " are a colon separated username and password.\n");
1772
fprintf(stderr, " -P attribute Add Basic Proxy Authentication, the attributes\n");
1773
fprintf(stderr, " are a colon separated username and password.\n");
1774
fprintf(stderr, " -X proxy:port Proxyserver and port number to use\n");
1775
fprintf(stderr, " -V Print version number and exit\n");
1776
fprintf(stderr, " -k Use HTTP KeepAlive feature\n");
1777
fprintf(stderr, " -d Do not show percentiles served table.\n");
1778
fprintf(stderr, " -S Do not show confidence estimators and warnings.\n");
1779
fprintf(stderr, " -g filename Output collected data to gnuplot format file.\n");
1780
fprintf(stderr, " -e filename Output CSV file with percentages served\n");
1781
fprintf(stderr, " -h Display usage information (this message)\n");
1783
fprintf(stderr, " -Z ciphersuite Specify SSL/TLS cipher suite (See openssl ciphers)\n");
1784
fprintf(stderr, " -f protocol Specify SSL/TLS protocol (SSL2, SSL3, TLS1, or ALL)\n");
1789
/* ------------------------------------------------------- */
1791
/* split URL into parts */
1793
static int parse_url(char *url)
1800
/* Save a copy for the proxy */
1801
fullurl = apr_pstrdup(cntxt, url);
1803
if (strlen(url) > 7 && strncmp(url, "http://", 7) == 0) {
1811
if (strlen(url) > 8 && strncmp(url, "https://", 8) == 0) {
1816
if (strlen(url) > 8 && strncmp(url, "https://", 8) == 0) {
1817
fprintf(stderr, "SSL not compiled in; no https support\n");
1822
if ((cp = strchr(url, '/')) == NULL)
1824
h = apr_palloc(cntxt, cp - url + 1);
1825
memcpy(h, url, cp - url);
1827
rv = apr_parse_addr_port(&hostname, &scope_id, &port, h, cntxt);
1828
if (rv != APR_SUCCESS || !hostname || scope_id) {
1831
path = apr_pstrdup(cntxt, cp);
1833
if (*url == '[') { /* IPv6 numeric address string */
1834
host_field = apr_psprintf(cntxt, "[%s]", hostname);
1837
host_field = hostname;
1840
if (port == 0) { /* no port specified */
1851
is_ssl && (port != 443)) || (!is_ssl &&
1855
colonhost = apr_psprintf(cntxt,":%d",port);
1861
/* ------------------------------------------------------- */
1863
/* read data to POST from file, save contents and length */
1865
static int open_postfile(const char *pfile)
1872
rv = apr_file_open(&postfd, pfile, APR_READ, APR_OS_DEFAULT, cntxt);
1873
if (rv != APR_SUCCESS) {
1874
fprintf(stderr, "ab: Could not open POST data file (%s): %s\n", pfile,
1875
apr_strerror(rv, errmsg, sizeof errmsg));
1879
apr_file_info_get(&finfo, APR_FINFO_NORM, postfd);
1880
postlen = (apr_size_t)finfo.size;
1881
postdata = malloc(postlen);
1883
fprintf(stderr, "ab: Could not allocate POST data buffer\n");
1886
rv = apr_file_read_full(postfd, postdata, postlen, NULL);
1887
if (rv != APR_SUCCESS) {
1888
fprintf(stderr, "ab: Could not read POST data file: %s\n",
1889
apr_strerror(rv, errmsg, sizeof errmsg));
1892
apr_file_close(postfd);
1896
/* ------------------------------------------------------- */
1898
/* sort out command-line args and call test */
1899
int main(int argc, const char * const argv[])
1903
apr_status_t status;
1908
SSL_METHOD *meth = SSLv23_client_method();
1911
/* table defaults */
1914
tdstring = "bgcolor=white";
1917
proxyhost[0] = '\0';
1920
apr_app_initialize(&argc, &argv, NULL);
1921
atexit(apr_terminate);
1922
apr_pool_create(&cntxt, NULL);
1925
status = apr_xlate_open(&to_ascii, "ISO-8859-1", APR_DEFAULT_CHARSET, cntxt);
1927
fprintf(stderr, "apr_xlate_open(to ASCII)->%d\n", status);
1930
status = apr_xlate_open(&from_ascii, APR_DEFAULT_CHARSET, "ISO-8859-1", cntxt);
1932
fprintf(stderr, "apr_xlate_open(from ASCII)->%d\n", status);
1935
status = apr_base64init_ebcdic(to_ascii, from_ascii);
1937
fprintf(stderr, "apr_base64init_ebcdic()->%d\n", status);
1942
apr_getopt_init(&opt, cntxt, argc, argv);
1943
while ((status = apr_getopt(opt, "n:c:t:T:p:v:kVhwix:y:z:C:H:P:A:g:X:de:Sq"
1947
,&c, &optarg)) == APR_SUCCESS) {
1950
requests = atoi(optarg);
1952
err("Invalid number of requests\n");
1962
concurrency = atoi(optarg);
1966
err("Cannot mix POST and HEAD\n");
1970
gnuplot = strdup(optarg);
1976
csvperc = strdup(optarg);
1983
err("Cannot mix POST and HEAD\n");
1984
if (0 == (r = open_postfile(optarg))) {
1987
else if (postdata) {
1992
verbosity = atoi(optarg);
1995
tlimit = atoi(optarg);
1996
requests = MAX_REQUESTS; /* need to size data array on
2000
strcpy(content_type, optarg);
2003
cookie = apr_pstrcat(cntxt, "Cookie: ", optarg, "\r\n", NULL);
2007
* assume username passwd already to be in colon separated form.
2008
* Ready to be uu-encoded.
2010
while (apr_isspace(*optarg))
2012
if (apr_base64_encode_len(strlen(optarg)) > sizeof(tmp)) {
2013
err("Authentication credentials too long\n");
2015
l = apr_base64_encode(tmp, optarg, strlen(optarg));
2018
auth = apr_pstrcat(cntxt, auth, "Authorization: Basic ", tmp,
2023
* assume username passwd already to be in colon separated form.
2025
while (apr_isspace(*optarg))
2027
if (apr_base64_encode_len(strlen(optarg)) > sizeof(tmp)) {
2028
err("Proxy credentials too long\n");
2030
l = apr_base64_encode(tmp, optarg, strlen(optarg));
2033
auth = apr_pstrcat(cntxt, auth, "Proxy-Authorization: Basic ",
2037
hdrs = apr_pstrcat(cntxt, hdrs, optarg, "\r\n", NULL);
2043
* if any of the following three are used, turn on html output
2048
tablestring = optarg;
2054
* assume proxy-name[:port]
2056
if ((p = strchr(optarg, ':'))) {
2059
proxyport = atoi(p);
2061
strcpy(proxyhost, optarg);
2081
ssl_cipher = strdup(optarg);
2084
if (strncasecmp(optarg, "ALL", 3) == 0) {
2085
meth = SSLv23_client_method();
2086
} else if (strncasecmp(optarg, "SSL2", 4) == 0) {
2087
meth = SSLv2_client_method();
2088
} else if (strncasecmp(optarg, "SSL3", 4) == 0) {
2089
meth = SSLv3_client_method();
2090
} else if (strncasecmp(optarg, "TLS1", 4) == 0) {
2091
meth = TLSv1_client_method();
2098
if (opt->ind != argc - 1) {
2099
fprintf(stderr, "%s: wrong number of arguments\n", argv[0]);
2103
if (parse_url(apr_pstrdup(cntxt, opt->argv[opt->ind++]))) {
2104
fprintf(stderr, "%s: invalid URL\n", argv[0]);
2108
if ((concurrency < 0) || (concurrency > MAX_CONCURRENCY)) {
2109
fprintf(stderr, "%s: Invalid Concurrency [Range 0..%d]\n",
2110
argv[0], MAX_CONCURRENCY);
2114
if (concurrency > requests) {
2115
fprintf(stderr, "%s: Cannot use concurrency level greater than "
2116
"total number of requests\n", argv[0]);
2120
if ((heartbeatres) && (requests > 150)) {
2121
heartbeatres = requests / 10; /* Print line every 10% of requests */
2122
if (heartbeatres < 100)
2123
heartbeatres = 100; /* but never more often than once every 100
2133
CRYPTO_malloc_init();
2135
SSL_load_error_strings();
2137
bio_out=BIO_new_fp(stdout,BIO_NOCLOSE);
2138
bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
2140
if (!(ssl_ctx = SSL_CTX_new(meth))) {
2141
BIO_printf(bio_err, "Could not initialize SSL Context.\n");
2142
ERR_print_errors(bio_err);
2145
SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL);
2146
if (ssl_cipher != NULL) {
2147
if (!SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher)) {
2148
fprintf(stderr, "error setting cipher list [%s]\n", ssl_cipher);
2149
ERR_print_errors_fp(stderr);
2153
if (verbosity >= 3) {
2154
SSL_CTX_set_info_callback(ssl_ctx, ssl_state_cb);
2158
apr_signal(SIGPIPE, SIG_IGN); /* Ignore writes to connections that
2159
* have been closed at the other end. */
2163
apr_pool_destroy(cntxt);