-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathh1load.c
2828 lines (2447 loc) · 76.7 KB
/
h1load.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
/*
* H1LOAD - simple HTTP/1 load generator
*
* Copyright (C) 2000-2020 Willy Tarreau - [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#define _GNU_SOURCE /* for F_SETPIPE_SZ */
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/user.h>
#include <sys/epoll.h>
#include <sys/resource.h>
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#if defined(USE_SSL)
#include <openssl/err.h>
#include <openssl/ssl.h>
#endif
/* some platforms do not provide PAGE_SIZE */
#ifndef PAGE_SIZE
#define PAGE_SIZE sysconf(_SC_PAGESIZE)
#endif
#ifndef MAXTHREADS
#define MAXTHREADS 256
#endif
#ifndef EPOLLRDHUP
#define EPOLLRDHUP 0
#endif
/* some useful types */
struct list {
struct list *n, *p;
};
#undef LIST_INIT
#undef LIST_NEXT
#define LIST_INIT(lh) ((lh)->n = (lh)->p = (lh))
#define LIST_ISEMPTY(lh) ((lh)->n == (lh))
#define LIST_APPEND(lh, el) ({ (el)->p = (lh)->p; (el)->p->n = (lh)->p = (el); (el)->n = (lh); (el); })
#define LIST_DELETE(el) ({ typeof(el) __ret = (el); (el)->n->p = (el)->p; (el)->p->n = (el)->n; (__ret); })
#define LIST_ELEM(lh, pt, el) ((pt)(((void *)(lh)) - ((void *)&((pt)0)->el)))
#define LIST_NEXT(lh, pt, el) (LIST_ELEM((lh)->n, pt, el))
#define LIST_DEL_INIT(el) \
({ typeof(el) __ret = (el); typeof(__ret->n) __n = __ret->n; typeof(__ret->p) __p = __ret->p; \
__n->p = __p; __p->n = __n; __ret->n = __ret->p = __ret; __ret; })
/* an error message returned to a caller */
struct errmsg {
char *msg;
size_t size;
size_t len;
};
/* frequency counter, smoothed over a sliding second period */
struct freq_ctr {
uint32_t curr_sec; /* start date of current period (seconds from now.tv_sec) */
uint32_t curr_ctr; /* cumulated value for current period */
uint32_t prev_ctr; /* value for last period */
};
/* connection flags */
#define CF_BLKW 0x00000001 // blocked on writes
#define CF_BLKR 0x00000002 // blocked on reads
#define CF_POLW 0x00000004 // subscribed to polling for writing
#define CF_POLR 0x00000008 // subscribed to polling for reading
#define CF_ERR 0x00000010 // I/O error reported
#define CF_HEAD 0x00000020 // a HEAD request was last sent
#define CF_V11 0x00000040 // HTTP/1.1 used for the response
#define CF_EXP 0x00000080 // task expired in a wait queue
#define CF_CHNK 0x00000100 // chunked encoding
#define CF_HUPR 0x00000200 // HUP/RDHUP reported by poller
#define CF_HUPC 0x00000400 // HUP/RDHUP confirmed
/* connection states */
enum cstate {
CS_NEW = 0, // just allocated
CS_CON, // pending connection attempt
CS_HSK, // pending SSL handshake
CS_REQ, // count a new request and check vs global limits
CS_SND, // send attempt (headers or body) (a req is active)
CS_RCV, // recv attempt (headers or body) (a req is active)
CS_THK, // think time
CS_END // finished, must be freed
};
/* describes a connection */
struct conn {
struct list link; // empty/io queue/think queue/run queue
struct timeval expire; // next expiration date
uint32_t flags; // CF_*
enum cstate state; // CS_*
int fd; // associated FD
int to_send; // number of bytes left to send from <send_ptr>
void *send_ptr; // where to send from
uint64_t to_recv; // bytes left to receive; 0=headers; ~0=unlimited
uint64_t tot_req; // total requests on this connection
uint64_t chnk_size; // current chunk size being parsed
struct timeval req_date; // moment the request was sent
#if defined(USE_SSL)
SSL *ssl; // SSL instance for this connection.
#endif
};
/* one thread */
struct thread_ctx {
struct list wq; // wait queue: I/O
struct list sq[32]; // sleep queue: sleep
struct list rq; // run queue: tasks to call
struct list iq; // idle queue: when not anywhere else
struct timeval now; // current time
struct freq_ctr req_rate; // thread's measured request rate
struct freq_ctr conn_rate; // thread's measured connection rate
uint32_t cur_req; // number of active requests
uint32_t curconn; // number of active connections
uint32_t maxconn; // max number of active connections
uint32_t is_ssl; // non-zero if SSL is used
uint64_t tot_conn; // total conns attempted on this thread
uint64_t tot_req; // total requests started on this thread
uint64_t tot_done; // total requests finished (successes+failures)
uint64_t tot_sent; // total bytes sent on this thread
uint64_t tot_rcvd; // total bytes received on this thread
uint64_t tot_serr; // total socket errors on this thread
uint64_t tot_cerr; // total connection errors on this thread
uint64_t tot_xerr; // total xfer errors on this thread
uint64_t tot_perr; // total protocol errors on this thread
uint64_t tot_cto; // total connection timeouts on this thread
uint64_t tot_xto; // total xfer timeouts on this thread
uint64_t tot_fbs; // total number of ttfb samples
uint64_t tot_ttfb; // total time-to-first-byte (us)
uint64_t tot_lbs; // total number of ttlb samples
uint64_t tot_ttlb; // total time-to-last-byte (us)
uint64_t *ttfb_pct; // counts per ttfb value for percentile
uint64_t *ttlb_pct; // counts per ttlb value for percentile
uint64_t tot_sc[5]; // total status codes on this thread: 1xx,2xx,3xx,4xx,5xx
int epollfd; // poller's FD
int start_len; // request's start line's length
char *start_line; // copy of the request's start line to be sent
char *hdr_block; // copy of the request's header block to be sent
int hdr_len; // request's header block's length
int ka_req_len; // keep-alive request length
char *ka_req; // fully assembled keep-alive request
char *cl_req; // fully assembled close request
int cl_req_len; // close request length
int tid; // thread number
struct timeval start_date; // thread's start date
pthread_t pth; // the pthread descriptor
struct sockaddr_storage dst; // destination address
struct sockaddr_storage pre_heat; // destination address for pre-heat
struct epoll_event *events; // event buffer
#if defined(USE_SSL)
SSL_CTX *ssl_ctx; // ssl context
unsigned char *ssl_sess; // stored ssl session;
int ssl_sess_size; // size of current stored session.
int ssl_sess_allocated; // current allocated size of stored session
#endif
__attribute__((aligned(64))) union { } __pad;
};
/* common constants for setsockopt() */
const int zero = 0;
const int one = 1;
/* default settings */
const int pollevents = 400;
const struct linger nolinger = { .l_onoff = 1, .l_linger = 0 };
/* command line arguments */
int arg_conn = 1; // concurrent conns
int arg_rcon = -1; // max requests per conn
long arg_reqs = -1; // max total requests
int arg_thnk = 0; // think time (ms)
int arg_thrd = 1; // number of threads
int arg_wait = 10000; // I/O time out (ms)
int arg_verb = 0; // verbosity
int arg_fast = 0; // merge send with connect's ACK
int arg_head = 0; // use HEAD
int arg_dura = 0; // test duration in sec if non-nul
int arg_host = 0; // set if host was passed in a header
int arg_ovre = 0; // overhead correction, extra bytes
int arg_ovrp = 0; // overhead correction, per-payload size
int arg_slow = 0; // slow start: delay in milliseconds
int arg_serr = 0; // stop on first error
int arg_long = 0; // long output format; 2=raw values
int arg_pctl = 0; // report percentiles.
int arg_rate = 0; // connection & request rate limit
int arg_accu = 0; // more accurate req/time measurements in keep-alive
int arg_hscd = 0; // HTTP status code distribution
char *arg_url;
char *arg_hdr;
#if defined(USE_SSL)
char *arg_ssl_cipher_list; // cipher list for TLSv1.2 and below
char *arg_ssl_cipher_suites; // cipher suites for TLSv1.3 and above
int arg_ssl_proto_ver = -1; // protocol version to use
int arg_ssl_reuse_sess = 0; // reuse session on TLS
#endif
static char *start_line;
static char *hdr_block;
/* global state */
#define THR_STOP_ALL 0x80000000 // set on running: must stop now!
#define THR_ENDING 0x40000000 // set on running: end once done
#define THR_SYNSTART 0x20000000 // set on running: threads wait for 0
#define THR_DUR_OVER 0x10000000 // test duration is over
#define THR_COUNT 0x0FFFFFFF // mask applied to check thr count
volatile uint32_t running = 0; // # = running threads + THR_* above
struct thread_ctx threads[MAXTHREADS];
struct timeval start_date, stop_date, now;
volatile uint32_t throttle = 0; // pass to mul32hi() if not null.
volatile unsigned long global_req = 0; // global (started) req counter to sync threads.
/* current thread */
__thread struct thread_ctx *thr;
__thread char buf[65536];
/* unsigned 16-bit float:
* b15..b11 = 5-bit exponent
* b10..b0 = 11-bit mantissa
*
* Numbers below 1024 are like usual denormals in that they are the only ones
* without bit 10 set. Values 0..2047 are mapped to the same encoding. Values
* 2^42 and above are infinite and all encoded as 0xFFFF.
*/
typedef uint16_t uf16_t;
/* make a uf16 from an exponent and a mantissa */
static inline uf16_t uf16(uint8_t e, uint16_t m)
{
return ((uf16_t)e << 11) + m;
}
/* converts any value between 0 and 2^42 to a uf16 */
static inline uf16_t to_uf16(uint64_t v)
{
uint64_t max = (uint64_t)0x7FF << 31;
int8_t e;
v = (v <= max) ? v : max;
if (sizeof(long) == 8) {
e = __builtin_clzl(v) ^ 63;
} else {
if (v >> 32)
e = 32 + (__builtin_clzl(v >> 32) ^ 31);
else
e = __builtin_clzl(v) ^ 31;
}
e -= 10;
if (e < 0)
e = 0;
v >>= e;
return uf16(e, v);
}
static inline uint64_t from_uf16(uf16_t u)
{
return (uint64_t)(u & 0x7FF) << (u >> 11);
}
/************ time manipulation functions ***************/
/* timeval is not set */
#define TV_UNSET ((struct timeval){ .tv_sec = 0, .tv_usec = ~0 })
/* make a timeval from <sec>, <usec> */
static inline struct timeval tv_set(time_t sec, suseconds_t usec)
{
struct timeval ret = { .tv_sec = sec, .tv_usec = usec };
return ret;
}
/* used to unset a timeout */
static inline struct timeval tv_unset()
{
return tv_set(0, ~0);
}
/* used to zero a timeval */
static inline struct timeval tv_zero()
{
return tv_set(0, 0);
}
/* returns true if the timeval is set */
static inline int tv_isset(struct timeval tv)
{
return tv.tv_usec != ~0;
}
/* returns the interval in microseconds, which must be set */
static inline uint64_t tv_us(const struct timeval tv)
{
return tv.tv_sec * (uint64_t)1000000 + tv.tv_usec;
}
/* returns true if <a> is before <b>, taking account unsets */
static inline int tv_isbefore(const struct timeval a, const struct timeval b)
{
return !tv_isset(b) ? 1 :
!tv_isset(a) ? 0 :
( a.tv_sec < b.tv_sec || (a.tv_sec == b.tv_sec && a.tv_usec < b.tv_usec));
}
/* returns the lowest of the two timers, for use in delay computation */
static inline struct timeval tv_min(const struct timeval a, const struct timeval b)
{
if (tv_isbefore(a, b))
return a;
else
return b;
}
/* returns the normalized sum of the <from> plus <off> */
static inline struct timeval tv_add(const struct timeval from, const struct timeval off)
{
struct timeval ret;
ret.tv_sec = from.tv_sec + off.tv_sec;
ret.tv_usec = from.tv_usec + off.tv_usec;
if (ret.tv_usec >= 1000000) {
ret.tv_usec -= 1000000;
ret.tv_sec += 1;
}
return ret;
}
/* returns the normalized sum of <from> plus <ms> milliseconds */
static inline struct timeval tv_ms_add(const struct timeval from, unsigned int ms)
{
struct timeval tv;
tv.tv_usec = from.tv_usec + (ms % 1000) * 1000;
tv.tv_sec = from.tv_sec + (ms / 1000);
if (tv.tv_usec >= 1000000) {
tv.tv_usec -= 1000000;
tv.tv_sec++;
}
return tv;
}
/* returns the delay between <past> and <now> or zero if <past> is after <now> */
static inline struct timeval tv_diff(const struct timeval past, const struct timeval now)
{
struct timeval ret = { .tv_sec = 0, .tv_usec = 0 };
if (tv_isbefore(past, now)) {
ret.tv_sec = now.tv_sec - past.tv_sec;
ret.tv_usec = now.tv_usec - past.tv_usec;
if ((signed)ret.tv_usec < 0) { // overflow
ret.tv_usec += 1000000;
ret.tv_sec -= 1;
}
}
return ret;
}
/* returns the time remaining between <tv1> and <tv2>, or zero if passed */
static inline struct timeval tv_remain(const struct timeval tv1, const struct timeval tv2)
{
struct timeval tv;
tv.tv_usec = tv2.tv_usec - tv1.tv_usec;
tv.tv_sec = tv2.tv_sec - tv1.tv_sec;
if ((signed)tv.tv_sec > 0) {
if ((signed)tv.tv_usec < 0) {
tv.tv_usec += 1000000;
tv.tv_sec--;
}
} else if (tv.tv_sec == 0) {
if ((signed)tv.tv_usec < 0)
tv.tv_usec = 0;
} else {
tv.tv_sec = 0;
tv.tv_usec = 0;
}
return tv;
}
/* returns the time remaining between <tv1> and <tv2> in milliseconds rounded
* up to the next millisecond, or zero if passed.
*/
static inline unsigned long tv_ms_remain(const struct timeval tv1, const struct timeval tv2)
{
struct timeval tv;
tv = tv_remain(tv1, tv2);
return tv.tv_sec * 1000 + (tv.tv_usec + 999) / 1000;
}
/* Multiply the two 32-bit operands and shift the 64-bit result right 32 bits.
* This is used to compute fixed ratios by setting one of the operands to
* (2^32*ratio).
*/
static inline uint32_t mul32hi(uint32_t a, uint32_t b)
{
return ((uint64_t)a * b + a - 1) >> 32;
}
/* read a freq counter over a 1-second period and return the event rate/s */
uint32_t read_freq_ctr(struct freq_ctr *ctr, const struct timeval now)
{
uint32_t curr, past;
uint32_t age;
age = now.tv_sec - ctr->curr_sec;
if (age > 1)
return 0;
curr = 0;
past = ctr->curr_ctr;
if (!age) {
curr = past;
past = ctr->prev_ctr;
}
if (past <= 1 && !curr)
return past; /* very low rate, avoid flapping */
return curr + mul32hi(past, (unsigned)(999999 - now.tv_usec) * 4294U);
}
/* returns the number of remaining events that can occur on this freq counter
* while respecting <freq> and taking into account that <pend> events are
* already known to be pending. Returns 0 if limit was reached.
*/
uint32_t freq_ctr_remain(struct freq_ctr *ctr, uint32_t freq, uint32_t pend, const struct timeval now)
{
uint32_t curr, past;
uint32_t age;
curr = 0;
age = now.tv_sec - ctr->curr_sec;
if (age <= 1) {
past = ctr->curr_ctr;
if (!age) {
curr = past;
past = ctr->prev_ctr;
}
curr += mul32hi(past, (unsigned)(999999 - now.tv_usec) * 4294U);
}
curr += pend;
if (curr >= freq)
return 0;
return freq - curr;
}
/* return the expected wait time in ms before the next event may occur,
* respecting frequency <freq>, and assuming there may already be some pending
* events. It returns zero if we can proceed immediately, otherwise the wait
* time, which will be rounded down 1ms for better accuracy, with a minimum
* of one ms.
*/
uint32_t next_event_delay(struct freq_ctr *ctr, uint32_t freq, uint32_t pend, const struct timeval now)
{
uint32_t curr, past;
uint32_t wait, age;
past = 0;
curr = 0;
age = now.tv_sec - ctr->curr_sec;
if (age <= 1) {
past = ctr->curr_ctr;
if (!age) {
curr = past;
past = ctr->prev_ctr;
}
curr += mul32hi(past, (unsigned)(999999 - now.tv_usec) * 4294U);
}
curr += pend;
if (curr < freq)
return 0;
/* too many events already, let's count how long to wait before they're
* processed.
*/
curr = curr - freq; // number of events left after current period
/* each events takes 1/freq second or 1000/freq ms */
wait = curr * 1000 / freq;
if (!wait)
wait = 1;
return wait;
}
/* Rotate a frequency counter when current period is over. Must not be called
* during a valid period. It is important that it correctly initializes a null
* area.
*/
static inline void rotate_freq_ctr(struct freq_ctr *ctr, const struct timeval now)
{
ctr->prev_ctr = ctr->curr_ctr;
if (now.tv_sec - ctr->curr_sec != 1) {
/* we missed more than one second */
ctr->prev_ctr = 0;
}
ctr->curr_sec = now.tv_sec;
ctr->curr_ctr = 0; /* leave it at the end to help gcc optimize it away */
}
/* Update a frequency counter by <inc> incremental units. It is automatically
* rotated if the period is over. It is important that it correctly initializes
* a null area.
*/
static inline void update_freq_ctr(struct freq_ctr *ctr, uint32_t inc, const struct timeval now)
{
if (ctr->curr_sec == now.tv_sec) {
ctr->curr_ctr += inc;
return;
}
rotate_freq_ctr(ctr, now);
ctr->curr_ctr = inc;
}
/************ connection management **************/
static inline int may_add_req()
{
unsigned long rq_cnt = global_req;
if (arg_reqs <= 0)
return 1;
do {
if (rq_cnt >= arg_reqs)
return 0;
} while (!__atomic_compare_exchange_n(&global_req, &rq_cnt, rq_cnt + 1,
0, __ATOMIC_RELAXED, __ATOMIC_RELAXED));
return 1;
}
/* updates polling on epoll FD <ep> for fd <fd> supposed to match connection
* flags <flags>.
*/
void update_poll(int ep, int fd, uint32_t flags, void *ptr)
{
struct epoll_event ev;
int op;
ev.data.ptr = ptr;
ev.events = ((flags & CF_BLKW) ? EPOLLOUT : 0) | ((flags & CF_BLKR) ? (EPOLLRDHUP|EPOLLHUP|EPOLLIN) : 0);
if (!(flags & (CF_POLR | CF_POLW)))
op = EPOLL_CTL_ADD;
else if (!(flags & (CF_POLR | CF_POLW)))
op = EPOLL_CTL_DEL;
else
op = EPOLL_CTL_MOD;
epoll_ctl(ep, op, fd, &ev);
}
/* update epoll_fd <ep> for conn <conn>, adding flag <add> and removing <del> */
static inline void update_conn(int ep, struct conn *conn)
{
uint32_t flags = conn->flags;
if ((!(flags & CF_BLKW) ^ !(flags & CF_POLW)) |
(!(flags & CF_BLKR) ^ !(flags & CF_POLR))) {
update_poll(ep, conn->fd, flags, conn);
if (conn->flags & CF_BLKW)
conn->flags |= CF_POLW;
else
conn->flags &= ~CF_POLW;
if (conn->flags & CF_BLKR)
conn->flags |= CF_POLR;
else
conn->flags &= ~CF_POLR;
}
}
static inline void cant_send(struct conn *conn)
{
conn->flags |= CF_BLKW;
}
static inline void cant_recv(struct conn *conn)
{
conn->flags |= CF_BLKR;
}
static inline void stop_send(struct conn *conn)
{
conn->flags &= ~CF_BLKW;
}
static inline void stop_recv(struct conn *conn)
{
conn->flags &= ~CF_BLKR;
}
static inline void may_send(struct conn *conn)
{
conn->flags &= ~CF_BLKW;
}
static inline void may_recv(struct conn *conn)
{
conn->flags &= ~CF_BLKR;
}
/* Tries to read from <conn> into <ptr> for <len> max bytes. Returns the number
* of bytes read, 0 if a read shutdown was received, -1 if no data was read
* (and connection subscribed), -2 if an error was received. If the buffer is
* NULL, then data will be silently drained.
*/
static ssize_t recv_raw(struct conn *conn, void *ptr, ssize_t len)
{
ssize_t ret;
if (conn->flags & CF_HUPC)
return 0;
if (!ptr && !MSG_TRUNC) {
ptr = buf;
if (len > sizeof(buf))
len = sizeof(buf);
}
ret = recv(conn->fd, ptr, len, MSG_NOSIGNAL | MSG_DONTWAIT | (ptr ? 0 : MSG_TRUNC));
if (ret <= 0) {
if (ret == 0) {
return 0;
}
if (errno == EAGAIN) {
cant_recv(conn);
return -1;
}
/* that's an error, but only if we're not draining,
* otherwise it's an end.
*/
if (ptr) {
conn->flags |= CF_ERR;
return -2;
}
return 0;
}
if (ret < len && (conn->flags & CF_HUPR))
conn->flags |= CF_HUPC; // hang up confirmed
return ret;
}
/* Tries to send from <ptr> to <conn> for <len> max bytes. Returns the number
* of bytes effectively sent, or -1 if no data was sent (and connection
* subscribed) or -2 if an error was met.
*/
static ssize_t send_raw(struct conn *conn, void *ptr, ssize_t len)
{
ssize_t ret;
if (conn->flags & (CF_BLKW | CF_ERR)) {
if (conn->flags & CF_ERR)
return -2;
return -1;
}
ret = send(conn->fd, ptr, len, MSG_NOSIGNAL | MSG_DONTWAIT);
if (ret < 0) {
if (errno == EAGAIN) {
cant_send(conn);
return -1;
}
conn->flags |= CF_ERR;
return -2;
}
return ret;
}
#if defined(USE_SSL)
/* Tries to send from <ptr> to <conn> for <len> max bytes using SSL. Returns
* the number of bytes effectively sent, or -1 if no data was sent (and
* connection subscribed) or -2 if an error was met.
*/
static ssize_t send_ssl(struct conn *conn, void *ptr, ssize_t len)
{
ssize_t ret;
if (conn->flags & (CF_BLKW | CF_ERR)) {
if (conn->flags & CF_ERR)
return -2;
return -1;
}
ret = SSL_write(conn->ssl, ptr, len);
if (ret < 0) {
int err = SSL_get_error(conn->ssl, ret);
if (err == SSL_ERROR_WANT_WRITE) {
cant_send(conn);
ret = -1;
}
else if (err == SSL_ERROR_WANT_READ) {
cant_recv(conn);
ret = -1;
}
else {
conn->flags |= CF_ERR;
ret = -2;
}
}
return ret;
}
/* Tries to read from <conn> into <ptr> for <len> max bytes over SSL. Returns
* the number of bytes read, 0 if a read shutdown was received, -1 if no data
* was read (and connection subscribed), -2 if an error was received. If the
* buffer is NULL, then data will be silently drained.
*/
static ssize_t recv_ssl(struct conn *conn, void *ptr, ssize_t len)
{
ssize_t ret;
if (conn->flags & CF_HUPC)
return 0;
if (!ptr) {
/* drain */
ptr = buf;
if (len > sizeof(buf))
len = sizeof(buf);
}
ret = SSL_read(conn->ssl, ptr, len);
if (ret < 0) {
int err = SSL_get_error(conn->ssl, ret);
if (err == SSL_ERROR_WANT_WRITE) {
cant_send(conn);
ret = -1;
}
else if (err == SSL_ERROR_WANT_READ) {
cant_recv(conn);
ret = -1;
}
else {
/* that's an error, but only if we're not draining,
* otherwise it's an end.
*/
if (ptr) {
conn->flags |= CF_ERR;
ret = -2;
} else {
ret = 0;
}
}
}
if (ret < len && (conn->flags & CF_HUPR))
conn->flags |= CF_HUPC; // hang up confirmed
return ret;
}
#endif
struct conn *new_conn()
{
struct conn *conn;
conn = malloc(sizeof(struct conn));
if (conn) {
conn->flags = 0;
conn->state = CS_NEW;
conn->expire = tv_unset();
conn->req_date = tv_unset();
conn->tot_req = 0;
#if defined(USE_SSL)
conn->ssl = NULL;
#endif
}
return conn;
}
/* pre-allocate connections to verify everything works well and to
* pre-initialize libc's and kernel's structures. Some tests have
* shown huge 25ms times around socket() alone during initial allocs!
* This will also help detect insufficient limits.
*/
struct conn *pre_heat_connection(struct thread_ctx *t)
{
struct conn *conn;
struct epoll_event ev;
struct sockaddr_storage addr;
socklen_t addr_len;
conn = new_conn();
if (!conn)
goto fail_conn;
conn->fd = socket(t->dst.ss_family, SOCK_STREAM, 0);
if (conn->fd < 0)
goto fail_sock;
if (fcntl(conn->fd, F_SETFL, O_NONBLOCK) == -1)
goto fail_setup;
if (setsockopt(conn->fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1)
goto fail_setup;
if (setsockopt(conn->fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)) == -1)
goto fail_setup;
#if defined(TCP_QUICKACK)
if (arg_fast && setsockopt(conn->fd, IPPROTO_TCP, TCP_QUICKACK, &zero, sizeof(zero)) == -1)
goto fail_setup;
#endif
/* only the first connection assigns a listening port, better stay
* short on this as bind() takes a huge amount of time finding a port.
*/
if (!t->curconn) {
memset(&addr, 0, sizeof(addr));
addr.ss_family = t->dst.ss_family;
if (bind(conn->fd, (struct sockaddr *)&addr, t->dst.ss_family == PF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)))
goto fail_setup;
t->pre_heat = addr;
}
else
addr = t->pre_heat;
addr_len = sizeof(addr);
if (getsockname(conn->fd, (struct sockaddr *)&addr, &addr_len) == -1)
goto fail_setup;
ev.data.ptr = 0;
ev.events = EPOLLIN;
/* connect to self */
if (connect(conn->fd, (struct sockaddr *)&addr, addr_len) < 0) {
/* let's assume it's EINPROGRESS */
ev.events |= EPOLLOUT;
}
setsockopt(conn->fd, SOL_SOCKET, SO_LINGER, &nolinger, sizeof(nolinger));
/* and register to epoll */
epoll_ctl(t->epollfd, EPOLL_CTL_ADD, conn->fd, &ev);
LIST_APPEND(&t->iq, &conn->link);
t->curconn++;
return conn;
fail_setup:
close(conn->fd);
fail_sock:
free(conn);
fail_conn:
if (arg_serr)
__sync_fetch_and_or(&running, THR_STOP_ALL);
t->tot_serr++;
return NULL;
}
/* Try to establish a connection to t->dst. Return the conn or NULL in case of error */
struct conn *add_connection(struct thread_ctx *t)
{
struct conn *conn;
conn = new_conn();
if (!conn)
goto fail_conn;
conn->fd = socket(t->dst.ss_family, SOCK_STREAM, 0);
if (conn->fd < 0)
goto fail_sock;
if (fcntl(conn->fd, F_SETFL, O_NONBLOCK) == -1)
goto fail_setup;
if (setsockopt(conn->fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1)
goto fail_setup;
if (setsockopt(conn->fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)) == -1)
goto fail_setup;
#if defined(TCP_QUICKACK)
if (arg_fast && setsockopt(conn->fd, IPPROTO_TCP, TCP_QUICKACK, &zero, sizeof(zero)) == -1)
goto fail_setup;
#endif
if (connect(conn->fd, (struct sockaddr *)&t->dst, t->dst.ss_family == PF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)) < 0) {
if (errno != EINPROGRESS)
goto fail_setup;
cant_send(conn);
conn->state = CS_CON;
LIST_APPEND(&t->iq, &conn->link);
}
else {
conn->state = CS_HSK;
LIST_APPEND(&t->iq, &conn->link);
}
if (arg_rate)
update_freq_ctr(&t->conn_rate, 1, t->now);
t->curconn++;
t->tot_conn++;
return conn;
fail_setup:
close(conn->fd);
fail_sock:
free(conn);
fail_conn:
if (arg_serr)
__sync_fetch_and_or(&running, THR_STOP_ALL);
t->tot_serr++;
return NULL;
}
/* parse HTTP response in <buf> of len <len>. Returns <0 on error (incl too
* short), or the number of bytes of headers block on success. If <rstatus> is
* not null, returns the parsed status there on success.
*/
int parse_resp(struct conn *conn, char *buf, int len, int *rstatus)
{
int ver;
int status;
uint64_t cl = 0;
int do_close = 0;
char *p, *hdr, *col, *eol, *end;
if (len < 13)
goto too_short;
if (memcmp(buf, "HTTP/1.", 7) != 0)
return -1;
ver = buf[7] - '0';
if (ver < 0 || ver > 1)
return -1;
if (ver > 0)
conn->flags |= CF_V11;
do_close = !ver;
if (buf[8] != ' ')
return -1;
if (buf[12] != ' ' && buf[12] != '\r' && buf[12] != '\n')
return -1;
status = buf[9] * 100 + buf[10] * 10 + buf[11] - '0' * 111;
if (status < 100 || status > 599)
return -1;
end = buf + len;
p = buf + 13;
while (1) {