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