-
Notifications
You must be signed in to change notification settings - Fork 0
/
ab.c
3241 lines (2922 loc) · 108 KB
/
ab.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// from https://github.com/apache/httpd/blob/trunk/support/ab.c
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
** This program is based on ZeusBench V1.0 written by Adam Twiss
** which is Copyright (c) 1996 by Zeus Technology Ltd.
** http://web.archive.org/web/20000304112933/http://www.zeustech.net/
**
** This software is provided "as is" and any express or implied warranties,
** including but not limited to, the implied warranties of merchantability and
** fitness for a particular purpose are disclaimed. In no event shall
** Zeus Technology Ltd. be liable for any direct, indirect, incidental, special,
** exemplary, or consequential damaged (including, but not limited to,
** procurement of substitute good or services; loss of use, data, or profits;
** or business interruption) however caused and on theory of liability. Whether
** in contract, strict liability or tort (including negligence or otherwise)
** arising in any way out of the use of this software, even if advised of the
** possibility of such damage.
**
*/
/*
** HISTORY:
** - Originally written by Adam Twiss <[email protected]>, March 1996
** with input from Mike Belshe <[email protected]> and
** Michael Campanella <[email protected]>
** - Enhanced by Dean Gaudet <[email protected]>, November 1997
** - Cleaned up by Ralf S. Engelschall <[email protected]>, March 1998
** - POST and verbosity by Kurt Sussman <[email protected]>, August 1998
** - HTML table output added by David N. Welton <[email protected]>, January 1999
** - Added Cookie, Arbitrary header and auth support. <[email protected]>, April 1999
** Version 1.3d
** - Increased version number - as some of the socket/error handling has
** fundamentally changed - and will give fundamentally different results
** in situations where a server is dropping requests. Therefore you can
** no longer compare results of AB as easily. Hence the inc of the version.
** They should be closer to the truth though. Sander & <[email protected]>, End 2000.
** - Fixed proxy functionality, added median/mean statistics, added gnuplot
** output option, added _experimental/rudimentary_ SSL support. Added
** confidence guestimators and warnings. Sander & <[email protected]>, End 2000
** - Fixed serious int overflow issues which would cause realistic (longer
** than a few minutes) run's to have wrong (but believable) results. Added
** trapping of connection errors which influenced measurements.
** Contributed by Sander Temme, Early 2001
** Version 1.3e
** - Changed timeout behavior during write to work whilst the sockets
** are filling up and apr_write() does writes a few - but not all.
** This will potentially change results. <[email protected]>, April 2001
** Version 2.0.36-dev
** Improvements to concurrent processing:
** - Enabled non-blocking connect()s.
** - Prevent blocking calls to apr_socket_recv() (thereby allowing AB to
** manage its entire set of socket descriptors).
** - Any error returned from apr_socket_recv() that is not EAGAIN or EOF
** is now treated as fatal.
** Contributed by Aaron Bannert, April 24, 2002
**
** Version 2.0.36-2
** Internalized the version string - this string is part
** of the Agent: header and the result output.
**
** Version 2.0.37-dev
** Adopted SSL code by Madhu Mathihalli <[email protected]>
** [PATCH] ab with SSL support Posted Wed, 15 Aug 2001 20:55:06 GMT
** Introduces four 'if (int == value)' tests per non-ssl request.
**
** Version 2.0.40-dev
** Switched to the new abstract pollset API, allowing ab to
** take advantage of future apr_pollset_t scalability improvements.
** Contributed by Brian Pane, August 31, 2002
**
** Version 2.3
** SIGINT now triggers output_results().
** Contributed by colm, March 30, 2006
**/
/* Note: this version string should start with \d+[\d\.]* and be a valid
* string for an HTTP Agent: header when prefixed with 'ApacheBench/'.
* It should reflect the version of AB - and not that of the apache server
* it happens to accompany. And it should be updated or changed whenever
* the results are no longer fundamentally comparable to the results of
* a previous version of ab. Either due to a change in the logic of
* ab - or to due to a change in the distribution it is compiled with
* (such as an APR change in for example blocking).
*/
#define AP_AB_BASEREVISION "2.3"
/*
* BUGS:
*
* - uses strcpy/etc.
* - has various other poor buffer attacks related to the lazy parsing of
* response headers from the server
* - doesn't implement much of HTTP/1.x, only accepts certain forms of
* responses
* - (performance problem) heavy use of strstr shows up top in profile
* only an issue for loopback usage
*/
/* -------------------------------------------------------------------- */
#if 'A' != 0x41
/* Hmmm... This source code isn't being compiled in ASCII.
* In order for data that flows over the network to make
* sense, we need to translate to/from ASCII.
*/
#define NOT_ASCII
#endif
/* affects include files on Solaris */
#define BSD_COMP
#include "apr.h"
#include "apr_signal.h"
#include "apr_strings.h"
#include "apr_network_io.h"
#include "apr_file_io.h"
#include "apr_ring.h"
#include "apr_time.h"
#include "apr_getopt.h"
#include "apr_general.h"
#include "apr_lib.h"
#include "apr_portable.h"
#include "ap_release.h"
#include "apr_poll.h"
#include "apr_atomic.h"
#if APR_HAS_THREADS
#include "apr_thread_proc.h"
#include "apr_thread_mutex.h"
#include "apr_thread_cond.h"
#if APR_HAVE_PTHREAD_H
#include <pthread.h>
#endif
#endif
#define APR_WANT_STRFUNC
#include "apr_want.h"
#include "apr_base64.h"
#ifdef NOT_ASCII
#include "apr_xlate.h"
#endif
#if APR_HAVE_STDIO_H
#include <stdio.h>
#endif
#if APR_HAVE_STDLIB_H
#include <stdlib.h>
#endif
#if APR_HAVE_UNISTD_H
#include <unistd.h> /* for getpid() */
#endif
// #if !defined(WIN32) && !defined(NETWARE)
// #include "ap_config_auto.h"
// #endif
#include <math.h>
#if APR_HAVE_CTYPE_H
#include <ctype.h>
#endif
#if APR_HAVE_LIMITS_H
#include <limits.h>
#endif
#if defined(HAVE_OPENSSL)
#include <openssl/rsa.h>
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/rand.h>
#define USE_SSL
#define SK_NUM(x) sk_X509_num(x)
#define SK_VALUE(x,y) sk_X509_value(x,y)
typedef STACK_OF(X509) X509_STACK_TYPE;
#if defined(_MSC_VER) && !defined(LIBRESSL_VERSION_NUMBER)
/* The following logic ensures we correctly glue FILE* within one CRT used
* by the OpenSSL library build to another CRT used by the ab.exe build.
* This became especially problematic with Visual Studio 2015.
*/
#include <openssl/applink.c>
#endif
#if (OPENSSL_VERSION_NUMBER >= 0x00909000)
#define AB_SSL_METHOD_CONST const
#else
#define AB_SSL_METHOD_CONST
#endif
#if (OPENSSL_VERSION_NUMBER >= 0x0090707f)
#define AB_SSL_CIPHER_CONST const
#else
#define AB_SSL_CIPHER_CONST
#endif
#ifdef SSL_OP_NO_TLSv1_2
#define HAVE_TLSV1_X
#endif
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_set_tlsext_host_name)
#define HAVE_TLSEXT
#endif
#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2060000f
#define SSL_CTRL_SET_MIN_PROTO_VERSION 123
#define SSL_CTRL_SET_MAX_PROTO_VERSION 124
#define SSL_CTX_set_min_proto_version(ctx, version) \
SSL_CTX_ctrl(ctx, SSL_CTRL_SET_MIN_PROTO_VERSION, version, NULL)
#define SSL_CTX_set_max_proto_version(ctx, version) \
SSL_CTX_ctrl(ctx, SSL_CTRL_SET_MAX_PROTO_VERSION, version, NULL)
#endif
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
#ifdef TLS1_3_VERSION
#define MAX_SSL_PROTO TLS1_3_VERSION
#else
#define MAX_SSL_PROTO TLS1_2_VERSION
#endif
#ifndef OPENSSL_NO_SSL3
#define MIN_SSL_PROTO SSL3_VERSION
#else
#define MIN_SSL_PROTO TLS1_VERSION
#endif
#endif /* OPENSSL_VERSION_NUMBER >= 0x10100000L */
#endif /* HAVE_OPENSSL */
/* ------------------- DEFINITIONS -------------------------- */
#ifndef LLONG_MAX
#define AB_MAX APR_INT64_C(0x7fffffffffffffff)
#else
#define AB_MAX LLONG_MAX
#endif
/* maximum number of requests on a time limited test */
#define MAX_REQUESTS (INT_MAX > 50000 ? 50000 : INT_MAX)
#define ROUND_UP(x, y) ((((x) + (y) - 1) / (y)) * (y))
/* connection state
* don't add enums or rearrange or otherwise change values without
* visiting set_conn_state()
*/
typedef enum {
STATE_UNCONNECTED = 0,
STATE_CONNECTING, /* TCP connect initiated, but we don't
* know if it worked yet
*/
STATE_CONNECTED, /* we know TCP connect completed */
#ifdef USE_SSL
STATE_HANDSHAKE, /* in the handshake phase */
#endif
STATE_WRITE, /* in the write phase */
STATE_READ /* in the read phase */
} connect_state_e;
#define CBUFFSIZE (8192)
/* forward declare */
struct worker;
struct connection {
APR_RING_ENTRY(connection) delay_list;
struct worker *worker;
apr_pool_t *ctx;
apr_socket_t *aprsock;
apr_pollfd_t pollfd;
int state;
apr_time_t delay;
apr_size_t read; /* amount of bytes read */
apr_size_t bread; /* amount of body read */
apr_size_t rwrite, rwrote; /* keep pointers in what we write - across
* EAGAINs */
apr_size_t length; /* Content-Length value used for keep-alive */
char cbuff[CBUFFSIZE]; /* a buffer to store server response header */
int cbx; /* offset in cbuffer */
int keepalive; /* non-zero if a keep-alive request */
int gotheader; /* non-zero if we have the entire header in
* cbuff */
apr_time_t start, /* Start of connection */
connect, /* Connected, start writing */
endwrite, /* Request written */
beginread, /* First byte of input */
end; /* Connection closed */
apr_size_t keptalive; /* subsequent keepalive requests */
#ifdef USE_SSL
SSL *ssl;
#endif
};
struct data {
apr_time_t starttime; /* start time of connection */
apr_interval_time_t waittime; /* between request and reading response */
apr_interval_time_t ctime; /* time to connect */
apr_interval_time_t time; /* time for connection */
};
struct metrics {
apr_size_t doclen; /* the length the document should be */
apr_int64_t totalread; /* total number of bytes read */
apr_int64_t totalbread; /* totoal amount of entity body read */
apr_int64_t totalposted; /* total number of bytes posted, inc. headers */
apr_int64_t done; /* number of requests we have done */
apr_int64_t doneka; /* number of keep alive connections done */
apr_int64_t good, bad; /* number of good and bad requests */
int epipe; /* number of broken pipe writes */
int err_length; /* requests failed due to response length */
int err_conn; /* requests failed due to connection drop */
int err_recv; /* requests failed due to broken read */
int err_except; /* requests failed due to exception */
int err_response; /* requests with invalid or non-200 response */
int concurrent; /* Number of multiple requests actually made */
#ifdef USE_SSL
char ssl_info[128];
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
char ssl_tmp_key[128];
#endif
#endif
};
APR_RING_HEAD(delayed_ring_t, connection);
struct worker {
apr_pool_t *pool;
#if APR_HAS_THREADS
apr_thread_t *thd;
#endif
apr_pollset_t *pollset;
apr_sockaddr_t *destsa;
int slot;
int requests;
int concurrency;
int succeeded_once; /* response header received once */
apr_int64_t started; /* number of requests started, so no excess */
struct data *stats;
struct connection *conns;
struct delayed_ring_t delayed_ring;
struct metrics metrics;
char buffer[CBUFFSIZE]; /* throw-away buffer to read stuff into */
};
/* global metrics (consolidated from workers') */
static struct metrics metrics;
static void consolidate_metrics(void);
#define ap_min(a,b) (((a)<(b))?(a):(b))
#define ap_max(a,b) (((a)>(b))?(a):(b))
// #define ap_round_ms(a) ((apr_time_t)((a) + 500)/1000)
// #define ap_double_ms(a) ((double)(a)/1000.0)
#define ap_round_ms(a) ((apr_time_t)a)
#define ap_double_ms(a) ((double)a)
#define MAX_CONCURRENCY 20000
/* --------------------- GLOBALS ---------------------------- */
int verbosity = 0; /* no verbosity by default */
int recverrok = 0; /* ok to proceed after socket receive errors */
enum {NO_METH = 0, GET, HEAD, PUT, POST, CUSTOM_METHOD} method = NO_METH;
const char *method_str[] = {"bug", "GET", "HEAD", "PUT", "POST", ""};
int send_body = 0; /* non-zero if sending body with request */
int requests = 1; /* Number of requests to make */
int num_workers = 1; /* Number of worker threads to use */
int heartbeatres = 100; /* How often do we say we're alive */
int concurrency = 1; /* Number of multiple requests to make */
int percentile = 1; /* Show percentile served */
int nolength = 0; /* Accept variable document length */
int confidence = 1; /* Show confidence estimator and warnings */
int tlimit = 0; /* time limit in secs */
int keepalive = 0; /* try and do keepalive connections */
int windowsize = 0; /* we use the OS default window size */
char servername[1024]; /* name that server reports */
char *hostname; /* host name from URL */
const char *host_field; /* value of "Host:" header field */
const char *path; /* path name */
char *postdata; /* *buffer containing data from postfile */
apr_size_t postlen = 0; /* length of data to be POSTed */
char *content_type = NULL; /* content type to put in POST header */
const char *cookie, /* optional cookie line */
*auth, /* optional (basic/uuencoded) auhentication */
*hdrs; /* optional arbitrary headers */
apr_port_t port; /* port number */
char *proxyhost = NULL; /* proxy host name */
int proxyport = 0; /* proxy port */
const char *connecthost;
const char *myhost;
apr_port_t connectport;
const char *gnuplot; /* GNUplot file */
const char *csvperc; /* CSV Percentile file */
const char *fullurl;
const char *colonhost;
int isproxy = 0;
apr_interval_time_t hbperiod = 0; /* heartbeat period (when time limited) */
apr_interval_time_t aprtimeout = apr_time_from_sec(30); /* timeout value */
apr_interval_time_t ramp = apr_time_from_msec(0); /* ramp delay */
int pollset_wakeable = 0;
/* overrides for ab-generated common headers */
const char *opt_host; /* which optional "Host:" header specified, if any */
int opt_useragent = 0; /* was an optional "User-Agent:" header specified? */
int opt_accept = 0; /* was an optional "Accept:" header specified? */
/*
* XXX - this is now a per read/write transact type of value
*/
int use_html = 0; /* use html in the report */
const char *tablestring;
const char *trstring;
const char *tdstring;
#ifdef USE_SSL
int is_ssl;
SSL_CTX *ssl_ctx;
char *ssl_cipher = NULL;
char *ssl_cert = NULL;
BIO *bio_out,*bio_err;
#ifdef HAVE_TLSEXT
int tls_use_sni = 1; /* used by default, -I disables it */
const char *tls_sni = NULL; /* 'opt_host' if any, 'hostname' otherwise */
#endif
#endif
apr_time_t start, logtime;
volatile apr_time_t lasttime, stoptime;
/* global request (and its length) */
char _request[8192];
char *request = _request;
apr_size_t reqlen;
/* interesting percentiles */
int percs[] = {50, 66, 75, 80, 90, 95, 98, 99, 100};
struct worker *workers; /* worker threads */
struct connection *conns; /* connection array */
struct data *stats; /* data for each request */
apr_pool_t *cntxt;
apr_sockaddr_t *mysa;
apr_sockaddr_t *destsa;
#ifdef NOT_ASCII
apr_xlate_t *from_ascii, *to_ascii;
#endif
#if APR_HAS_THREADS
static apr_thread_mutex_t *workers_mutex;
static apr_thread_cond_t *workers_can_start;
#endif
static APR_INLINE int worker_should_exit(struct worker *worker)
{
return (lasttime >= stoptime
|| (!tlimit && worker->metrics.done >= worker->requests));
}
static APR_INLINE int worker_should_stop(struct worker *worker)
{
return (worker_should_exit(worker)
|| (!tlimit && worker->started >= worker->requests));
}
static void write_request(struct connection * c);
static void retry_connection(struct connection *c, apr_status_t status);
static void cleanup_connection(struct connection *c, int reuse);
static APR_INLINE void reuse_connection(struct connection *c)
{
cleanup_connection(c, 1);
}
static APR_INLINE void close_connection(struct connection *c)
{
cleanup_connection(c, 0);
}
static APR_INLINE void abort_connection(struct connection *c)
{
c->gotheader = 0; /* invalidate */
close_connection(c);
}
static void output_results(void);
static void output_html_results(void);
/* --------------------------------------------------------- */
/* simple little function to write an error string and exit */
static void err(const char *s)
{
fprintf(stderr, "%s\n", s);
fflush(stderr);
consolidate_metrics();
if (metrics.done)
printf("Total of %" APR_INT64_T_FMT " requests completed\n" , metrics.done);
if (use_html)
output_html_results();
else
output_results();
exit(1);
}
/* simple little function to write an APR error string and exit */
static void apr_err(const char *s, apr_status_t rv)
{
char buf[120];
fprintf(stderr, "%s: %s (%d)\n",
s, apr_strerror(rv, buf, sizeof buf), rv);
fflush(stderr);
consolidate_metrics();
if (metrics.done)
printf("Total of %" APR_INT64_T_FMT " requests completed\n" , metrics.done);
if (use_html)
output_html_results();
else
output_results();
exit(rv);
}
/*
* Similar to standard strstr() but we ignore case in this version.
* Copied from ap_strcasestr().
*/
static char *xstrcasestr(const char *s1, const char *s2)
{
char *p1, *p2;
if (*s2 == '\0') {
/* an empty s2 */
return((char *)s1);
}
while(1) {
for ( ; (*s1 != '\0') && (apr_tolower(*s1) != apr_tolower(*s2)); s1++);
if (*s1 == '\0') {
return(NULL);
}
/* found first character of s2, see if the rest matches */
p1 = (char *)s1;
p2 = (char *)s2;
for (++p1, ++p2; apr_tolower(*p1) == apr_tolower(*p2); ++p1, ++p2) {
if (*p1 == '\0') {
/* both strings ended together */
return((char *)s1);
}
}
if (*p2 == '\0') {
/* second string ended, a match */
break;
}
/* didn't find a match here, try starting at next character in s1 */
s1++;
}
return((char *)s1);
}
/* pool abort function */
static int abort_on_oom(int retcode)
{
fprintf(stderr, "Could not allocate memory\n");
exit(1);
/* not reached */
return retcode;
}
static void set_polled_events(struct connection *c, apr_int16_t new_reqevents)
{
apr_status_t rv;
if (c->pollfd.reqevents != new_reqevents) {
if (c->pollfd.reqevents != 0) {
rv = apr_pollset_remove(c->worker->pollset, &c->pollfd);
if (rv != APR_SUCCESS) {
apr_err("apr_pollset_remove()", rv);
}
}
if (new_reqevents != 0) {
c->pollfd.reqevents = new_reqevents;
rv = apr_pollset_add(c->worker->pollset, &c->pollfd);
if (rv != APR_SUCCESS) {
apr_err("apr_pollset_add()", rv);
}
}
}
}
static void set_conn_state(struct connection *c, connect_state_e new_state,
apr_int16_t events)
{
c->state = new_state;
set_polled_events(c, events);
}
/* --------------------------------------------------------- */
/* write out request to a connection - assumes we can write
* (small) request out in one go into our new socket buffer
*
*/
#ifdef USE_SSL
static long ssl_print_cb(BIO *bio,int cmd,const char *argp,int argi,long argl,long ret)
{
BIO *out;
out=(BIO *)BIO_get_callback_arg(bio);
if (out == NULL) return(ret);
if (cmd == (BIO_CB_READ|BIO_CB_RETURN)) {
BIO_printf(out,"read from %p [%p] (%d bytes => %ld (0x%lX))\n",
bio, argp, argi, ret, ret);
BIO_dump(out,(char *)argp,(int)ret);
return(ret);
}
else if (cmd == (BIO_CB_WRITE|BIO_CB_RETURN)) {
BIO_printf(out,"write to %p [%p] (%d bytes => %ld (0x%lX))\n",
bio, argp, argi, ret, ret);
BIO_dump(out,(char *)argp,(int)ret);
}
return ret;
}
static void ssl_state_cb(const SSL *s, int w, int r)
{
if (w & SSL_CB_ALERT) {
BIO_printf(bio_err, "SSL/TLS Alert [%s] %s:%s\n",
(w & SSL_CB_READ ? "read" : "write"),
SSL_alert_type_string_long(r),
SSL_alert_desc_string_long(r));
} else if (w & SSL_CB_LOOP) {
BIO_printf(bio_err, "SSL/TLS State [%s] %s\n",
(SSL_in_connect_init((SSL*)s) ? "connect" : "-"),
SSL_state_string_long(s));
} else if (w & (SSL_CB_HANDSHAKE_START|SSL_CB_HANDSHAKE_DONE)) {
BIO_printf(bio_err, "SSL/TLS Handshake [%s] %s\n",
(w & SSL_CB_HANDSHAKE_START ? "Start" : "Done"),
SSL_state_string_long(s));
}
}
#if OPENSSL_VERSION_NUMBER < 0x10101000
#ifndef RAND_MAX
#define RAND_MAX INT_MAX
#endif
static int ssl_rand_choosenum(int l, int h)
{
int i;
char buf[50];
apr_snprintf(buf, sizeof(buf), "%.0f",
(((double)(rand()%RAND_MAX)/RAND_MAX)*(h-l)));
i = atoi(buf)+1;
if (i < l) i = l;
if (i > h) i = h;
return i;
}
static void ssl_rand_seed(void)
{
int n, l;
apr_time_t t;
pid_t pid;
unsigned char stackdata[256];
/*
* seed in the current time (usually just 4 bytes)
*/
t = lasttime;
l = sizeof(apr_time_t);
RAND_seed((unsigned char *)&t, l);
/*
* seed in the current process id (usually just 4 bytes)
*/
pid = getpid();
l = sizeof(pid_t);
RAND_seed((unsigned char *)&pid, l);
/*
* seed in some current state of the run-time stack (128 bytes)
*/
n = ssl_rand_choosenum(0, sizeof(stackdata)-128-1);
RAND_seed(stackdata+n, 128);
}
#else
#define ssl_rand_seed() /* noop */
#endif
static int ssl_print_connection_info(BIO *bio, SSL *ssl)
{
AB_SSL_CIPHER_CONST SSL_CIPHER *c;
int alg_bits,bits;
BIO_printf(bio,"Transport Protocol :%s\n", SSL_get_version(ssl));
c = SSL_get_current_cipher(ssl);
BIO_printf(bio,"Cipher Suite Protocol :%s\n", SSL_CIPHER_get_version(c));
BIO_printf(bio,"Cipher Suite Name :%s\n",SSL_CIPHER_get_name(c));
bits = SSL_CIPHER_get_bits(c,&alg_bits);
BIO_printf(bio,"Cipher Suite Cipher Bits:%d (%d)\n",bits,alg_bits);
return(1);
}
static void ssl_print_cert_info(BIO *bio, X509 *cert)
{
X509_NAME *dn;
EVP_PKEY *pk;
char buf[1024];
BIO_printf(bio, "Certificate version: %ld\n", X509_get_version(cert)+1);
BIO_printf(bio,"Valid from: ");
ASN1_UTCTIME_print(bio, X509_get_notBefore(cert));
BIO_printf(bio,"\n");
BIO_printf(bio,"Valid to : ");
ASN1_UTCTIME_print(bio, X509_get_notAfter(cert));
BIO_printf(bio,"\n");
pk = X509_get_pubkey(cert);
BIO_printf(bio,"Public key is %d bits\n",
EVP_PKEY_bits(pk));
EVP_PKEY_free(pk);
dn = X509_get_issuer_name(cert);
X509_NAME_oneline(dn, buf, sizeof(buf));
BIO_printf(bio,"The issuer name is %s\n", buf);
dn=X509_get_subject_name(cert);
X509_NAME_oneline(dn, buf, sizeof(buf));
BIO_printf(bio,"The subject name is %s\n", buf);
/* dump the extension list too */
BIO_printf(bio, "Extension Count: %d\n", X509_get_ext_count(cert));
}
static void ssl_print_info(struct connection *c)
{
X509_STACK_TYPE *sk;
X509 *cert;
int count;
BIO_printf(bio_err, "\n");
sk = SSL_get_peer_cert_chain(c->ssl);
if ((count = SK_NUM(sk)) > 0) {
int i;
for (i=1; i<count; i++) {
cert = (X509 *)SK_VALUE(sk, i);
ssl_print_cert_info(bio_out, cert);
}
}
cert = SSL_get_peer_certificate(c->ssl);
if (cert == NULL) {
BIO_printf(bio_out, "Anon DH\n");
} else {
BIO_printf(bio_out, "Peer certificate\n");
ssl_print_cert_info(bio_out, cert);
X509_free(cert);
}
ssl_print_connection_info(bio_err,c->ssl);
SSL_SESSION_print(bio_err, SSL_get_session(c->ssl));
}
static void ssl_proceed_handshake(struct connection *c)
{
struct worker *worker = c->worker;
int again;
do {
int ret, ecode;
apr_status_t status;
again = 0; /* until further notice */
ret = SSL_do_handshake(c->ssl);
ecode = SSL_get_error(c->ssl, ret);
switch (ecode) {
case SSL_ERROR_NONE:
if (verbosity >= 2)
ssl_print_info(c);
if (!worker->metrics.ssl_info[0]) {
AB_SSL_CIPHER_CONST SSL_CIPHER *ci;
X509 *cert;
int sk_bits, pk_bits, swork;
ci = SSL_get_current_cipher(c->ssl);
sk_bits = SSL_CIPHER_get_bits(ci, &swork);
cert = SSL_get_peer_certificate(c->ssl);
if (cert)
pk_bits = EVP_PKEY_bits(X509_get_pubkey(cert));
else
pk_bits = 0; /* Anon DH */
apr_snprintf(worker->metrics.ssl_info, sizeof(worker->metrics.ssl_info),
"%s,%s,%d,%d",
SSL_get_version(c->ssl),
SSL_CIPHER_get_name(ci),
pk_bits, sk_bits);
}
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
if (!worker->metrics.ssl_tmp_key[0] && !worker->metrics.ssl_tmp_key[1]) {
EVP_PKEY *key;
if (SSL_get_server_tmp_key(c->ssl, &key)) {
switch (EVP_PKEY_id(key)) {
case EVP_PKEY_RSA:
apr_snprintf(worker->metrics.ssl_tmp_key, 128, "RSA %d bits",
EVP_PKEY_bits(key));
break;
case EVP_PKEY_DH:
apr_snprintf(worker->metrics.ssl_tmp_key, 128, "DH %d bits",
EVP_PKEY_bits(key));
break;
#ifndef OPENSSL_NO_EC
case EVP_PKEY_EC: {
const char *cname = NULL;
EC_KEY *ec = EVP_PKEY_get1_EC_KEY(key);
int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
EC_KEY_free(ec);
cname = EC_curve_nid2nist(nid);
if (!cname)
cname = OBJ_nid2sn(nid);
apr_snprintf(worker->metrics.ssl_tmp_key, 128, "ECDH %s %d bits",
cname, EVP_PKEY_bits(key));
break;
}
#endif
default:
apr_snprintf(worker->metrics.ssl_tmp_key, 128, "%s %d bits",
OBJ_nid2sn(EVP_PKEY_id(key)),
EVP_PKEY_bits(key));
break;
}
EVP_PKEY_free(key);
}
else {
/* not available, do not reenter here still */
worker->metrics.ssl_tmp_key[1] = !0;
}
}
#endif
write_request(c);
break;
case SSL_ERROR_WANT_READ:
set_conn_state(c, STATE_HANDSHAKE, APR_POLLIN);
break;
case SSL_ERROR_WANT_WRITE:
set_conn_state(c, STATE_HANDSHAKE, APR_POLLOUT);
break;
case SSL_ERROR_WANT_CONNECT:
case SSL_ERROR_SSL:
case SSL_ERROR_SYSCALL:
/* Unexpected result */
status = apr_get_netos_error();
BIO_printf(bio_err, "SSL handshake failed (%d): %s\n", ecode,
apr_psprintf(c->ctx, "%pm", &status));
ERR_print_errors(bio_err);
abort_connection(c);
break;
default:
again = 1;
break;
}
} while (again);
}
#endif /* USE_SSL */
static void write_request(struct connection * c)
{
struct worker *worker = c->worker;
do {
apr_time_t tnow;
apr_size_t l = c->rwrite;
apr_status_t e = APR_SUCCESS; /* prevent gcc warning */
tnow = lasttime = apr_time_now();
/*
* First time round ?
*/
if (c->rwrite == 0) {
/* zero connect time with keep-alive */
if (c->keptalive)
c->start = tnow;
c->connect = tnow;
c->rwrote = 0;
c->rwrite = reqlen;
if (send_body)
c->rwrite += postlen;
l = c->rwrite;
}
else if (tnow > c->connect + aprtimeout) {
printf("Send request timed out!\n");
abort_connection(c);
return;
}
#ifdef USE_SSL
if (c->ssl) {
e = SSL_write(c->ssl, request + c->rwrote, l);
if (e <= 0) {
switch (SSL_get_error(c->ssl, e)) {
case SSL_ERROR_WANT_READ:
set_conn_state(c, STATE_WRITE, APR_POLLIN);
break;
case SSL_ERROR_WANT_WRITE:
set_conn_state(c, STATE_WRITE, APR_POLLOUT);
break;
default:
BIO_printf(bio_err, "SSL write failed - closing connection\n");
ERR_print_errors(bio_err);
abort_connection(c);
break;
}
return;
}
l = e;
}
else
#endif
{
e = apr_socket_send(c->aprsock, request + c->rwrote, &l);
if (e != APR_SUCCESS && !l) {
if (APR_STATUS_IS_EAGAIN(e)) {
set_conn_state(c, STATE_WRITE, APR_POLLOUT);
}
else {
worker->metrics.epipe++;
printf("Send request failed!\n");
abort_connection(c);
}
return;
}
}
worker->metrics.totalposted += l;
c->rwrote += l;
c->rwrite -= l;
} while (c->rwrite);
c->endwrite = lasttime = apr_time_now();
worker->started++;
set_conn_state(c, STATE_READ, APR_POLLIN);
}
/* --------------------------------------------------------- */
/* calculate and output results */
static int compradre(struct data * a, struct data * b)
{
if ((a->ctime) < (b->ctime))
return -1;
if ((a->ctime) > (b->ctime))
return +1;
return 0;
}
static int comprando(struct data * a, struct data * b)
{
if ((a->time) < (b->time))
return -1;
if ((a->time) > (b->time))
return +1;