]> granicus.if.org Git - apache/blob - support/ab.c
catch out of memory condition (ID 29 of reasoning report)
[apache] / support / ab.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  * Portions of this software are based upon public domain software
55  * originally written at the National Center for Supercomputing Applications,
56  * University of Illinois, Urbana-Champaign.
57  */
58
59 /*
60    ** This program is based on ZeusBench V1.0 written by Adam Twiss
61    ** which is Copyright (c) 1996 by Zeus Technology Ltd. http://www.zeustech.net/
62    **
63    ** This software is provided "as is" and any express or implied waranties,
64    ** including but not limited to, the implied warranties of merchantability and
65    ** fitness for a particular purpose are disclaimed.  In no event shall
66    ** Zeus Technology Ltd. be liable for any direct, indirect, incidental, special,
67    ** exemplary, or consequential damaged (including, but not limited to,
68    ** procurement of substitute good or services; loss of use, data, or profits;
69    ** or business interruption) however caused and on theory of liability.  Whether
70    ** in contract, strict liability or tort (including negligence or otherwise)
71    ** arising in any way out of the use of this software, even if advised of the
72    ** possibility of such damage.
73    **
74  */
75
76 /*
77    ** HISTORY:
78    **    - Originally written by Adam Twiss <adam@zeus.co.uk>, March 1996
79    **      with input from Mike Belshe <mbelshe@netscape.com> and
80    **      Michael Campanella <campanella@stevms.enet.dec.com>
81    **    - Enhanced by Dean Gaudet <dgaudet@apache.org>, November 1997
82    **    - Cleaned up by Ralf S. Engelschall <rse@apache.org>, March 1998
83    **    - POST and verbosity by Kurt Sussman <kls@merlot.com>, August 1998
84    **    - HTML table output added by David N. Welton <davidw@prosa.it>, January 1999
85    **    - Added Cookie, Arbitrary header and auth support. <dirkx@webweaving.org>, April 1999
86    ** Version 1.3d
87    **    - Increased version number - as some of the socket/error handling has
88    **      fundamentally changed - and will give fundamentally different results
89    **      in situations where a server is dropping requests. Therefore you can
90    **      no longer compare results of AB as easily. Hence the inc of the version.
91    **      They should be closer to the truth though. Sander & <dirkx@covalent.net>, End 2000.
92    **    - Fixed proxy functionality, added median/mean statistics, added gnuplot
93    **      output option, added _experimental/rudimentary_ SSL support. Added
94    **      confidence guestimators and warnings. Sander & <dirkx@covalent.net>, End 2000
95    **    - Fixed serious int overflow issues which would cause realistic (longer
96    **      than a few minutes) run's to have wrong (but believable) results. Added
97    **      trapping of connection errors which influenced measurements.
98    **      Contributed by Sander Temme, Early 2001
99    ** Version 1.3e
100    **    - Changed timeout behavour during write to work whilst the sockets
101    **      are filling up and apr_write() does writes a few - but not all.
102    **      This will potentially change results. <dirkx@webweaving.org>, April 2001
103    ** Version 2.0.36-dev
104    **    Improvements to concurrent processing:
105    **      - Enabled non-blocking connect()s.
106    **      - Prevent blocking calls to apr_recv() (thereby allowing AB to
107    **        manage its entire set of socket descriptors).
108    **      - Any error returned from apr_recv() that is not EAGAIN or EOF
109    **        is now treated as fatal.
110    **      Contributed by Aaron Bannert, April 24, 2002
111    **
112    ** Version 2.0.36-2
113    **     Internalized the version string - this string is part
114    **     of the Agent: header and the result output.
115    **
116    ** Version 2.0.37-dev
117    **     Adopted SSL code by Madhu Mathihalli <madhusudan_mathihalli@hp.com>
118    **     [PATCH] ab with SSL support  Posted Wed, 15 Aug 2001 20:55:06 GMT
119    **     Introduces four 'if (int == value)' tests per non-ssl request.
120    **
121    ** Version 2.0.40-dev
122    **     Switched to the new abstract pollset API, allowing ab to
123    **     take advantage of future apr_pollset_t scalability improvements.
124    **     Contributed by Brian Pane, August 31, 2002
125    **/
126
127 /* Note: this version string should start with \d+[\d\.]* and be a valid
128  * string for an HTTP Agent: header when prefixed with 'ApacheBench/'. 
129  * It should reflect the version of AB - and not that of the apache server 
130  * it happens to accompany. And it should be updated or changed whenever 
131  * the results are no longer fundamentally comparable to the results of 
132  * a previous version of ab. Either due to a change in the logic of
133  * ab - or to due to a change in the distribution it is compiled with 
134  * (such as an APR change in for example blocking).
135  */
136 #define AP_AB_BASEREVISION "2.0.40-dev"    
137
138 /*
139  * BUGS:
140  *
141  * - uses strcpy/etc.
142  * - has various other poor buffer attacks related to the lazy parsing of
143  *   response headers from the server
144  * - doesn't implement much of HTTP/1.x, only accepts certain forms of
145  *   responses
146  * - (performance problem) heavy use of strstr shows up top in profile
147  *   only an issue for loopback usage
148  */
149
150 /*  -------------------------------------------------------------------- */
151
152 #if 'A' != 0x41
153 /* Hmmm... This source code isn't being compiled in ASCII.
154  * In order for data that flows over the network to make
155  * sense, we need to translate to/from ASCII.
156  */
157 #define NOT_ASCII
158 #endif
159
160 /* affects include files on Solaris */
161 #define BSD_COMP
162
163 #include "apr.h"
164 #include "apr_signal.h"
165 #include "apr_strings.h"
166 #include "apr_network_io.h"
167 #include "apr_file_io.h"
168 #include "apr_time.h"
169 #include "apr_getopt.h"
170 #include "apr_general.h"
171 #include "apr_lib.h"
172 #include "apr_portable.h"
173 #include "ap_release.h"
174 #include "apr_poll.h"
175
176 #define APR_WANT_STRFUNC
177 #include "apr_want.h"
178
179 #include "apr_base64.h"
180 #ifdef NOT_ASCII
181 #include "apr_xlate.h"
182 #endif
183 #if APR_HAVE_STDIO_H
184 #include <stdio.h>
185 #endif
186 #if APR_HAVE_STDLIB_H
187 #include <stdlib.h>
188 #endif
189
190 #if !defined(WIN32) && !defined(NETWARE)
191 #include "ap_config_auto.h"
192 #endif
193
194 #if defined(HAVE_SSLC)
195
196 /* Libraries for RSA SSL-C */
197 #include <rsa.h>
198 #include <x509.h>
199 #include <pem.h>
200 #include <err.h>
201 #include <ssl.h>
202 #include <r_rand.h>
203 #include <sslc.h>
204 #define USE_SSL
205 #define RSAREF
206
207 #elif defined(HAVE_OPENSSL)
208
209 /* Libraries on most systems.. */
210 #include <openssl/rsa.h>
211 #include <openssl/crypto.h>
212 #include <openssl/x509.h>
213 #include <openssl/pem.h>
214 #include <openssl/err.h>
215 #include <openssl/ssl.h>
216 #include <openssl/rand.h>
217 #define USE_SSL
218
219 #endif
220
221 #include <math.h>
222 #if APR_HAVE_CTYPE_H
223 #include <ctype.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 50000
236
237 /* good old state hostname */
238 #define STATE_UNCONNECTED 0
239 #define STATE_CONNECTING  1
240 #define STATE_READ        2
241
242 #define CBUFFSIZE (2048)
243
244 struct connection {
245     apr_pool_t *ctx;
246     apr_socket_t *aprsock;
247     int state;
248     apr_size_t read;            /* amount of bytes read */
249     apr_size_t bread;           /* amount of body read */
250     apr_size_t rwrite, rwrote;  /* keep pointers in what we write - across
251                                  * EAGAINs */
252     apr_size_t length;          /* Content-Length value used for keep-alive */
253     char cbuff[CBUFFSIZE];      /* a buffer to store server response header */
254     int cbx;                    /* offset in cbuffer */
255     int keepalive;              /* non-zero if a keep-alive request */
256     int gotheader;              /* non-zero if we have the entire header in
257                                  * cbuff */
258     apr_time_t start,           /* Start of connection */
259                connect,         /* Connected, start writing */
260                endwrite,        /* Request written */
261                beginread,       /* First byte of input */
262                done;            /* Connection closed */
263
264     int socknum;
265 #ifdef USE_SSL
266     SSL *ssl;
267 #endif
268 };
269
270 struct data {
271 #ifdef USE_SSL
272     /* XXXX insert SSL timings */
273 #endif
274     int read;              /* number of bytes read */
275     apr_time_t starttime;  /* start time of connection in seconds since
276                             * Jan. 1, 1970 */
277     apr_interval_time_t waittime;   /* Between writing request and reading
278                                      * response */
279     apr_interval_time_t ctime;      /* time in ms to connect */
280     apr_interval_time_t time;       /* time in ms for connection */
281 };
282
283 #define ap_min(a,b) ((a)<(b))?(a):(b)
284 #define ap_max(a,b) ((a)>(b))?(a):(b)
285
286 /* --------------------- GLOBALS ---------------------------- */
287
288 int verbosity = 0;              /* no verbosity by default */
289 int posting = 0;                /* GET by default */
290 int requests = 1;               /* Number of requests to make */
291 int heartbeatres = 100;         /* How often do we say we're alive */
292 int concurrency = 1;            /* Number of multiple requests to make */
293 int percentile = 1;             /* Show percentile served */
294 int confidence = 1;             /* Show confidence estimator and warnings */
295 int tlimit = 0;                 /* time limit in secs */
296 int keepalive = 0;              /* try and do keepalive connections */
297 char servername[1024];          /* name that server reports */
298 char *hostname;                 /* host name from URL */
299 char *host_field;               /* value of "Host:" header field */
300 char *path;                     /* path name */
301 char postfile[1024];            /* name of file containing post data */
302 char *postdata;                 /* *buffer containing data from postfile */
303 apr_size_t postlen = 0;         /* length of data to be POSTed */
304 char content_type[1024];        /* content type to put in POST header */
305 char *cookie,                   /* optional cookie line */
306      *auth,                     /* optional (basic/uuencoded) auhentication */
307      *hdrs;                     /* optional arbitrary headers */
308 apr_port_t port;                /* port number */
309 char proxyhost[1024];           /* proxy host name */
310 int proxyport = 0;              /* proxy port */
311 char *connecthost;
312 apr_port_t connectport;
313 char *gnuplot;                  /* GNUplot file */
314 char *csvperc;                  /* CSV Percentile file */
315 char url[1024];
316 char * fullurl, * colonhost;
317 int isproxy = 0;
318 apr_interval_time_t aprtimeout = apr_time_from_sec(30); /* timeout value */
319  /*
320   * XXX - this is now a per read/write transact type of value
321   */
322
323 int use_html = 0;               /* use html in the report */
324 const char *tablestring;
325 const char *trstring;
326 const char *tdstring;
327
328 apr_size_t doclen = 0;          /* the length the document should be */
329 long started = 0;               /* number of requests started, so no excess */
330 long totalread = 0;             /* total number of bytes read */
331 long totalbread = 0;            /* totoal amount of entity body read */
332 long totalposted = 0;           /* total number of bytes posted, inc. headers */
333 long done = 0;                  /* number of requests we have done */
334 long doneka = 0;                /* number of keep alive connections done */
335 long good = 0, bad = 0;         /* number of good and bad requests */
336 long epipe = 0;                 /* number of broken pipe writes */
337
338 #ifdef USE_SSL
339 int ssl = 0;
340 SSL_CTX *ctx;
341 BIO *bio_out,*bio_err;
342 static void write_request(struct connection * c);
343 #endif
344
345 /* store error cases */
346 int err_length = 0, err_conn = 0, err_except = 0;
347 int err_response = 0;
348
349 apr_time_t start, endtime;
350
351 /* global request (and its length) */
352 char _request[512];
353 char *request = _request;
354 apr_size_t reqlen;
355
356 /* one global throw-away buffer to read stuff into */
357 char buffer[8192];
358
359 /* interesting percentiles */
360 int percs[] = {50, 66, 75, 80, 90, 95, 98, 99, 100};
361
362 struct connection *con;         /* connection array */
363 struct data *stats;             /* date for each request */
364 apr_pool_t *cntxt;
365
366 apr_pollset_t *readbits;
367
368 apr_sockaddr_t *destsa;
369
370 #ifdef NOT_ASCII
371 apr_xlate_t *from_ascii, *to_ascii;
372 #endif
373
374 static void close_connection(struct connection * c);
375 /* --------------------------------------------------------- */
376
377 /* simple little function to write an error string and exit */
378
379 static void err(char *s)
380 {
381     fprintf(stderr, "%s\n", s);
382     if (done)
383         printf("Total of %ld requests completed\n" , done);
384     exit(1);
385 }
386
387 /* simple little function to write an APR error string and exit */
388
389 static void apr_err(char *s, apr_status_t rv)
390 {
391     char buf[120];
392
393     fprintf(stderr,
394             "%s: %s (%d)\n",
395             s, apr_strerror(rv, buf, sizeof buf), rv);
396     if (done)
397         printf("Total of %ld requests completed\n" , done);
398     exit(rv);
399 }
400
401 #if defined(USE_SSL) && USE_THREADS
402 /*
403  * To ensure thread-safetyness in OpenSSL - work in progress
404  */
405
406 static apr_thread_mutex_t **lock_cs;
407 static int                  lock_num_locks;
408
409 static void ssl_util_thr_lock(int mode, int type,
410                               const char *file, int line)
411 {
412     if (type < lock_num_locks) {
413         if (mode & CRYPTO_LOCK) {
414             apr_thread_mutex_lock(lock_cs[type]);
415         }
416         else {
417             apr_thread_mutex_unlock(lock_cs[type]);
418         }
419     }
420 }
421
422 static unsigned long ssl_util_thr_id(void)
423 {
424     /* OpenSSL needs this to return an unsigned long.  On OS/390, the pthread 
425      * id is a structure twice that big.  Use the TCB pointer instead as a 
426      * unique unsigned long.
427      */
428 #ifdef __MVS__
429     struct PSA {
430         char unmapped[540];
431         unsigned long PSATOLD;
432     } *psaptr = 0;
433
434     return psaptr->PSATOLD;
435 #else
436     return (unsigned long) apr_os_thread_current();
437 #endif
438 }
439
440 static apr_status_t ssl_util_thread_cleanup(void *data)
441 {
442     CRYPTO_set_locking_callback(NULL);
443
444     /* Let the registered mutex cleanups do their own thing 
445      */
446     return APR_SUCCESS;
447 }
448
449 void ssl_util_thread_setup(apr_pool_t *p)
450 {
451     int i;
452
453     lock_num_locks = CRYPTO_num_locks();
454     lock_cs = apr_palloc(p, lock_num_locks * sizeof(*lock_cs));
455
456     for (i = 0; i < lock_num_locks; i++) {
457         apr_thread_mutex_create(&(lock_cs[i]), APR_THREAD_MUTEX_DEFAULT, p);
458     }
459
460     CRYPTO_set_id_callback(ssl_util_thr_id);
461
462     CRYPTO_set_locking_callback(ssl_util_thr_lock);
463
464     apr_pool_cleanup_register(p, NULL, ssl_util_thread_cleanup,
465                                        apr_pool_cleanup_null);
466 }
467 #endif
468
469 /* --------------------------------------------------------- */
470 /* write out request to a connection - assumes we can write
471  * (small) request out in one go into our new socket buffer
472  *
473  */
474 #ifdef USE_SSL
475 long ssl_print_cb(BIO *bio,int cmd,const char *argp,int argi,long argl,long ret)
476 {
477     BIO *out;
478
479     out=(BIO *)BIO_get_callback_arg(bio);
480     if (out == NULL) return(ret);
481
482     if (cmd == (BIO_CB_READ|BIO_CB_RETURN))
483     {
484         BIO_printf(out,"read from %08X [%08lX] (%d bytes => %ld (0x%X))\n",
485                 bio,argp,argi,ret,ret);
486         BIO_dump(out,(char *)argp,(int)ret);
487         return(ret);
488     }
489     else if (cmd == (BIO_CB_WRITE|BIO_CB_RETURN))
490     {
491         BIO_printf(out,"write to %08X [%08lX] (%d bytes => %ld (0x%X))\n",
492             bio,argp,argi,ret,ret);
493         BIO_dump(out,(char *)argp,(int)ret);
494     }
495     return(ret);
496 }
497
498 #ifndef RAND_MAX
499 #include <limits.h>
500 #define RAND_MAX INT_MAX
501 #endif
502
503 static int ssl_rand_choosenum(int l, int h)
504 {
505     int i;
506     char buf[50];
507
508     srand((unsigned int)time(NULL));
509     apr_snprintf(buf, sizeof(buf), "%.0f",
510                  (((double)(rand()%RAND_MAX)/RAND_MAX)*(h-l)));
511     i = atoi(buf)+1;
512     if (i < l) i = l;
513     if (i > h) i = h;
514     return i;
515 }
516
517 void ssl_rand_seed()
518 {
519     int nDone = 0;
520     int n, l;
521     time_t t;
522     pid_t pid;
523     unsigned char stackdata[256];
524
525     /*
526      * seed in the current time (usually just 4 bytes)
527      */
528     t = time(NULL);
529     l = sizeof(time_t);
530     RAND_seed((unsigned char *)&t, l);
531     nDone += l;
532
533     /*
534      * seed in the current process id (usually just 4 bytes)
535      */
536     pid = getpid();
537     l = sizeof(pid_t);
538     RAND_seed((unsigned char *)&pid, l);
539     nDone += l;
540
541     /*
542      * seed in some current state of the run-time stack (128 bytes)
543      */
544     n = ssl_rand_choosenum(0, sizeof(stackdata)-128-1);
545     RAND_seed(stackdata+n, 128);
546     nDone += 128;
547 }
548
549 int ssl_print_connection_info(bio,ssl)
550 BIO *bio;
551 SSL *ssl;
552 {
553         SSL_CIPHER *c;
554         int alg_bits,bits;
555
556         c=SSL_get_current_cipher(ssl);
557         BIO_printf(bio,"Cipher Suite Protocol   :%s\n", SSL_CIPHER_get_version(c));
558         BIO_printf(bio,"Cipher Suite Name       :%s\n",SSL_CIPHER_get_name(c));
559
560         bits=SSL_CIPHER_get_bits(c,&alg_bits);
561         BIO_printf(bio,"Cipher Suite Cipher Bits:%d (%d)\n",bits,alg_bits);
562
563         return(1);
564 }
565
566 int ssl_print_cert_info(bio,x509cert)
567 BIO *bio;
568 X509 *x509cert;
569 {
570         X509_NAME *dn;
571         char buf[64];
572
573         BIO_printf(bio,"Certificate version: %d\n",X509_get_version(x509cert)+1);
574
575         BIO_printf(bio,"Valid from: ");
576         ASN1_UTCTIME_print(bio, X509_get_notBefore(x509cert));
577         BIO_printf(bio,"\n");
578
579         BIO_printf(bio,"Valid to  : ");
580         ASN1_UTCTIME_print(bio, X509_get_notAfter(x509cert));
581         BIO_printf(bio,"\n");
582
583         BIO_printf(bio,"Public key is %d bits\n",
584             EVP_PKEY_bits(X509_get_pubkey(x509cert)));
585
586         dn=X509_get_issuer_name(x509cert);
587         X509_NAME_oneline(dn, buf, BUFSIZ);
588         BIO_printf(bio,"The issuer name is %s\n", buf);
589
590         dn=X509_get_subject_name(x509cert);
591         X509_NAME_oneline(dn, buf, BUFSIZ);
592         BIO_printf(bio,"The subject name is %s\n", buf);
593
594         /* dump the extension list too */
595         BIO_printf(bio,"Extension Count: %d\n",X509_get_ext_count(x509cert));
596
597         return(1);
598 }
599
600 void ssl_start_connect(struct connection * c)
601 {
602     BIO *bio;
603     X509 *x509cert;
604 #ifdef RSAREF
605     STACK *sk;
606 #else
607     STACK_OF(X509) *sk;
608 #endif
609     int i, count, hdone = 0;
610     char ssl_hostname[80];
611     
612     /* XXX - Verify if it's okay - TBD */
613     if (requests < concurrency)
614         requests = concurrency;
615
616     if (!(started < requests))
617         return;
618
619     c->read = 0;
620     c->bread = 0;
621     c->keepalive = 0;
622     c->cbx = 0;
623     c->gotheader = 0;
624     c->rwrite = 0;
625     if (c->ctx)
626         apr_pool_destroy(c->ctx);
627     apr_pool_create(&c->ctx, cntxt);
628
629     if ((c->ssl=SSL_new(ctx)) == NULL)
630     {
631         BIO_printf(bio_err,"SSL_new failed\n");
632         exit(1);
633     }
634
635     ssl_rand_seed();
636
637     c->start = apr_time_now();
638     memset(ssl_hostname, 0, 80);
639     sprintf(ssl_hostname, "%s:%d", hostname, port);
640
641     if ((bio = BIO_new_connect(ssl_hostname)) == NULL)
642     {
643         BIO_printf(bio_err,"BIO_new_connect failed\n");
644         exit(1);
645     }
646     SSL_set_bio(c->ssl,bio,bio);
647     SSL_set_connect_state(c->ssl);
648
649     if (verbosity >= 4)
650     {
651         BIO_set_callback(bio,ssl_print_cb);
652         BIO_set_callback_arg(bio,(void*)bio_err);
653     }
654
655     while (!hdone)
656     {
657         i = SSL_do_handshake(c->ssl);
658
659         switch (SSL_get_error(c->ssl,i))
660         {
661             case SSL_ERROR_NONE:
662                 hdone=1;
663                 break;
664             case SSL_ERROR_SSL:
665             case SSL_ERROR_SYSCALL:
666                 BIO_printf(bio_err,"SSL connection failed\n");
667                 err_conn++;
668                 c->state = STATE_UNCONNECTED;
669                 if (bad++ > 10) {
670                     SSL_free (c->ssl);
671                     BIO_printf(bio_err,"\nTest aborted after 10 failures\n\n");
672                     exit (1);
673                 }
674                 break;
675             case SSL_ERROR_WANT_READ:
676             case SSL_ERROR_WANT_WRITE:
677             case SSL_ERROR_WANT_CONNECT:
678                 BIO_printf(bio_err, "Waiting .. sleep(1)\n");
679                 apr_sleep(apr_time_from_sec(1));
680                 c->state = STATE_CONNECTING;
681                 c->rwrite = 0;
682                 break;
683             case SSL_ERROR_ZERO_RETURN:
684                 BIO_printf(bio_err,"socket closed\n");
685                 break;
686         }
687     }
688     
689     if (verbosity >= 2)
690     {
691         BIO_printf(bio_err, "\n");
692         sk = SSL_get_peer_cert_chain(c->ssl);
693 #ifdef RSAREF
694         if ((count = sk_num(sk)) > 0)
695 #else
696         if ((count = sk_X509_num(sk)) > 0)
697 #endif
698         {
699             for (i=1; i<count; i++)
700             {
701 #ifdef RSAREF
702                 x509cert = (X509 *)sk_value(sk,i);
703 #else
704                 x509cert = (X509 *)sk_X509_value(sk,i);
705 #endif
706                 ssl_print_cert_info(bio_out,x509cert);
707                 X509_free(x509cert);
708             }
709         }
710
711         x509cert = SSL_get_peer_certificate(c->ssl);
712         if (x509cert == NULL)
713             BIO_printf(bio_out, "Anon DH\n");
714         else
715         {
716             BIO_printf(bio_out, "Peer certificate\n");
717             ssl_print_cert_info(bio_out,x509cert);
718             X509_free(x509cert);
719         }
720
721         ssl_print_connection_info(bio_err,c->ssl);
722         SSL_SESSION_print(bio_err,SSL_get_session(c->ssl));
723     }
724
725     /* connected first time */
726     started++;
727     write_request(c);
728 }
729 #endif /* USE_SSL */
730
731 static void write_request(struct connection * c)
732 {
733     do {
734         apr_time_t tnow = apr_time_now();
735         apr_size_t l = c->rwrite;
736         apr_status_t e;
737
738         /*
739          * First time round ?
740          */
741         if (c->rwrite == 0) {
742 #ifdef USE_SSL
743             if (ssl != 1)
744 #endif
745             apr_socket_timeout_set(c->aprsock, 0);
746             c->connect = tnow;
747             c->rwrite = reqlen;
748             c->rwrote = 0;
749             if (posting)
750                 c->rwrite += postlen;
751         }
752         else if (tnow > c->connect + aprtimeout) {
753             printf("Send request timed out!\n");
754             close_connection(c);
755             return;
756         }
757
758 #ifdef USE_SSL
759         if (ssl == 1) {
760             apr_size_t e_ssl;
761             e_ssl = SSL_write(c->ssl,request + c->rwrote, l);
762             if (e_ssl != l)
763             {
764                 printf("SSL write failed - closing connection\n");
765                 close_connection (c);
766                 return;
767             }
768             l = e_ssl;
769         }
770         else
771 #endif
772         e = apr_send(c->aprsock, request + c->rwrote, &l);
773
774         /*
775          * Bail early on the most common case
776          */
777         if (l == c->rwrite)
778             break;
779
780 #ifdef USE_SSL
781         if (ssl != 1)
782         if (e != APR_SUCCESS) {
783             /*
784              * Let's hope this traps EWOULDBLOCK too !
785              */
786             if (!APR_STATUS_IS_EAGAIN(e)) {
787                 epipe++;
788                 printf("Send request failed!\n");
789                 close_connection(c);
790             }
791             return;
792         }
793 #endif
794         c->rwrote += l;
795         c->rwrite -= l;
796     } while (1);
797
798     totalposted += c->rwrite;
799     c->state = STATE_READ;
800     c->endwrite = apr_time_now();
801 #ifdef USE_SSL
802     if (ssl != 1)
803 #endif
804     {
805         apr_pollfd_t new_pollfd;
806         new_pollfd.desc_type = APR_POLL_SOCKET;
807         new_pollfd.reqevents = APR_POLLIN;
808         new_pollfd.desc.s = c->aprsock;
809         new_pollfd.client_data = c;
810         apr_pollset_add(readbits, &new_pollfd);
811     }
812 }
813
814 /* --------------------------------------------------------- */
815
816 /* calculate and output results */
817
818 static int compradre(struct data * a, struct data * b)
819 {
820     if ((a->ctime) < (b->ctime))
821         return -1;
822     if ((a->ctime) > (b->ctime))
823         return +1;
824     return 0;
825 }
826
827 static int comprando(struct data * a, struct data * b)
828 {
829     if ((a->time) < (b->time))
830         return -1;
831     if ((a->time) > (b->time))
832         return +1;
833     return 0;
834 }
835
836 static int compri(struct data * a, struct data * b)
837 {
838     apr_interval_time_t p = a->time - a->ctime;
839     apr_interval_time_t q = b->time - b->ctime;
840     if (p < q)
841         return -1;
842     if (p > q)
843         return +1;
844     return 0;
845 }
846
847 static int compwait(struct data * a, struct data * b)
848 {
849     if ((a->waittime) < (b->waittime))
850         return -1;
851     if ((a->waittime) > (b->waittime))
852         return 1;
853     return 0;
854 }
855
856 static void output_results(void)
857 {
858     apr_interval_time_t timetakenusec;
859     float timetaken;
860
861     endtime = apr_time_now();
862     timetakenusec = endtime - start;
863     timetaken = ((float)apr_time_sec(timetakenusec)) +
864         ((float)apr_time_usec(timetakenusec)) / 1000000.0F;
865     
866     printf("\n\n");
867     printf("Server Software:        %s\n", servername);
868     printf("Server Hostname:        %s\n", hostname);
869     printf("Server Port:            %hd\n", port);
870     printf("\n");
871     printf("Document Path:          %s\n", path);
872     printf("Document Length:        %" APR_SIZE_T_FMT " bytes\n", doclen);
873     printf("\n");
874     printf("Concurrency Level:      %d\n", concurrency);
875     printf("Time taken for tests:   %ld.%03ld seconds\n",
876            (long) apr_time_sec(timetakenusec),
877            (long) apr_time_usec(timetakenusec));
878     printf("Complete requests:      %ld\n", done);
879     printf("Failed requests:        %ld\n", bad);
880     if (bad)
881         printf("   (Connect: %d, Length: %d, Exceptions: %d)\n",
882                err_conn, err_length, err_except);
883     printf("Write errors:           %ld\n", epipe);
884     if (err_response)
885         printf("Non-2xx responses:      %d\n", err_response);
886     if (keepalive)
887         printf("Keep-Alive requests:    %ld\n", doneka);
888     printf("Total transferred:      %ld bytes\n", totalread);
889     if (posting > 0)
890         printf("Total POSTed:           %ld\n", totalposted);
891     printf("HTML transferred:       %ld bytes\n", totalbread);
892
893     /* avoid divide by zero */
894     if (timetaken) {
895         printf("Requests per second:    %.2f [#/sec] (mean)\n", 
896                (float) (done / timetaken));
897         printf("Time per request:       %.3f [ms] (mean)\n", 
898                (float) (1000 * concurrency * timetaken / done));
899         printf("Time per request:       %.3f [ms] (mean, across all concurrent requests)\n",
900                (float) (1000 * timetaken / done));
901         printf("Transfer rate:          %.2f [Kbytes/sec] received\n",
902                (float) (totalread / 1024 / timetaken));
903         if (posting > 0) {
904             printf("                        %.2f kb/s sent\n",
905                    (float) (totalposted / timetaken / 1024));
906             printf("                        %.2f kb/s total\n",
907                    (float) ((totalread + totalposted) / timetaken / 1024));
908         }
909     }
910
911     if (requests) {
912         /* work out connection times */
913         long i;
914         apr_time_t totalcon = 0, total = 0, totald = 0, totalwait = 0;
915         apr_interval_time_t mincon = AB_MAX, mintot = AB_MAX, mind = AB_MAX, 
916                             minwait = AB_MAX;
917         apr_interval_time_t maxcon = 0, maxtot = 0, maxd = 0, maxwait = 0;
918         apr_interval_time_t meancon = 0, meantot = 0, meand = 0, meanwait = 0;
919         double sdtot = 0, sdcon = 0, sdd = 0, sdwait = 0;
920
921         for (i = 0; i < requests; i++) {
922             struct data s = stats[i];
923             mincon = ap_min(mincon, s.ctime);
924             mintot = ap_min(mintot, s.time);
925             mind = ap_min(mind, s.time - s.ctime);
926             minwait = ap_min(minwait, s.waittime);
927
928             maxcon = ap_max(maxcon, s.ctime);
929             maxtot = ap_max(maxtot, s.time);
930             maxd = ap_max(maxd, s.time - s.ctime);
931             maxwait = ap_max(maxwait, s.waittime);
932
933             totalcon += s.ctime;
934             total += s.time;
935             totald += s.time - s.ctime;
936             totalwait += s.waittime;
937         }
938         totalcon /= requests;
939         total /= requests;
940         totald /= requests;
941         totalwait /= requests;
942
943         for (i = 0; i < requests; i++) {
944             struct data s = stats[i];
945             double a;
946             a = ((double)s.time - total);
947             sdtot += a * a;
948             a = ((double)s.ctime - totalcon);
949             sdcon += a * a;
950             a = ((double)s.time - (double)s.ctime - totald);
951             sdd += a * a;
952             a = ((double)s.waittime - totalwait);
953             sdwait += a * a;
954         }
955
956         sdtot = (requests > 1) ? sqrt(sdtot / (requests - 1)) : 0;
957         sdcon = (requests > 1) ? sqrt(sdcon / (requests - 1)) : 0;
958         sdd = (requests > 1) ? sqrt(sdd / (requests - 1)) : 0;
959         sdwait = (requests > 1) ? sqrt(sdwait / (requests - 1)) : 0;
960
961         if (gnuplot) {
962             FILE *out = fopen(gnuplot, "w");
963             long i;
964             apr_time_t sttime;
965             char tmstring[1024];/* XXXX */
966             if (!out) {
967                 perror("Cannot open gnuplot output file");
968                 exit(1);
969             }
970             fprintf(out, "starttime\tseconds\tctime\tdtime\tttime\twait\n");
971             for (i = 0; i < requests; i++) {
972                 apr_time_t diff = stats[i].time - stats[i].ctime;
973
974                 sttime = stats[i].starttime;
975                 (void) apr_ctime(tmstring, sttime);
976                 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",
977                         tmstring,
978                         sttime,
979                         stats[i].ctime,
980                         diff,
981                         stats[i].time,
982                         stats[i].waittime);
983             }
984             fclose(out);
985         }
986     /*
987      * XXX: what is better; this hideous cast of the compradre function; or
988      * the four warnings during compile ? dirkx just does not know and
989      * hates both/
990      */
991         qsort(stats, requests, sizeof(struct data),
992               (int (*) (const void *, const void *)) compradre);
993         if ((requests > 1) && (requests % 2))
994             meancon = (stats[requests / 2].ctime + stats[requests / 2 + 1].ctime) / 2;
995         else
996             meancon = stats[requests / 2].ctime;
997
998         qsort(stats, requests, sizeof(struct data),
999               (int (*) (const void *, const void *)) compri);
1000         if ((requests > 1) && (requests % 2))
1001             meand = (stats[requests / 2].time + stats[requests / 2 + 1].time \
1002             -stats[requests / 2].ctime - stats[requests / 2 + 1].ctime) / 2;
1003         else
1004             meand = stats[requests / 2].time - stats[requests / 2].ctime;
1005
1006         qsort(stats, requests, sizeof(struct data),
1007               (int (*) (const void *, const void *)) compwait);
1008         if ((requests > 1) && (requests % 2))
1009             meanwait = (stats[requests / 2].waittime + stats[requests / 2 + 1].waittime) / 2;
1010         else
1011             meanwait = stats[requests / 2].waittime;
1012
1013         qsort(stats, requests, sizeof(struct data),
1014               (int (*) (const void *, const void *)) comprando);
1015         if ((requests > 1) && (requests % 2))
1016             meantot = (stats[requests / 2].time + stats[requests / 2 + 1].time) / 2;
1017         else
1018             meantot = stats[requests / 2].time;
1019
1020         printf("\nConnection Times (ms)\n");
1021
1022         if (confidence) {
1023 #define CONF_FMT_STRING "%5" APR_TIME_T_FMT " %4d %5.1f %6" APR_TIME_T_FMT " %7" APR_TIME_T_FMT "\n"
1024             printf("              min  mean[+/-sd] median   max\n");
1025             printf("Connect:    " CONF_FMT_STRING, 
1026                    mincon, (int) (totalcon + 0.5), sdcon, meancon, maxcon);
1027             printf("Processing: " CONF_FMT_STRING,
1028                    mind, (int) (totald + 0.5), sdd, meand, maxd);
1029             printf("Waiting:    " CONF_FMT_STRING,
1030                    minwait, (int) (totalwait + 0.5), sdwait, meanwait, maxwait);
1031             printf("Total:      " CONF_FMT_STRING,
1032                    mintot, (int) (total + 0.5), sdtot, meantot, maxtot);
1033 #undef CONF_FMT_STRING
1034
1035 #define     SANE(what,avg,mean,sd) \
1036               { \
1037                 double d = (double)avg - mean; \
1038                 if (d < 0) d = -d; \
1039                 if (d > 2 * sd ) \
1040                     printf("ERROR: The median and mean for " what " are more than twice the standard\n" \
1041                            "       deviation apart. These results are NOT reliable.\n"); \
1042                 else if (d > sd ) \
1043                     printf("WARNING: The median and mean for " what " are not within a normal deviation\n" \
1044                            "        These results are probably not that reliable.\n"); \
1045             }
1046             SANE("the initial connection time", totalcon, meancon, sdcon);
1047             SANE("the processing time", totald, meand, sdd);
1048             SANE("the waiting time", totalwait, meanwait, sdwait);
1049             SANE("the total time", total, meantot, sdtot);
1050         }
1051         else {
1052             printf("              min   avg   max\n");
1053 #define CONF_FMT_STRING "%5" APR_TIME_T_FMT " %5" APR_TIME_T_FMT "%5" APR_TIME_T_FMT "\n"
1054             printf("Connect:    " CONF_FMT_STRING, 
1055                    mincon, totalcon / requests, maxcon);
1056             printf("Processing: " CONF_FMT_STRING, mintot - mincon, 
1057                    (total / requests) - (totalcon / requests), 
1058                    maxtot - maxcon);
1059             printf("Total:      " CONF_FMT_STRING, 
1060                    mintot, total / requests, maxtot);
1061 #undef CONF_FMT_STRING
1062         }
1063
1064
1065         /* Sorted on total connect times */
1066         if (percentile && (requests > 1)) {
1067             printf("\nPercentage of the requests served within a certain time (ms)\n");
1068             for (i = 0; i < sizeof(percs) / sizeof(int); i++)
1069                 if (percs[i] <= 0)
1070                     printf(" 0%%  <0> (never)\n");
1071                 else if (percs[i] >= 100)
1072                     printf(" 100%%  %5" APR_TIME_T_FMT " (longest request)\n",
1073                            stats[requests - 1].time);
1074                 else
1075                     printf("  %d%%  %5" APR_TIME_T_FMT "\n", percs[i], 
1076                            stats[(int) (requests * percs[i] / 100)].time);
1077         }
1078         if (csvperc) {
1079             FILE *out = fopen(csvperc, "w");
1080             int i;
1081             if (!out) {
1082                 perror("Cannot open CSV output file");
1083                 exit(1);
1084             }
1085             fprintf(out, "" "Percentage served" "," "Time in ms" "\n");
1086             for (i = 0; i < 100; i++) {
1087                 apr_time_t t;
1088                 if (i == 0)
1089                     t = stats[0].time;
1090                 else if (i == 100)
1091                     t = stats[requests - 1].time;
1092                 else
1093                     t = stats[(int) (0.5 + requests * i / 100.0)].time;
1094                 fprintf(out, "%d,%e\n", i, (double)t);
1095             }
1096             fclose(out);
1097         }
1098
1099     }
1100 }
1101
1102 /* --------------------------------------------------------- */
1103
1104 /* calculate and output results in HTML  */
1105
1106 static void output_html_results(void)
1107 {
1108     long timetaken;
1109
1110     endtime = apr_time_now();
1111     timetaken = (long)((endtime - start) / 1000);
1112
1113     printf("\n\n<table %s>\n", tablestring);
1114     printf("<tr %s><th colspan=2 %s>Server Software:</th>"
1115            "<td colspan=2 %s>%s</td></tr>\n",
1116            trstring, tdstring, tdstring, servername);
1117     printf("<tr %s><th colspan=2 %s>Server Hostname:</th>"
1118            "<td colspan=2 %s>%s</td></tr>\n",
1119            trstring, tdstring, tdstring, hostname);
1120     printf("<tr %s><th colspan=2 %s>Server Port:</th>"
1121            "<td colspan=2 %s>%hd</td></tr>\n",
1122            trstring, tdstring, tdstring, port);
1123     printf("<tr %s><th colspan=2 %s>Document Path:</th>"
1124            "<td colspan=2 %s>%s</td></tr>\n",
1125            trstring, tdstring, tdstring, path);
1126     printf("<tr %s><th colspan=2 %s>Document Length:</th>"
1127            "<td colspan=2 %s>%" APR_SIZE_T_FMT " bytes</td></tr>\n",
1128            trstring, tdstring, tdstring, doclen);
1129     printf("<tr %s><th colspan=2 %s>Concurrency Level:</th>"
1130            "<td colspan=2 %s>%d</td></tr>\n",
1131            trstring, tdstring, tdstring, concurrency);
1132     printf("<tr %s><th colspan=2 %s>Time taken for tests:</th>"
1133            "<td colspan=2 %s>%" APR_INT64_T_FMT ".%03ld seconds</td></tr>\n",
1134            trstring, tdstring, tdstring, apr_time_sec(timetaken),
1135            (long)apr_time_usec(timetaken));
1136     printf("<tr %s><th colspan=2 %s>Complete requests:</th>"
1137            "<td colspan=2 %s>%ld</td></tr>\n",
1138            trstring, tdstring, tdstring, done);
1139     printf("<tr %s><th colspan=2 %s>Failed requests:</th>"
1140            "<td colspan=2 %s>%ld</td></tr>\n",
1141            trstring, tdstring, tdstring, bad);
1142     if (bad)
1143         printf("<tr %s><td colspan=4 %s >   (Connect: %d, Length: %d, Exceptions: %d)</td></tr>\n",
1144                trstring, tdstring, err_conn, err_length, err_except);
1145     if (err_response)
1146         printf("<tr %s><th colspan=2 %s>Non-2xx responses:</th>"
1147                "<td colspan=2 %s>%d</td></tr>\n",
1148                trstring, tdstring, tdstring, err_response);
1149     if (keepalive)
1150         printf("<tr %s><th colspan=2 %s>Keep-Alive requests:</th>"
1151                "<td colspan=2 %s>%ld</td></tr>\n",
1152                trstring, tdstring, tdstring, doneka);
1153     printf("<tr %s><th colspan=2 %s>Total transferred:</th>"
1154            "<td colspan=2 %s>%ld bytes</td></tr>\n",
1155            trstring, tdstring, tdstring, totalread);
1156     if (posting > 0)
1157         printf("<tr %s><th colspan=2 %s>Total POSTed:</th>"
1158                "<td colspan=2 %s>%ld</td></tr>\n",
1159                trstring, tdstring, tdstring, totalposted);
1160     printf("<tr %s><th colspan=2 %s>HTML transferred:</th>"
1161            "<td colspan=2 %s>%ld bytes</td></tr>\n",
1162            trstring, tdstring, tdstring, totalbread);
1163
1164     /* avoid divide by zero */
1165     if (timetaken) {
1166         printf("<tr %s><th colspan=2 %s>Requests per second:</th>"
1167                "<td colspan=2 %s>%.2f</td></tr>\n",
1168            trstring, tdstring, tdstring, 1000 * (float) (done) / timetaken);
1169         printf("<tr %s><th colspan=2 %s>Transfer rate:</th>"
1170                "<td colspan=2 %s>%.2f kb/s received</td></tr>\n",
1171              trstring, tdstring, tdstring, (float) (totalread) / timetaken);
1172         if (posting > 0) {
1173             printf("<tr %s><td colspan=2 %s>&nbsp;</td>"
1174                    "<td colspan=2 %s>%.2f kb/s sent</td></tr>\n",
1175                    trstring, tdstring, tdstring,
1176                    (float) (totalposted) / timetaken);
1177             printf("<tr %s><td colspan=2 %s>&nbsp;</td>"
1178                    "<td colspan=2 %s>%.2f kb/s total</td></tr>\n",
1179                    trstring, tdstring, tdstring,
1180                    (float) (totalread + totalposted) / timetaken);
1181         }
1182     } {
1183         /* work out connection times */
1184         long i;
1185         apr_interval_time_t totalcon = 0, total = 0;
1186         apr_interval_time_t mincon = AB_MAX, mintot = AB_MAX;
1187         apr_interval_time_t maxcon = 0, maxtot = 0;
1188
1189         for (i = 0; i < requests; i++) {
1190             struct data s = stats[i];
1191             mincon = ap_min(mincon, s.ctime);
1192             mintot = ap_min(mintot, s.time);
1193             maxcon = ap_max(maxcon, s.ctime);
1194             maxtot = ap_max(maxtot, s.time);
1195             totalcon += s.ctime;
1196             total += s.time;
1197         }
1198
1199         if (requests > 0) {     /* avoid division by zero (if 0 requests) */
1200             printf("<tr %s><th %s colspan=4>Connnection Times (ms)</th></tr>\n",
1201                    trstring, tdstring);
1202             printf("<tr %s><th %s>&nbsp;</th> <th %s>min</th>   <th %s>avg</th>   <th %s>max</th></tr>\n",
1203                    trstring, tdstring, tdstring, tdstring, tdstring);
1204             printf("<tr %s><th %s>Connect:</th>"
1205                    "<td %s>%5" APR_TIME_T_FMT "</td>"
1206                    "<td %s>%5" APR_TIME_T_FMT "</td>"
1207                    "<td %s>%5" APR_TIME_T_FMT "</td></tr>\n",
1208                    trstring, tdstring, tdstring, mincon, tdstring, totalcon / requests, tdstring, maxcon);
1209             printf("<tr %s><th %s>Processing:</th>"
1210                    "<td %s>%5" APR_TIME_T_FMT "</td>"
1211                    "<td %s>%5" APR_TIME_T_FMT "</td>"
1212                    "<td %s>%5" APR_TIME_T_FMT "</td></tr>\n",
1213                    trstring, tdstring, tdstring, mintot - mincon, tdstring,
1214                    (total / requests) - (totalcon / requests), tdstring, maxtot - maxcon);
1215             printf("<tr %s><th %s>Total:</th>"
1216                    "<td %s>%5" APR_TIME_T_FMT "</td>"
1217                    "<td %s>%5" APR_TIME_T_FMT "</td>"
1218                    "<td %s>%5" APR_TIME_T_FMT "</td></tr>\n",
1219                    trstring, tdstring, tdstring, mintot, tdstring, total / requests, tdstring, maxtot);
1220         }
1221         printf("</table>\n");
1222     }
1223 }
1224
1225 /* --------------------------------------------------------- */
1226
1227 /* start asnchronous non-blocking connection */
1228
1229 static void start_connect(struct connection * c)
1230 {
1231     apr_status_t rv;
1232
1233 #ifdef USE_SSL
1234     if (ssl == 1) {
1235         ssl_start_connect(c);
1236         return;
1237     }
1238 #endif
1239     
1240     if (!(started < requests))
1241         return;
1242
1243     c->read = 0;
1244     c->bread = 0;
1245     c->keepalive = 0;
1246     c->cbx = 0;
1247     c->gotheader = 0;
1248     c->rwrite = 0;
1249     if (c->ctx)
1250         apr_pool_destroy(c->ctx);
1251     apr_pool_create(&c->ctx, cntxt);
1252
1253     if ((rv = apr_socket_create(&c->aprsock, destsa->family,
1254                                 SOCK_STREAM, c->ctx)) != APR_SUCCESS) {
1255         apr_err("socket", rv);
1256     }
1257     if ((rv = apr_socket_opt_set(c->aprsock, APR_SO_NONBLOCK, 1))
1258          != APR_SUCCESS) {
1259         apr_err("socket nonblock", rv);
1260     }
1261     c->start = apr_time_now();
1262     if ((rv = apr_connect(c->aprsock, destsa)) != APR_SUCCESS) {
1263         if (APR_STATUS_IS_EINPROGRESS(rv)) {
1264             apr_pollfd_t new_pollfd;
1265             c->state = STATE_CONNECTING;
1266             c->rwrite = 0;
1267             new_pollfd.desc_type = APR_POLL_SOCKET;
1268             new_pollfd.reqevents = APR_POLLIN;
1269             new_pollfd.desc.s = c->aprsock;
1270             new_pollfd.client_data = c;
1271             apr_pollset_add(readbits, &new_pollfd);
1272             return;
1273         }
1274         else {
1275             apr_pollfd_t remove_pollfd;
1276             remove_pollfd.desc_type = APR_POLL_SOCKET;
1277             remove_pollfd.desc.s = c->aprsock;
1278             apr_pollset_remove(readbits, &remove_pollfd);
1279             apr_socket_close(c->aprsock);
1280             err_conn++;
1281             if (bad++ > 10) {
1282                 fprintf(stderr,
1283                         "\nTest aborted after 10 failures\n\n");
1284                 apr_err("apr_connect()", rv);
1285             }
1286             c->state = STATE_UNCONNECTED;
1287             start_connect(c);
1288             return;
1289         }
1290     }
1291
1292     /* connected first time */
1293     started++;
1294     write_request(c);
1295 }
1296
1297 /* --------------------------------------------------------- */
1298
1299 /* close down connection and save stats */
1300
1301 static void close_connection(struct connection * c)
1302 {
1303     if (c->read == 0 && c->keepalive) {
1304         /*
1305          * server has legitimately shut down an idle keep alive request
1306          */
1307         if (good)
1308             good--;             /* connection never happened */
1309     }
1310     else {
1311         if (good == 1) {
1312             /* first time here */
1313             doclen = c->bread;
1314         }
1315         else if (c->bread != doclen) {
1316             bad++;
1317             err_length++;
1318         }
1319         /* save out time */
1320         if (done < requests) {
1321             struct data s;
1322             if ((done) && heartbeatres && !(done % heartbeatres)) {
1323                 fprintf(stderr, "Completed %ld requests\n", done);
1324                 fflush(stderr);
1325             }
1326             c->done = apr_time_now();
1327             s.read = c->read;
1328             s.starttime = c->start;
1329             s.ctime = (c->connect - c->start) / 1000;
1330             s.time = (c->done - c->start) / 1000;
1331             s.waittime = (c->beginread - c->endwrite) / 1000;
1332             stats[done++] = s;
1333         }
1334     }
1335
1336 #ifdef USE_SSL
1337     if (ssl == 1) {
1338         SSL_shutdown(c->ssl);
1339         SSL_free(c->ssl);
1340     }
1341     else
1342 #endif
1343     {
1344         apr_pollfd_t remove_pollfd;
1345         remove_pollfd.desc_type = APR_POLL_SOCKET;
1346         remove_pollfd.desc.s = c->aprsock;
1347         apr_pollset_remove(readbits, &remove_pollfd);
1348         apr_socket_close(c->aprsock);
1349     }
1350     c->state = STATE_UNCONNECTED;
1351
1352     /* connect again */
1353     start_connect(c);
1354     return;
1355 }
1356
1357 /* --------------------------------------------------------- */
1358
1359 /* read data from connection */
1360
1361 static void read_connection(struct connection * c)
1362 {
1363     apr_size_t r;
1364     apr_status_t status;
1365     char *part;
1366     char respcode[4];           /* 3 digits and null */
1367
1368     r = sizeof(buffer);
1369 #ifdef USE_SSL
1370     if (ssl == 1)
1371     {
1372         status = SSL_read (c->ssl, buffer, r);
1373         if (status <= 0) {
1374             good++; c->read = 0;
1375             if (status < 0) printf("SSL read failed - closing connection\n");
1376             close_connection(c);
1377             return;
1378         }
1379     r = status;
1380     }
1381     else {
1382 #endif
1383     status = apr_recv(c->aprsock, buffer, &r);
1384     if (APR_STATUS_IS_EAGAIN(status))
1385         return;
1386     else if (r == 0 && APR_STATUS_IS_EOF(status)) {
1387         good++;
1388         close_connection(c);
1389         return;
1390     }
1391     /* catch legitimate fatal apr_recv errors */
1392     else if (status != APR_SUCCESS) {
1393         err_except++; /* XXX: is this the right error counter? */
1394         /* XXX: Should errors here be fatal, or should we allow a
1395          * certain number of them before completely failing? -aaron */
1396         apr_err("apr_recv", status);
1397     }
1398 #ifdef USE_SSL
1399     }
1400 #endif
1401
1402     totalread += r;
1403     if (c->read == 0) {
1404         c->beginread = apr_time_now();
1405     }
1406     c->read += r;
1407
1408
1409     if (!c->gotheader) {
1410         char *s;
1411         int l = 4;
1412         apr_size_t space = CBUFFSIZE - c->cbx - 1; /* -1 allows for \0 term */
1413         int tocopy = (space < r) ? space : r;
1414 #ifdef NOT_ASCII
1415         apr_size_t inbytes_left = space, outbytes_left = space;
1416
1417         status = apr_xlate_conv_buffer(from_ascii, buffer, &inbytes_left,
1418                                        c->cbuff + c->cbx, &outbytes_left);
1419         if (status || inbytes_left || outbytes_left) {
1420             fprintf(stderr, "only simple translation is supported (%d/%u/%u)\n",
1421                     status, inbytes_left, outbytes_left);
1422             exit(1);
1423         }
1424 #else
1425         memcpy(c->cbuff + c->cbx, buffer, space);
1426 #endif                          /* NOT_ASCII */
1427         c->cbx += tocopy;
1428         space -= tocopy;
1429         c->cbuff[c->cbx] = 0;   /* terminate for benefit of strstr */
1430         if (verbosity >= 2) {
1431             printf("LOG: header received:\n%s\n", c->cbuff);
1432         }
1433         s = strstr(c->cbuff, "\r\n\r\n");
1434         /*
1435          * this next line is so that we talk to NCSA 1.5 which blatantly
1436          * breaks the http specifaction
1437          */
1438         if (!s) {
1439             s = strstr(c->cbuff, "\n\n");
1440             l = 2;
1441         }
1442
1443         if (!s) {
1444             /* read rest next time */
1445             if (space) {
1446                 return;
1447             }
1448             else {
1449                 /* header is in invalid or too big - close connection */
1450                 apr_pollfd_t remove_pollfd;
1451                 remove_pollfd.desc_type = APR_POLL_SOCKET;
1452                 remove_pollfd.desc.s = c->aprsock;
1453                 apr_pollset_remove(readbits, &remove_pollfd);
1454                 apr_socket_close(c->aprsock);
1455                 err_response++;
1456                 if (bad++ > 10) {
1457                     err("\nTest aborted after 10 failures\n\n");
1458                 }
1459                 start_connect(c);
1460             }
1461         }
1462         else {
1463             /* have full header */
1464             if (!good) {
1465                 /*
1466                  * this is first time, extract some interesting info
1467                  */
1468                 char *p, *q;
1469                 p = strstr(c->cbuff, "Server:");
1470                 q = servername;
1471                 if (p) {
1472                     p += 8;
1473                     while (*p > 32)
1474                         *q++ = *p++;
1475                 }
1476                 *q = 0;
1477             }
1478             /*
1479              * XXX: this parsing isn't even remotely HTTP compliant... but in
1480              * the interest of speed it doesn't totally have to be, it just
1481              * needs to be extended to handle whatever servers folks want to
1482              * test against. -djg
1483              */
1484
1485             /* check response code */
1486             part = strstr(c->cbuff, "HTTP");    /* really HTTP/1.x_ */
1487             if (part && strlen(part) > strlen("HTTP/1.x_")) {
1488                 strncpy(respcode, (part + strlen("HTTP/1.x_")), 3);
1489                 respcode[3] = '\0';
1490             }
1491             else {
1492                 strcpy(respcode, "500");
1493             }
1494
1495             if (respcode[0] != '2') {
1496                 err_response++;
1497                 if (verbosity >= 2)
1498                     printf("WARNING: Response code not 2xx (%s)\n", respcode);
1499             }
1500             else if (verbosity >= 3) {
1501                 printf("LOG: Response code = %s\n", respcode);
1502             }
1503             c->gotheader = 1;
1504             *s = 0;             /* terminate at end of header */
1505             if (keepalive &&
1506                 (strstr(c->cbuff, "Keep-Alive")
1507                  || strstr(c->cbuff, "keep-alive"))) {  /* for benefit of MSIIS */
1508                 char *cl;
1509                 cl = strstr(c->cbuff, "Content-Length:");
1510                 /* handle NCSA, which sends Content-length: */
1511                 if (!cl)
1512                     cl = strstr(c->cbuff, "Content-length:");
1513                 if (cl) {
1514                     c->keepalive = 1;
1515                     c->length = atoi(cl + 16);
1516                 }
1517             }
1518             c->bread += c->cbx - (s + l - c->cbuff) + r - tocopy;
1519             totalbread += c->bread;
1520         }
1521     }
1522     else {
1523         /* outside header, everything we have read is entity body */
1524         c->bread += r;
1525         totalbread += r;
1526     }
1527
1528     if (c->keepalive && (c->bread >= c->length)) {
1529         /* finished a keep-alive connection */
1530         good++;
1531         doneka++;
1532         /* save out time */
1533         if (good == 1) {
1534             /* first time here */
1535             doclen = c->bread;
1536         }
1537         else if (c->bread != doclen) {
1538             bad++;
1539             err_length++;
1540         }
1541         if (done < requests) {
1542             struct data s;
1543             if (done && heartbeatres && !(done % heartbeatres)) {
1544                 fprintf(stderr, "Completed %ld requests\n", done);
1545                 fflush(stderr);
1546             }
1547             c->done = apr_time_now();
1548             s.read = c->read;
1549             s.starttime = c->start;
1550             s.ctime = (c->connect - c->start) / 1000;
1551             s.waittime = (c->beginread - c->endwrite) / 1000;
1552             s.time = (c->done - c->start) / 1000;
1553             stats[done++] = s;
1554         }
1555         c->keepalive = 0;
1556         c->length = 0;
1557         c->gotheader = 0;
1558         c->cbx = 0;
1559         c->read = c->bread = 0;
1560         write_request(c);
1561         c->start = c->connect;  /* zero connect time with keep-alive */
1562     }
1563 }
1564
1565 /* --------------------------------------------------------- */
1566
1567 /* run the tests */
1568
1569 static void test(void)
1570 {
1571     apr_time_t now;
1572     apr_int16_t rv;
1573     long i;
1574     apr_status_t status;
1575 #ifdef NOT_ASCII
1576     apr_size_t inbytes_left, outbytes_left;
1577 #endif
1578
1579     if (isproxy) {
1580         connecthost = apr_pstrdup(cntxt, proxyhost);
1581         connectport = proxyport;
1582     }
1583     else {
1584         connecthost = apr_pstrdup(cntxt, hostname);
1585         connectport = port;
1586     }
1587
1588     if (!use_html) {
1589         printf("Benchmarking %s ", hostname);
1590         if (isproxy)
1591             printf("[through %s:%d] ", proxyhost, proxyport);
1592         printf("(be patient)%s",
1593                (heartbeatres ? "\n" : "..."));
1594         fflush(stdout);
1595     }
1596
1597     now = apr_time_now();
1598
1599     con = calloc(concurrency * sizeof(struct connection), 1);
1600     
1601     stats = calloc(requests * sizeof(struct data), 1);
1602     apr_pollset_create(&readbits, concurrency, cntxt, 0);
1603
1604     /* setup request */
1605     if (posting <= 0) {
1606         sprintf(request, "%s %s HTTP/1.0\r\n"
1607                 "User-Agent: ApacheBench/%s\r\n"
1608                 "%s" "%s" "%s"
1609                 "Host: %s%s\r\n"
1610                 "Accept: */*\r\n"
1611                 "%s" "\r\n",
1612                 (posting == 0) ? "GET" : "HEAD",
1613                 (isproxy) ? fullurl : path,
1614                 AP_AB_BASEREVISION,
1615                 keepalive ? "Connection: Keep-Alive\r\n" : "",
1616                 cookie, auth, host_field, colonhost, hdrs);
1617     }
1618     else {
1619         sprintf(request, "POST %s HTTP/1.0\r\n"
1620                 "User-Agent: ApacheBench/%s\r\n"
1621                 "%s" "%s" "%s"
1622                 "Host: %s%s\r\n"
1623                 "Accept: */*\r\n"
1624                 "Content-length: %" APR_SIZE_T_FMT "\r\n"
1625                 "Content-type: %s\r\n"
1626                 "%s"
1627                 "\r\n",
1628                 (isproxy) ? fullurl : path,
1629                 AP_AB_BASEREVISION,
1630                 keepalive ? "Connection: Keep-Alive\r\n" : "",
1631                 cookie, auth,
1632                 host_field, colonhost, postlen,
1633                 (content_type[0]) ? content_type : "text/plain", hdrs);
1634     }
1635
1636     if (verbosity >= 2)
1637         printf("INFO: POST header == \n---\n%s\n---\n", request);
1638
1639     reqlen = strlen(request);
1640
1641     /*
1642      * Combine headers and (optional) post file into one contineous buffer
1643      */
1644     if (posting == 1) {
1645         char *buff = malloc(postlen + reqlen + 1);
1646         if (!buff) {
1647             fprintf(stderr, "error creating request buffer: out of memory\n");
1648             return;
1649         }
1650         strcpy(buff, request);
1651         strcpy(buff + reqlen, postdata);
1652         request = buff;
1653     }
1654
1655 #ifdef NOT_ASCII
1656     inbytes_left = outbytes_left = reqlen;
1657     status = apr_xlate_conv_buffer(to_ascii, request, &inbytes_left,
1658                                    request, &outbytes_left);
1659     if (status || inbytes_left || outbytes_left) {
1660         fprintf(stderr, "only simple translation is supported (%d/%u/%u)\n",
1661                 status, inbytes_left, outbytes_left);
1662         exit(1);
1663     }
1664 #endif                          /* NOT_ASCII */
1665
1666     /* This only needs to be done once */
1667 #ifdef USE_SSL
1668     if (ssl != 1)
1669 #endif
1670     if ((rv = apr_sockaddr_info_get(&destsa, connecthost, APR_UNSPEC, connectport, 0, cntxt))
1671         != APR_SUCCESS) {
1672         char buf[120];
1673         apr_snprintf(buf, sizeof(buf),
1674                      "apr_sockaddr_info_get() for %s", connecthost);
1675         apr_err(buf, rv);
1676     }
1677
1678     /* ok - lets start */
1679     start = apr_time_now();
1680
1681     /* initialise lots of requests */
1682     for (i = 0; i < concurrency; i++) {
1683         con[i].socknum = i;
1684         start_connect(&con[i]);
1685     }
1686
1687     while (done < requests) {
1688         apr_int32_t n;
1689         apr_int32_t timed;
1690         const apr_pollfd_t *pollresults;
1691
1692         /* check for time limit expiry */
1693         now = apr_time_now();
1694         timed = (apr_int32_t)apr_time_sec(now - start);
1695         if (tlimit && timed >= tlimit) {
1696             requests = done;    /* so stats are correct */
1697             break;              /* no need to do another round */
1698         }
1699
1700         n = concurrency;
1701 #ifdef USE_SSL
1702         if (ssl == 1)
1703             status = APR_SUCCESS;
1704         else
1705 #endif
1706         status = apr_pollset_poll(readbits, aprtimeout, &n, &pollresults);
1707         if (status != APR_SUCCESS)
1708             apr_err("apr_poll", status);
1709
1710         if (!n) {
1711             err("\nServer timed out\n\n");
1712         }
1713
1714         for (i = 0; i < n; i++) {
1715             const apr_pollfd_t *next_fd = &(pollresults[i]);
1716             struct connection *c = next_fd->client_data;
1717
1718             /*
1719              * If the connection isn't connected how can we check it?
1720              */
1721             if (c->state == STATE_UNCONNECTED)
1722                 continue;
1723
1724 #ifdef USE_SSL
1725             if (ssl == 1)
1726                 rv = APR_POLLIN;
1727             else
1728 #endif
1729             rv = next_fd->rtnevents;
1730
1731             /*
1732              * Notes: APR_POLLHUP is set after FIN is received on some
1733              * systems, so treat that like APR_POLLIN so that we try to read
1734              * again.
1735              *
1736              * Some systems return APR_POLLERR with APR_POLLHUP.  We need to
1737              * call read_connection() for APR_POLLHUP, so check for
1738              * APR_POLLHUP first so that a closed connection isn't treated
1739              * like an I/O error.  If it is, we never figure out that the
1740              * connection is done and we loop here endlessly calling
1741              * apr_poll().
1742              */
1743             if ((rv & APR_POLLIN) || (rv & APR_POLLPRI) || (rv & APR_POLLHUP))
1744                 read_connection(c);
1745             if ((rv & APR_POLLERR) || (rv & APR_POLLNVAL)) {
1746                 bad++;
1747                 err_except++;
1748                 start_connect(c);
1749                 continue;
1750             }
1751             if (rv & APR_POLLOUT)
1752                 write_request(c);
1753
1754             /*
1755              * When using a select based poll every time we check the bits
1756              * are reset. In 1.3's ab we copied the FD_SET's each time
1757              * through, but here we're going to check the state and if the
1758              * connection is in STATE_READ or STATE_CONNECTING we'll add the
1759              * socket back in as APR_POLLIN.
1760              */
1761 #ifdef USE_SSL
1762             if (ssl != 1)
1763 #endif
1764             if (c->state == STATE_READ ||
1765                 c->state == STATE_CONNECTING) {
1766                     apr_pollfd_t new_pollfd;
1767                     new_pollfd.desc_type = APR_POLL_SOCKET;
1768                     new_pollfd.reqevents = APR_POLLIN;
1769                     new_pollfd.desc.s = c->aprsock;
1770                     new_pollfd.client_data = c;
1771                     apr_pollset_add(readbits, &new_pollfd);
1772                 }
1773         }
1774     }
1775
1776     if (heartbeatres)
1777         fprintf(stderr, "Finished %ld requests\n", done);
1778     else
1779         printf("..done\n");
1780
1781     if (use_html)
1782         output_html_results();
1783     else
1784         output_results();
1785 }
1786
1787 /* ------------------------------------------------------- */
1788
1789 /* display copyright information */
1790 static void copyright(void)
1791 {
1792     if (!use_html) {
1793         printf("This is ApacheBench, Version %s\n", AP_AB_BASEREVISION " <$Revision: 1.125 $> apache-2.0");
1794         printf("Copyright (c) 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\n");
1795         printf("Copyright (c) 1998-2002 The Apache Software Foundation, http://www.apache.org/\n");
1796         printf("\n");
1797     }
1798     else {
1799         printf("<p>\n");
1800         printf(" This is ApacheBench, Version %s <i>&lt;%s&gt;</i> apache-2.0<br>\n", AP_AB_BASEREVISION, "$Revision: 1.125 $");
1801         printf(" Copyright (c) 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/<br>\n");
1802         printf(" Copyright (c) 1998-2002 The Apache Software Foundation, http://www.apache.org/<br>\n");
1803         printf("</p>\n<p>\n");
1804     }
1805 }
1806
1807 /* display usage information */
1808 static void usage(const char *progname)
1809 {
1810     fprintf(stderr, "Usage: %s [options] [http"
1811 #ifdef USE_SSL
1812             "[s]"
1813 #endif
1814             "://]hostname[:port]/path\n", progname);
1815     fprintf(stderr, "Options are:\n");
1816     fprintf(stderr, "    -n requests     Number of requests to perform\n");
1817     fprintf(stderr, "    -c concurrency  Number of multiple requests to make\n");
1818     fprintf(stderr, "    -t timelimit    Seconds to max. wait for responses\n");
1819     fprintf(stderr, "    -p postfile     File containing data to POST\n");
1820     fprintf(stderr, "    -T content-type Content-type header for POSTing\n");
1821     fprintf(stderr, "    -v verbosity    How much troubleshooting info to print\n");
1822     fprintf(stderr, "    -w              Print out results in HTML tables\n");
1823     fprintf(stderr, "    -i              Use HEAD instead of GET\n");
1824     fprintf(stderr, "    -x attributes   String to insert as table attributes\n");
1825     fprintf(stderr, "    -y attributes   String to insert as tr attributes\n");
1826     fprintf(stderr, "    -z attributes   String to insert as td or th attributes\n");
1827     fprintf(stderr, "    -C attribute    Add cookie, eg. 'Apache=1234. (repeatable)\n");
1828     fprintf(stderr, "    -H attribute    Add Arbitrary header line, eg. 'Accept-Encoding: gzip'\n");
1829     fprintf(stderr, "                    Inserted after all normal header lines. (repeatable)\n");
1830     fprintf(stderr, "    -A attribute    Add Basic WWW Authentication, the attributes\n");
1831     fprintf(stderr, "                    are a colon separated username and password.\n");
1832     fprintf(stderr, "    -P attribute    Add Basic Proxy Authentication, the attributes\n");
1833     fprintf(stderr, "                    are a colon separated username and password.\n");
1834     fprintf(stderr, "    -X proxy:port   Proxyserver and port number to use\n");
1835     fprintf(stderr, "    -V              Print version number and exit\n");
1836     fprintf(stderr, "    -k              Use HTTP KeepAlive feature\n");
1837     fprintf(stderr, "    -d              Do not show percentiles served table.\n");
1838     fprintf(stderr, "    -S              Do not show confidence estimators and warnings.\n");
1839     fprintf(stderr, "    -g filename     Output collected data to gnuplot format file.\n");
1840     fprintf(stderr, "    -e filename     Output CSV file with percentages served\n");
1841 #ifdef USE_SSL
1842     fprintf(stderr, "    -s              Use httpS instead of HTTP (SSL)\n");
1843 #endif
1844     fprintf(stderr, "    -h              Display usage information (this message)\n");
1845     exit(EINVAL);
1846 }
1847
1848 /* ------------------------------------------------------- */
1849
1850 /* split URL into parts */
1851
1852 static int parse_url(char *url)
1853 {
1854     char *cp;
1855     char *h;
1856     char *scope_id;
1857     apr_status_t rv;
1858
1859     /* Save a copy for the proxy */
1860     fullurl = apr_pstrdup(cntxt, url);
1861
1862     if (strlen(url) > 7 && strncmp(url, "http://", 7) == 0) {
1863         url += 7;
1864 #ifdef USE_SSL
1865         ssl = 0;
1866 #endif
1867     }
1868     else
1869 #ifdef USE_SSL
1870     if (strlen(url) > 8 && strncmp(url, "https://", 8) == 0) {
1871         url += 8;
1872         ssl = 1;
1873     }
1874 #else
1875     if (strlen(url) > 8 && strncmp(url, "https://", 8) == 0) {
1876         fprintf(stderr, "SSL not compiled in; no https support\n");
1877         exit(1);
1878     }
1879 #endif
1880
1881     if ((cp = strchr(url, '/')) == NULL)
1882         return 1;
1883     h = apr_palloc(cntxt, cp - url + 1);
1884     memcpy(h, url, cp - url);
1885     h[cp - url] = '\0';
1886     rv = apr_parse_addr_port(&hostname, &scope_id, &port, h, cntxt);
1887     if (rv != APR_SUCCESS || !hostname || scope_id) {
1888         return 1;
1889     }
1890     path = apr_pstrdup(cntxt, cp);
1891     *cp = '\0';
1892     if (*url == '[') {          /* IPv6 numeric address string */
1893         host_field = apr_psprintf(cntxt, "[%s]", hostname);
1894     }
1895     else {
1896         host_field = hostname;
1897     }
1898
1899     if (port == 0) {            /* no port specified */
1900 #ifdef USE_SSL
1901         if (ssl == 1)
1902             port = 443;
1903         else
1904 #endif
1905             port = 80;
1906     }
1907
1908     if ((
1909 #ifdef USE_SSL
1910          (ssl == 1) && (port != 443)) || (( ssl == 0 ) && 
1911 #endif
1912          (port != 80)))
1913     {
1914         colonhost = apr_psprintf(cntxt,":%d",port);
1915     } else
1916         colonhost = "";
1917     return 0;
1918 }
1919
1920 /* ------------------------------------------------------- */
1921
1922 /* read data to POST from file, save contents and length */
1923
1924 static int open_postfile(const char *pfile)
1925 {
1926     apr_file_t *postfd = NULL;
1927     apr_finfo_t finfo;
1928     apr_fileperms_t mode = APR_OS_DEFAULT;
1929     apr_size_t length;
1930     apr_status_t rv;
1931     char errmsg[120];
1932
1933     rv = apr_file_open(&postfd, pfile, APR_READ, mode, cntxt);
1934     if (rv != APR_SUCCESS) {
1935         printf("Invalid postfile name (%s): %s\n", pfile,
1936                apr_strerror(rv, errmsg, sizeof errmsg));
1937         return rv;
1938     }
1939
1940     apr_file_info_get(&finfo, APR_FINFO_NORM, postfd);
1941     postlen = (apr_size_t)finfo.size;
1942     postdata = (char *) malloc(postlen);
1943     if (!postdata) {
1944         printf("Can\'t alloc postfile buffer\n");
1945         return APR_ENOMEM;
1946     }
1947     length = postlen;
1948     rv = apr_file_read(postfd, postdata, &length);
1949     if (rv != APR_SUCCESS) {
1950         printf("error reading postfile: %s\n",
1951                apr_strerror(rv, errmsg, sizeof errmsg));
1952         return rv;
1953     }
1954     if (length != postlen) {
1955         printf("error reading postfile: read only %"
1956                APR_SIZE_T_FMT " bytes",
1957                length);
1958         return APR_EINVAL;
1959     }
1960     apr_file_close(postfd);
1961     return 0;
1962 }
1963
1964 /* ------------------------------------------------------- */
1965
1966 /* sort out command-line args and call test */
1967 int main(int argc, const char * const argv[])
1968 {
1969     int r, l;
1970     char tmp[1024];
1971     apr_status_t status;
1972     apr_getopt_t *opt;
1973     const char *optarg;
1974     char c;
1975
1976     /* table defaults  */
1977     tablestring = "";
1978     trstring = "";
1979     tdstring = "bgcolor=white";
1980     cookie = "";
1981     auth = "";
1982     proxyhost[0] = '\0';
1983     hdrs = "";
1984
1985     apr_app_initialize(&argc, &argv, NULL);
1986     atexit(apr_terminate);
1987     apr_pool_create(&cntxt, NULL);
1988
1989 #ifdef NOT_ASCII
1990     status = apr_xlate_open(&to_ascii, "ISO8859-1", APR_DEFAULT_CHARSET, cntxt);
1991     if (status) {
1992         fprintf(stderr, "apr_xlate_open(to ASCII)->%d\n", status);
1993         exit(1);
1994     }
1995     status = apr_xlate_open(&from_ascii, APR_DEFAULT_CHARSET, "ISO8859-1", cntxt);
1996     if (status) {
1997         fprintf(stderr, "apr_xlate_open(from ASCII)->%d\n", status);
1998         exit(1);
1999     }
2000     status = apr_base64init_ebcdic(to_ascii, from_ascii);
2001     if (status) {
2002         fprintf(stderr, "apr_base64init_ebcdic()->%d\n", status);
2003         exit(1);
2004     }
2005 #endif
2006
2007     apr_getopt_init(&opt, cntxt, argc, argv);
2008     while ((status = apr_getopt(opt, "n:c:t:T:p:v:kVhwix:y:z:C:H:P:A:g:X:de:Sq"
2009 #ifdef USE_SSL
2010                                 "s"
2011 #endif
2012                                 ,&c, &optarg)) == APR_SUCCESS) {
2013         switch (c) {
2014         case 's':
2015 #ifdef USE_SSL
2016         ssl = 1;
2017         break;
2018 #else
2019         fprintf(stderr, "SSL not compiled in; no https support\n");
2020         exit(1);
2021 #endif
2022         case 'n':
2023             requests = atoi(optarg);
2024             if (!requests) {
2025                 err("Invalid number of requests\n");
2026             }
2027             break;
2028         case 'k':
2029             keepalive = 1;
2030             break;
2031         case 'q':
2032             heartbeatres = 0;
2033             break;
2034         case 'c':
2035             concurrency = atoi(optarg);
2036             break;
2037         case 'i':
2038             if (posting == 1)
2039                 err("Cannot mix POST and HEAD\n");
2040             posting = -1;
2041             break;
2042         case 'g':
2043             gnuplot = strdup(optarg);
2044             break;
2045         case 'd':
2046             percentile = 0;
2047             break;
2048         case 'e':
2049             csvperc = strdup(optarg);
2050             break;
2051         case 'S':
2052             confidence = 0;
2053             break;
2054         case 'p':
2055             if (posting != 0)
2056                 err("Cannot mix POST and HEAD\n");
2057
2058             if (0 == (r = open_postfile(optarg))) {
2059                 posting = 1;
2060             }
2061             else if (postdata) {
2062                 exit(r);
2063             }
2064             break;
2065         case 'v':
2066             verbosity = atoi(optarg);
2067             break;
2068         case 't':
2069             tlimit = atoi(optarg);
2070             requests = MAX_REQUESTS;    /* need to size data array on
2071                                          * something */
2072             break;
2073         case 'T':
2074             strcpy(content_type, optarg);
2075             break;
2076         case 'C':
2077             cookie = apr_pstrcat(cntxt, "Cookie: ", optarg, "\r\n", NULL);
2078             break;
2079         case 'A':
2080             /*
2081              * assume username passwd already to be in colon separated form.
2082              * Ready to be uu-encoded.
2083              */
2084             while (apr_isspace(*optarg))
2085                 optarg++;
2086             l = apr_base64_encode(tmp, optarg, strlen(optarg));
2087             tmp[l] = '\0';
2088
2089             auth = apr_pstrcat(cntxt, auth, "Authorization: Basic ", tmp,
2090                                "\r\n", NULL);
2091             break;
2092         case 'P':
2093             /*
2094              * assume username passwd already to be in colon separated form.
2095              */
2096             while (apr_isspace(*optarg))
2097                 optarg++;
2098             l = apr_base64_encode(tmp, optarg, strlen(optarg));
2099             tmp[l] = '\0';
2100
2101             auth = apr_pstrcat(cntxt, auth, "Proxy-Authorization: Basic ",
2102                                tmp, "\r\n", NULL);
2103             break;
2104         case 'H':
2105             hdrs = apr_pstrcat(cntxt, hdrs, optarg, "\r\n", NULL);
2106             break;
2107         case 'w':
2108             use_html = 1;
2109             break;
2110             /*
2111              * if any of the following three are used, turn on html output
2112              * automatically
2113              */
2114         case 'x':
2115             use_html = 1;
2116             tablestring = optarg;
2117             break;
2118         case 'X':
2119             {
2120                 char *p;
2121                 /*
2122                  * assume proxy-name[:port]
2123                  */
2124                 if ((p = strchr(optarg, ':'))) {
2125                     *p = '\0';
2126                     p++;
2127                     proxyport = atoi(p);
2128                 }
2129                 strcpy(proxyhost, optarg);
2130                 isproxy = 1;
2131             }
2132             break;
2133         case 'y':
2134             use_html = 1;
2135             trstring = optarg;
2136             break;
2137         case 'z':
2138             use_html = 1;
2139             tdstring = optarg;
2140             break;
2141         case 'h':
2142             usage(argv[0]);
2143             break;
2144         case 'V':
2145             copyright();
2146             return 0;
2147         }
2148     }
2149
2150     if (opt->ind != argc - 1) {
2151         fprintf(stderr, "%s: wrong number of arguments\n", argv[0]);
2152         usage(argv[0]);
2153     }
2154
2155     if (parse_url(apr_pstrdup(cntxt, opt->argv[opt->ind++]))) {
2156         fprintf(stderr, "%s: invalid URL\n", argv[0]);
2157         usage(argv[0]);
2158     }
2159
2160
2161     if ((heartbeatres) && (requests > 150)) {
2162         heartbeatres = requests / 10;   /* Print line every 10% of requests */
2163         if (heartbeatres < 100)
2164             heartbeatres = 100; /* but never more often than once every 100
2165                                  * connections. */
2166     }
2167     else
2168         heartbeatres = 0;
2169
2170 #ifdef USE_SSL
2171 #ifdef RSAREF
2172     R_malloc_init();
2173 #else
2174     CRYPTO_malloc_init();
2175 #endif
2176     SSL_load_error_strings();
2177     SSL_library_init();
2178     bio_out=BIO_new_fp(stdout,BIO_NOCLOSE);
2179     bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
2180
2181     /* TODO: Allow force SSLv2_client_method() (TLSv1?) */
2182     if (!(ctx = SSL_CTX_new(SSLv23_client_method()))) {
2183         fprintf(stderr, "Could not init SSL CTX");
2184         ERR_print_errors_fp(stderr);
2185         exit(1);
2186     }
2187     SSL_CTX_set_options(ctx, SSL_OP_ALL);
2188 #ifdef USE_THREADS
2189     ssl_util_thread_setup(cntxt);
2190 #endif
2191 #endif
2192 #ifdef SIGPIPE
2193     apr_signal(SIGPIPE, SIG_IGN);       /* Ignore writes to connections that
2194                                          * have been closed at the other end. */
2195 #endif
2196     copyright();
2197     test();
2198     apr_pool_destroy(cntxt);
2199
2200     return 0;
2201 }