-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcpspammer.c
1534 lines (1408 loc) · 42.2 KB
/
tcpspammer.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
#include <unistd.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <assert.h>
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <sched.h>
#include <fcntl.h>
#include <stdbool.h>
#include <pthread.h>
#include <stdarg.h>
#include <signal.h>
#include <netdb.h>
#include <errno.h>
#include <sys/sysinfo.h>
#include <sys/timerfd.h>
#include <sys/eventfd.h>
#include <sys/signalfd.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/epoll.h>
int logpipe[2];
static int verbosity = 0;
static unsigned int keepidle_value = 5;
static unsigned int max_conns_per_loop = 8192;
static void log_func(int lvl, const char *func, unsigned int line,
const char *fmt, ...)__attribute__((format(printf, 4, 5)));
static void log_func(int lvl, const char *func, unsigned int line,
const char *fmt, ...)
{
if (lvl <= verbosity)
{
va_list ap;
char buf[BUFSIZ];
size_t len;
ssize_t ret;
len = snprintf(buf, sizeof(buf), "%s:%u (#%d) ", func, line,
sched_getcpu());
va_start(ap, fmt);
len += vsnprintf(buf + len, sizeof(buf) - len, fmt, ap);
va_end(ap);
ret = write(logpipe[1], buf, len);
if (ret < 0 || ret != (ssize_t)len)
{
if (errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK)
{
perror("Writing to log pipe");
}
}
}
}
#define LOG(_lvl, _fmt, ...) \
log_func(_lvl, __func__, __LINE__, _fmt "\n", ##__VA_ARGS__)
#define FATAL(...) LOG(-1, __VA_ARGS__)
#define ERR(...) LOG(0, __VA_ARGS__)
#define INF(...) LOG(1, __VA_ARGS__)
#define DBG(...) LOG(2, __VA_ARGS__)
/** @brief Context per thread. */
struct tcpspammer_thread_ctx
{
int efd; //!< epoll fd containing the other event fds.
int efd_connect; //!< fd for connected sockets.
int efd_extra; //!< event fd for listening connections.
int efd_echo; //!< Event fd for echo request.
int timer; //!< event fd for listening connections.
int cpu; //!< Cpu this thread is running on.
_Atomic uint64_t active_connections; //!< Connections started.
_Atomic uint64_t established_connections; //!< Connections handshaked.
pthread_t thread;
pthread_attr_t attr;
struct tcpspammer_ctx *main_ctx;
};
/** @brief Main context */
struct tcpspammer_ctx
{
unsigned long n_threads; //!< Number of threads created.
int signalfd; //!< Main thread signal fd.
int eventfd; //!< Eventfd for signaling program exit.
int efd; //!< Main thread epoll fd.
int timerfd; //!< timer fd for printing stats.
struct tcpspammer_thread_ctx *threads; //!< All threads.
struct sockaddr_storage *sources; //!< Array of source addresses.
struct sockaddr_storage *destinations; //!< Array of destination addresses
struct timespec echo_timer; //!< If echo set, timer for echo.
char *echostring; //!< String to echo.
unsigned int n_sources; //!< Number of available sources.
unsigned int n_destinations; //!< Number of destinations.
unsigned int n_connections; //!< Number of connections per thread.
unsigned int n_connections_per_sec; //!< Number of connections per second.
_Atomic unsigned short n_finished; //!< Number of threads finished.
_Atomic uint64_t new_connections; //!< New connections this second.
bool listen; //!< True if process listens rather than connects.
bool disconnect_after_hello; //!< True if connection is closed after reply.
bool explicit_echo; //!< Echo timer explicitly set.
};
__thread char ipstr_src[INET6_ADDRSTRLEN];
__thread char ipstr_dst[INET6_ADDRSTRLEN];
__thread char service_str_src[8];
__thread char service_str_dst[8];
static void strings_set(struct sockaddr_storage *saddr, bool dst,
int lvl)
{
if (lvl <= verbosity)
{
int ret = getnameinfo((struct sockaddr *)saddr, sizeof(*saddr),
(dst) ? ipstr_dst : ipstr_src, INET6_ADDRSTRLEN,
(dst) ? service_str_dst : service_str_src, 8,
NI_NUMERICHOST | NI_NUMERICSERV);
if (ret)
{
ERR("Failed to solve address to string: %s", gai_strerror(ret));
}
}
}
__attribute__((constructor)) void init_logpipe(void)
{
if (pipe2(logpipe, O_CLOEXEC | O_NONBLOCK))
{
abort();
}
}
static void safe_close(int *efd)
{
if (*efd != -1)
{
if (close(*efd) == -1 && errno == EBADF)
{
abort();
}
*efd = -1;
}
}
static void safe_close_remove(int *fd, int efd)
{
if (*fd != -1)
{
if (epoll_ctl(efd, EPOLL_CTL_DEL, *fd, NULL))
{
FATAL("Failed to remove %d from %d: %m", *fd, efd);
}
safe_close(fd);
}
}
static void safe_close_decrement(int *fd, int efd,
struct tcpspammer_thread_ctx *ctx,
bool was_active)
{
ctx->active_connections--;
if (was_active)
{
ctx->established_connections--;
if (ctx->efd_echo != -1)
{
if (efd != ctx->efd_echo &&
epoll_ctl(ctx->efd_echo, EPOLL_CTL_DEL, *fd, NULL))
{
ERR("Failed to remove %d from echo efd %d: %m", *fd,
ctx->efd_echo);
}
}
}
safe_close_remove(fd, efd);
}
static int read_timer(int fd)
{
uint64_t val;
if (read(fd, &val, sizeof(val)) > 0)
{
return val;
}
else
{
ERR("Failed to read timer %d: %m", fd);
}
return -1;
}
static int init_timer(struct timespec tv)
{
int fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
if (fd != -1)
{
struct itimerspec interval = { tv, tv };
if (!timerfd_settime(fd, 0, &interval, NULL))
{
return fd;
}
else
{
FATAL("Failed to set timer %d: %m", fd);
}
safe_close(&fd);
}
else
{
FATAL("Failed to create timerfd: %m");
}
return fd;
}
static int signalfd_init(void)
{
sigset_t sigs;
sigemptyset(&sigs);
sigaddset(&sigs, SIGINT);
sigaddset(&sigs, SIGTERM);
sigaddset(&sigs, SIGPIPE);
if (!sigprocmask(SIG_BLOCK, &sigs, NULL))
{
int sfd = signalfd(-1, &sigs, SFD_CLOEXEC | SFD_NONBLOCK);
if (sfd != -1)
{
return sfd;
}
else
{
ERR("Failed to create signalfd: %m");
}
}
else
{
ERR("Failed to block sigs: %m");
}
return -1;
}
static bool max_nofile_soft(void)
{
struct rlimit limits = {};
if (!getrlimit(RLIMIT_NOFILE, &limits))
{
INF("Increasing soft limit from %lu to %lu", limits.rlim_cur,
limits.rlim_max);
limits.rlim_cur = limits.rlim_max;
if (!setrlimit(RLIMIT_NOFILE, &limits))
{
return true;
}
else
{
FATAL("Failed to increase soft limit to %lu: %m", limits.rlim_cur);
}
}
else
{
FATAL("Failed to get soft limits: %m");
}
return false;
}
static bool max_nofile(void)
{
unsigned long maxes[] = {UINT_MAX, UINT_MAX};
char *files[] = {"/proc/sys/fs/file-max", "/proc/sys/fs/nr_open"};
unsigned int i;
struct rlimit limits = {};
for (i = 0; i < 2; i++)
{
FILE *fp = fopen(files[i], "r");
if (fp)
{
char buf[BUFSIZ];
size_t n_read;
n_read = fread(buf, 1, sizeof(buf), fp);
if (n_read > 0 && n_read < sizeof(buf))
{
buf[n_read] = '\0';
maxes[i] = atoll(buf);
INF("Read %s to have value %lu", files[i], maxes[i]);
}
else
{
FATAL("Failed to read %s: %m", files[i]);
}
fclose(fp);
}
else
{
FATAL("Failed to open %s: %m", files[i]);
}
}
limits.rlim_cur = limits.rlim_max =
((maxes[0] < maxes[1]) ? maxes[0] : maxes[1]);
if (!setrlimit(RLIMIT_NOFILE, &limits))
{
return true;
}
else
{
FATAL("Failed to increase hard limit to %lu: %m", limits.rlim_cur);
}
return false;
}
static bool resolve_to_storage(struct sockaddr_storage *saddr,
const char *node, const char *service,
bool local)
{
if (!node && !service)
{
saddr->ss_family = AF_INET6;
// Initialized to 0 is okay.
return true;
}
int err;
struct addrinfo hints = {.ai_socktype = SOCK_STREAM,
.ai_flags = AI_NUMERICSERV | AI_ADDRCONFIG},
*res;
if (local)
{
hints.ai_flags |= AI_PASSIVE;
}
err = getaddrinfo(node, service, &hints, &res);
if (!err)
{
memcpy(saddr, res->ai_addr, res->ai_addrlen);
freeaddrinfo(res);
return true;
}
else
{
ERR("Failed to get addrinfo for %s:%s: %s", node, service,
gai_strerror(err));
}
return false;
}
static unsigned int address_to_range(const char *str,
struct sockaddr_storage **store,
const char *service, bool source)
{
unsigned int ret = 0;
char *limiter;
if (str && (limiter = strchr(str, '-')))
{
char start[INET6_ADDRSTRLEN] = { }, end[INET6_ADDRSTRLEN] = { };
struct sockaddr_storage store_start, store_end;
// Yeah yeah no null termination goes bad.
strncpy(start, str, limiter - str);
strncpy(end, limiter + 1, sizeof(end) - 1);
INF("Using %s from %s to %s", (source) ? "sources" : "destinations",
start, end);
if (resolve_to_storage(&store_start, start, service, source) &&
resolve_to_storage(&store_end, end, service, source))
{
uint32_t *start_addr, *end_addr;
if (store_start.ss_family == AF_INET)
{
start_addr =
&(((struct sockaddr_in *)&store_start)->sin_addr.s_addr),
end_addr =
&(((struct sockaddr_in *)&store_end)->sin_addr.s_addr);
}
else
{
start_addr = &(((struct sockaddr_in6 *)&store_start)
->sin6_addr.__in6_u.__u6_addr32[3]),
end_addr = &(((struct sockaddr_in6 *)&store_end)
->sin6_addr.__in6_u.__u6_addr32[3]);
}
while (ntohl(*start_addr) + ret <= ntohl(*end_addr))
{
ret++;
}
INF("Found %u addresses between %s and %s", ret, start, end);
*store = calloc(ret, sizeof(**store));
if (*store)
{
unsigned int i;
for (i = 0; i < ret; i++)
{
struct sockaddr_storage *target = (*store) + i;
uint32_t last_val = htonl(ntohl(*start_addr) + i);
memcpy(target, &store_start, sizeof(**store));
if (store_start.ss_family == AF_INET6)
{
((struct sockaddr_in6 *)target)
->sin6_addr.__in6_u.__u6_addr32[3] = last_val;
}
else
{
((struct sockaddr_in *)target)->sin_addr.s_addr =
last_val;
}
strings_set(target, false, 2);
DBG("Adding %s:%s as source", ipstr_src, service_str_dst);
}
}
else
{
ERR("Failed to allocate %lu bytes for storage: %m",
ret * sizeof(**store));
ret = 0;
}
}
}
else
{
*store = calloc(1, sizeof(**store));
if (*store)
{
if (resolve_to_storage(*store, str, service, source))
{
ret = 1;
}
}
else
{
ERR("Failed to allocate storage: %m");
}
}
return ret;
}
static void do_exit(struct tcpspammer_ctx *ctx)
{
uint64_t val = ctx->n_threads + 1;
ERR("Exit called");
if (write(ctx->eventfd, &val, sizeof(val)) != sizeof(val))
{
abort();
}
}
static bool register_thread_fds(struct tcpspammer_thread_ctx *ctx)
{
unsigned int i;
struct epoll_event evs[] = {
{.events = EPOLLIN, .data.fd = ctx->efd_connect},
{.events = EPOLLIN | EPOLLONESHOT, .data.fd = ctx->main_ctx->eventfd},
{.events = EPOLLIN, .data.fd = ctx->efd_extra},
{.events = EPOLLIN, .data.fd = ctx->timer},
};
const unsigned int n_events = sizeof(evs) / sizeof(*evs);
for (i = 0; i < n_events; i++)
{
if (!epoll_ctl(ctx->efd, EPOLL_CTL_ADD, evs[i].data.fd, &evs[i]))
{
DBG("Registered %d to main efd %d", evs[i].data.fd, ctx->efd);
}
else
{
FATAL("Failed to register %d to %d in thread %m", evs[i].data.fd,
ctx->efd);
break;
}
}
return (i == n_events);
}
static bool so_timeout(int fd)
{
int yes = 1;
if (!keepidle_value)
{
return true;
}
if (!setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes)))
{
int keepcount = 2, idle = keepidle_value, between = keepidle_value;
if (!setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &keepcount, sizeof(int)) &&
!setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(int)) &&
!setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &between, sizeof(int)) &&
!setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(int)) &&
!setsockopt(fd, IPPROTO_TCP, TCP_SYNCNT, &keepcount, sizeof(int)))
{
return true;
}
else
{
FATAL("Failed to set TCP parameters on fd %d: %m", fd);
}
}
else
{
FATAL("Failed to enable keepalive on fd %d: %m", fd);
}
return false;
}
enum available_sockopts
{
SOCKOPT_INCOMING_CPU = 0x1,
SOCKOPT_REUSEADDR = 0x2,
SOCKOPT_REUSEPORT = 0x4,
SOCKOPT_TIMEOUT = 0x8,
};
static bool do_sockopts(int fd, int cpu, enum available_sockopts opts)
{
bool bret = true;
int yes = 1;
static _Atomic uint32_t incoming_cpu_failed = 0;
if (!incoming_cpu_failed && opts & SOCKOPT_INCOMING_CPU &&
setsockopt(fd, SOL_SOCKET, SO_INCOMING_CPU, &cpu, sizeof(cpu)))
{
FATAL("Failed to balance %d to cpu %d: %m", fd, cpu);
incoming_cpu_failed = 1;
// Don't fail fully, just warn once. User might just have old kernel.
}
if (opts & SOCKOPT_REUSEADDR &&
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)))
{
FATAL("Failed to reuseaddr on %d: %m", fd);
bret = false;
}
if (opts & SOCKOPT_REUSEPORT &&
setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes)))
{
FATAL("Failed to set port reuse on fd %d: %m", fd);
bret = false;
}
if (opts & SOCKOPT_TIMEOUT && !so_timeout(fd))
{
bret = false;
}
return bret;
}
static bool create_listeners(struct tcpspammer_thread_ctx *ctx)
{
unsigned int i, bases_covered = 0;
for (i = 0; i < ctx->main_ctx->n_connections; i++)
{
int fd;
struct sockaddr_storage *saddr = ctx->main_ctx->sources;
if (ctx->main_ctx->n_sources > 0)
{
// Cover all the given listening addresses if possible.
saddr += (bases_covered++ * ctx->main_ctx->n_threads + ctx->cpu) %
ctx->main_ctx->n_sources;
}
fd =
socket(saddr->ss_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (fd != -1)
{
if (do_sockopts(
fd, ctx->cpu,
SOCKOPT_INCOMING_CPU | SOCKOPT_REUSEADDR | SOCKOPT_REUSEPORT))
{
if (!bind(fd, (struct sockaddr *)saddr, sizeof(*saddr)))
{
if (!listen(fd, 128))
{
struct epoll_event ev = {.data.fd = fd,
.events = EPOLLIN};
if (!epoll_ctl(ctx->efd_extra, EPOLL_CTL_ADD, ev.data.fd,
&ev))
{
strings_set(saddr, false, 1);
INF("Listening on %s:%s", ipstr_src, service_str_src);
continue;
}
else
{
FATAL("Failed to add %d to %d: %m", fd,
ctx->efd_extra);
}
}
else
{
ERR("Failed to listen on fd %d: %m", fd);
}
}
else
{
strings_set(saddr, false, 0);
ERR("Failed to bind to %s:%s: %m", ipstr_src, service_str_src);
}
}
safe_close(&fd);
}
else
{
ERR("Failed to create socket: %m");
}
break;
}
return (i == ctx->main_ctx->n_connections);
}
static bool thread_connect(struct tcpspammer_thread_ctx *ctx)
{
struct sockaddr_storage *src = (ctx->main_ctx->sources +
(rand() % ctx->main_ctx->n_sources)),
*dst = (ctx->main_ctx->destinations +
(rand() % ctx->main_ctx->n_destinations));
int fd = socket(src->ss_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
if (fd != -1)
{
if (do_sockopts(
fd, ctx->cpu,
SOCKOPT_INCOMING_CPU | SOCKOPT_REUSEADDR | SOCKOPT_TIMEOUT))
{
if (!bind(fd, (struct sockaddr *)src, sizeof(*src)))
{
int ret = connect(fd, (struct sockaddr *)dst, sizeof(*dst));
if (!ret || errno == EINPROGRESS)
{
struct epoll_event ev = {.data.fd = fd, .events = EPOLLIN};
int efd = (!ret) ? ctx->efd_connect : ctx->efd_extra;
if (ret == -1)
{
ev.events |= EPOLLOUT;
}
if (!epoll_ctl(efd, EPOLL_CTL_ADD, fd, &ev))
{
ctx->active_connections++;
if (!ret)
{
ctx->established_connections++;
ctx->main_ctx->new_connections++;
}
strings_set(src, false, 2);
strings_set(dst, true, 2);
DBG("Connect%s from %s:%s to %s:%s", (ret) ? "ing" : "ed",
ipstr_src, service_str_dst, ipstr_dst,
service_str_dst);
return true;
}
else
{
FATAL("Failed to add just connected %d to %d: %m", fd,
efd);
}
}
else
{
strings_set(src, false, 0);
ERR("Failed to connect %s:%s : %m", ipstr_src,
service_str_dst);
}
}
else
{
strings_set(src, false, 0);
ERR("Failed to bind to %s:%s: %m", ipstr_src, service_str_src);
}
}
safe_close(&fd);
}
else
{
ERR("Failed to get fd: %m");
}
return false;
}
static int epoll_handler(int efd,
bool (*handler)(void *,
struct epoll_event *ev),
void *ctx,
int timeout)
{
int ret = 0;
const unsigned int max_events = 128;
struct epoll_event ev[max_events];
ret = epoll_wait(efd, ev, max_events, timeout);
if (ret >= 0)
{
const unsigned int n_events = ret;
unsigned int i;
for (i = 0; i < (unsigned int)n_events && ret != -1; i++)
{
if (!handler(ctx, &ev[i]))
{
ret = -1;
}
else
{
ret++;
}
}
}
else if (errno == EINTR)
{
ret = 0;
}
else
{
ERR("Failed to wait on fd %d: %m", efd);
ret = -1;
}
return ret;
}
static bool thread_connections(void *ctx_ptr,
struct epoll_event *ev)
{
struct tcpspammer_thread_ctx *ctx = ctx_ptr;
char buf[BUFSIZ];
ssize_t ret;
int fd = ev->data.fd;
ret = read(fd, buf, sizeof(buf));
if (ret > 0)
{
DBG("Read %zu bytes from peer", ret);
if (ctx->main_ctx->listen)
{
// Echo back.
if (write(fd, buf, ret) != ret)
{
INF("Failed to reply with %zu data", ret);
safe_close_decrement(&fd, ctx->efd_connect, ctx, true);
}
}
else
{
if (ctx->main_ctx->disconnect_after_hello)
{
INF("Disconnecting after received reply");
safe_close_decrement(&fd, ctx->efd_connect, ctx, true);
}
else if (ctx->main_ctx->explicit_echo)
{
struct epoll_event ev_echo = {.data.fd = fd,
.events = EPOLLOUT | EPOLLONESHOT};
if (epoll_ctl(ctx->efd_echo, EPOLL_CTL_MOD, fd, &ev_echo))
{
ERR("Failed to add %d back to echo list: %m", fd);
safe_close_decrement(&fd, ctx->efd_connect, ctx, true);
}
}
}
}
else
{
if (!(ret == -1 &&
(errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR)))
{
INF("Peer %s: %m", (!ret) ? "disconnected" : "error");
safe_close_decrement(&fd, ctx->efd_connect, ctx, true);
}
}
return true;
}
static bool handle_listening(void *ctx_ptr,
struct epoll_event *ev)
{
struct tcpspammer_thread_ctx *ctx = ctx_ptr;
int fd = ev->data.fd, accepted_fd;
struct sockaddr_storage peer;
socklen_t peer_len = sizeof(peer);
while ((accepted_fd = accept4(fd, (struct sockaddr *)&peer, &peer_len,
SOCK_NONBLOCK | SOCK_CLOEXEC)) >= 0)
{
struct epoll_event ev_new =
{
.data.fd = accepted_fd, .events = EPOLLIN
};
strings_set(&peer, true, 1);
INF("Accepted connection from %s", ipstr_dst);
if (do_sockopts(accepted_fd, ctx->cpu,
SOCKOPT_INCOMING_CPU | SOCKOPT_TIMEOUT))
{
if (!epoll_ctl(ctx->efd_connect, EPOLL_CTL_ADD, accepted_fd, &ev_new))
{
ctx->active_connections++;
ctx->established_connections++;
ctx->main_ctx->new_connections++;
continue;
}
else
{
FATAL("Failed to add fd %d to %d: %m", accepted_fd,
ctx->efd_connect);
}
}
safe_close(&accepted_fd);
}
if (!(accepted_fd == -1 &&
(errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)))
{
if (errno == EMFILE || errno == ENFILE || errno == ECONNABORTED)
{
INF("Non-fatal error on fd %d: %m", fd);
}
else
{
ERR("Failed to accept on fd %d: %m", fd);
return false;
}
}
return true;
}
static bool send_hello(void *ctx_ptr, struct epoll_event *ev)
{
struct tcpspammer_thread_ctx *ctx = ctx_ptr;
ssize_t ret;
int fd = ev->data.fd;
ret = write(fd, ctx->main_ctx->echostring, strlen(ctx->main_ctx->echostring));
if (ret <= 0)
{
ERR("Failed to write to %d: %s", fd, (!ret) ? "Disconnected" :
strerror(errno));
safe_close_decrement(
&fd, (ctx->main_ctx->explicit_echo) ? ctx->efd_echo : ctx->efd_connect,
ctx, true);
}
return true;
}
static bool handle_einprogress(void *ctx_ptr,
struct epoll_event *ev)
{
struct tcpspammer_thread_ctx *ctx = ctx_ptr;
int fd = ev->data.fd, err = 0;
socklen_t err_len = sizeof(err);
if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &err_len))
{
struct sockaddr_storage dst;
socklen_t dst_len = sizeof(dst);
if (!err)
{
if (!getpeername(fd, (struct sockaddr *)&dst, &dst_len))
{
if (!connect(fd, (struct sockaddr *)&dst, dst_len))
{
if (!epoll_ctl(ctx->efd_extra, EPOLL_CTL_DEL, fd, NULL))
{
struct epoll_event ev_new = {.data.fd = fd,
.events = EPOLLIN};
if (!epoll_ctl(ctx->efd_connect, EPOLL_CTL_ADD, fd,
&ev_new))
{
struct epoll_event ev_echo = {
.data.fd = fd, .events = EPOLLOUT | EPOLLONESHOT};
if (!ctx->main_ctx->echostring ||
ctx->main_ctx->disconnect_after_hello ||
!epoll_ctl(ctx->efd_echo, EPOLL_CTL_ADD, fd,
&ev_echo))
{
if (verbosity)
{
strings_set(&dst, true, verbosity);
INF("Connected to %s:%s", ipstr_dst,
service_str_dst);
}
ctx->established_connections++;
ctx->main_ctx->new_connections++;
if (ctx->main_ctx->echostring &&
ctx->main_ctx->disconnect_after_hello)
{
send_hello(ctx_ptr, &ev_echo);
}
return true;
}
else
{
ERR("Failed to register fd %d to efd %d: %m", fd,
ctx->efd_echo);
}
}
else
{
FATAL("Failed to add %d to efd %d: %m", fd,
ctx->efd_connect);
}
}
else
{
FATAL("Failed to remove %d from efd %d: %m", fd,
ctx->efd_extra);
}
}
else if (errno == EINPROGRESS)
{
DBG("Connection on fd %d: %m", fd);
return true;
}
else
{
ERR("Failed to continue connect on fd %d: %m", fd);
}
}
else
{
ERR("Failed to get peer address on fd %d: %m", fd);
}
}
else
{
if (verbosity > 0)
{
ERR("Failed to connect: %s", strerror(err));
if (!getpeername(fd, (struct sockaddr *)&dst, &dst_len))
{
strings_set(&dst, true, 0);
ERR("Endpoint was %s:%s", ipstr_dst, service_str_dst);
}
else
{
ERR("Couldn't get it: %m");
}
}
}
}
else
{
ERR("Failed to get SO_ERROR for %d: %m", fd);
}
safe_close_decrement(&fd, ctx->efd_extra, ctx, false);
return true;
}
static bool should_exit(int eventfd)
{
uint64_t data;
ssize_t ret = read(eventfd, &data, sizeof(data));
if (ret == sizeof(data))
{
INF("Registered exit call from eventfd");
return true;
}
else
{
ERR("Failed to read eventfd %d: %s", eventfd,
(!ret) ? "closed" : strerror(errno));
}
return false;
}
static bool handle_thread_main_efd(void *ctx_ptr,
struct epoll_event *ev)
{
struct tcpspammer_thread_ctx *ctx = ctx_ptr;