geoip: Use correct line endings in HTTP request
[netsniff-ng.git] / trafgen.c
blobba2393c31421666958e82d89e3c70e51399a5ac0
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2011 - 2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,
4 * Swiss federal institute of technology (ETH Zurich)
5 * Subject to the GPL, version 2.
6 */
8 #include <stdio.h>
9 #include <string.h>
10 #include <getopt.h>
11 #include <ctype.h>
12 #include <stdbool.h>
13 #include <sched.h>
14 #include <sys/socket.h>
15 #include <sys/types.h>
16 #include <sys/fsuid.h>
17 #include <sys/prctl.h>
18 #include <sys/stat.h>
19 #include <sys/time.h>
20 #include <sys/wait.h>
21 #include <sys/mman.h>
22 #include <net/ethernet.h>
23 #include <netinet/in.h>
24 #include <netinet/ip.h>
25 #include <linux/icmp.h>
26 #include <linux/if.h>
27 #include <arpa/inet.h>
28 #include <signal.h>
29 #include <stdint.h>
30 #include <stdlib.h>
31 #include <fcntl.h>
32 #include <time.h>
33 #include <poll.h>
34 #include <netdb.h>
35 #include <math.h>
36 #include <unistd.h>
38 #include "xmalloc.h"
39 #include "die.h"
40 #include "str.h"
41 #include "sig.h"
42 #include "sock.h"
43 #include "cpus.h"
44 #include "lockme.h"
45 #include "privs.h"
46 #include "proc.h"
47 #include "mac80211.h"
48 #include "ioops.h"
49 #include "irq.h"
50 #include "config.h"
51 #include "built_in.h"
52 #include "trafgen_conf.h"
53 #include "tprintf.h"
54 #include "timer.h"
55 #include "ring_tx.h"
56 #include "csum.h"
58 struct ctx {
59 bool rand, rfraw, jumbo_support, verbose, smoke_test, enforce, qdisc_path;
60 size_t reserve_size;
61 unsigned long num;
62 unsigned int cpus;
63 uid_t uid; gid_t gid;
64 char *device, *device_trans, *rhost;
65 struct timespec gap;
66 struct sockaddr_in dest;
67 char *packet_str;
70 struct cpu_stats {
71 unsigned long tv_sec, tv_usec;
72 unsigned long long tx_packets, tx_bytes;
73 unsigned long long cf_packets, cf_bytes;
74 unsigned long long cd_packets;
75 sig_atomic_t state;
78 static sig_atomic_t sigint = 0;
80 struct packet *packets = NULL;
81 size_t plen = 0;
83 struct packet_dyn *packet_dyn = NULL;
84 size_t dlen = 0;
86 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:CHQq";
87 static const struct option long_options[] = {
88 {"dev", required_argument, NULL, 'd'},
89 {"out", required_argument, NULL, 'o'},
90 {"in", required_argument, NULL, 'i'},
91 {"conf", required_argument, NULL, 'c'},
92 {"num", required_argument, NULL, 'n'},
93 {"gap", required_argument, NULL, 't'},
94 {"cpus", required_argument, NULL, 'P'},
95 {"ring-size", required_argument, NULL, 'S'},
96 {"kernel-pull", required_argument, NULL, 'k'},
97 {"smoke-test", required_argument, NULL, 's'},
98 {"seed", required_argument, NULL, 'E'},
99 {"user", required_argument, NULL, 'u'},
100 {"group", required_argument, NULL, 'g'},
101 {"prio-high", no_argument, NULL, 'H'},
102 {"notouch-irq", no_argument, NULL, 'Q'},
103 {"no-sock-mem", no_argument, NULL, 'A'},
104 {"qdisc-path", no_argument, NULL, 'q'},
105 {"jumbo-support", no_argument, NULL, 'J'},
106 {"no-cpu-stats", no_argument, NULL, 'C'},
107 {"cpp", no_argument, NULL, 'p'},
108 {"rfraw", no_argument, NULL, 'R'},
109 {"rand", no_argument, NULL, 'r'},
110 {"verbose", no_argument, NULL, 'V'},
111 {"version", no_argument, NULL, 'v'},
112 {"example", no_argument, NULL, 'e'},
113 {"help", no_argument, NULL, 'h'},
114 {NULL, 0, NULL, 0}
117 static const char *copyright = "Please report bugs to <netsniff-ng@googlegroups.com>\n"
118 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
119 "Swiss federal institute of technology (ETH Zurich)\n"
120 "License: GNU GPL version 2.0\n"
121 "This is free software: you are free to change and redistribute it.\n"
122 "There is NO WARRANTY, to the extent permitted by law.";
124 static int sock;
125 static struct cpu_stats *stats;
126 static unsigned int seed;
128 #define CPU_STATS_STATE_CFG 1
129 #define CPU_STATS_STATE_CHK 2
130 #define CPU_STATS_STATE_RES 4
132 #ifndef ICMP_FILTER
133 # define ICMP_FILTER 1
135 struct icmp_filter {
136 __u32 data;
138 #endif
140 #define SMOKE_N_PROBES 100
142 #define PKT_MIN_LEN 14
144 static void signal_handler(int number)
146 switch (number) {
147 case SIGINT:
148 case SIGQUIT:
149 case SIGTERM:
150 sigint = 1;
151 case SIGHUP:
152 default:
153 break;
157 static void __noreturn help(void)
159 printf("trafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
160 puts("http://www.netsniff-ng.org\n\n"
161 "Usage: trafgen [options] [packet]\n"
162 "Options:\n"
163 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
164 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
165 " -p|--cpp Run packet config through C preprocessor\n"
166 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
167 " -R|--rfraw Inject raw 802.11 frames\n"
168 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
169 " -n|--num <uint> Number of packets until exit (def: 0)\n"
170 " -r|--rand Randomize packet selection (def: round robin)\n"
171 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
172 " -t|--gap <time> Set approx. interpacket gap (s/ms/us/ns, def: us)\n"
173 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
174 " -E|--seed <uint> Manually set srand(3) seed\n"
175 " -u|--user <userid> Drop privileges and change to userid\n"
176 " -g|--group <groupid> Drop privileges and change to groupid\n"
177 " -H|--prio-high Make this high priority process\n"
178 " -A|--no-sock-mem Don't tune core socket memory\n"
179 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
180 " -q|--qdisc-path Enabled qdisc kernel path (default off since 3.14)\n"
181 " -V|--verbose Be more verbose\n"
182 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
183 " -v|--version Show version and exit\n"
184 " -e|--example Show built-in packet config example\n"
185 " -h|--help Guess what?!\n\n"
186 "Examples:\n"
187 " trafgen --dev eth0 --conf trafgen.cfg\n"
188 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
189 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
190 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
191 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000us\n"
192 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
193 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n"
194 " trafgen --dev eth0 '{ fill(0xff, 6), 0x00, 0x02, 0xb3, rnd(3), c16(0x0800), fill(0xca, 64) }'\n\n"
195 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
196 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
197 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
198 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
199 "Generate config files from existing pcap using netsniff-ng:\n"
200 " netsniff-ng --in dump.pcap --out dump.cfg\n\n"
201 "Note:\n"
202 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
203 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
204 " we assume the kernel crashed, thus we print the packet and quit.\n"
205 " In case you find a ping-of-death, please mention trafgen in your\n"
206 " commit message of the fix!\n\n"
207 " For introducing bit errors, delays with random variation and more,\n"
208 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
209 " For generating different package distributions, you can use scripting\n"
210 " to generate a trafgen config file with packet ratios as:\n\n"
211 " IMIX 64:7, 570:4, 1518:1\n"
212 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
213 " Cisco 64:7, 594:4, 1518:1\n"
214 " RPR Trimodal 64:60, 512:20, 1518:20\n"
215 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n");
216 puts(copyright);
217 die();
220 static void __noreturn example(void)
222 const char *e =
223 "/* Note: dynamic elements make trafgen slower! */\n"
224 "#include <stddef.h>\n\n"
225 "{\n"
226 " /* MAC Destination */\n"
227 " fill(0xff, ETH_ALEN),\n"
228 " /* MAC Source */\n"
229 " 0x00, 0x02, 0xb3, drnd(3),\n"
230 " /* IPv4 Protocol */\n"
231 " c16(ETH_P_IP),\n"
232 " /* IPv4 Version, IHL, TOS */\n"
233 " 0b01000101, 0,\n"
234 " /* IPv4 Total Len */\n"
235 " c16(59),\n"
236 " /* IPv4 Ident */\n"
237 " drnd(2),\n"
238 " /* IPv4 Flags, Frag Off */\n"
239 " 0b01000000, 0,\n"
240 " /* IPv4 TTL */\n"
241 " 64,\n"
242 " /* Proto TCP */\n"
243 " 0x06,\n"
244 " /* IPv4 Checksum (IP header from, to) */\n"
245 " csumip(14, 33),\n"
246 " /* Source IP */\n"
247 " drnd(4),\n"
248 " /* Dest IP */\n"
249 " drnd(4),\n"
250 " /* TCP Source Port */\n"
251 " drnd(2),\n"
252 " /* TCP Dest Port */\n"
253 " c16(80),\n"
254 " /* TCP Sequence Number */\n"
255 " drnd(4),\n"
256 " /* TCP Ackn. Number */\n"
257 " c32(0),\n"
258 " /* TCP Header length + TCP SYN/ECN Flag */\n"
259 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
260 " /* Window Size */\n"
261 " c16(16),\n"
262 " /* TCP Checksum (offset IP, offset TCP) */\n"
263 " csumtcp(14, 34),\n"
264 " /* TCP Options */\n"
265 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
266 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
267 " /* Data blob */\n"
268 " \"gotcha!\",\n"
269 "}";
270 puts(e);
271 die();
274 static void __noreturn version(void)
276 printf("trafgen %s, Git id: %s\n", VERSION_LONG, GITVERSION);
277 puts("multithreaded zero-copy network packet generator\n"
278 "http://www.netsniff-ng.org\n");
279 puts(copyright);
280 die();
283 static void apply_counter(int id)
285 size_t j, counter_max = packet_dyn[id].clen;
287 for (j = 0; j < counter_max; ++j) {
288 uint8_t val;
289 struct counter *counter = &packet_dyn[id].cnt[j];
291 val = counter->val - counter->min;
293 switch (counter->type) {
294 case TYPE_INC:
295 val = (val + counter->inc) % (counter->max - counter->min + 1);
296 break;
297 case TYPE_DEC:
298 val = (val - counter->inc) % (counter->min - counter->max + 1);
299 break;
300 default:
301 bug();
304 counter->val = val + counter->min;
305 packets[id].payload[counter->off] = val;
309 static void apply_randomizer(int id)
311 size_t j, rand_max = packet_dyn[id].rlen;
313 for (j = 0; j < rand_max; ++j) {
314 uint8_t val = (uint8_t) rand();
315 struct randomizer *randomizer = &packet_dyn[id].rnd[j];
317 packets[id].payload[randomizer->off] = val;
321 static void apply_csum16(int id)
323 size_t j, csum_max = packet_dyn[id].slen;
325 for (j = 0; j < csum_max; ++j) {
326 uint16_t sum = 0;
327 struct csum16 *csum = &packet_dyn[id].csum[j];
329 fmemset(&packets[id].payload[csum->off], 0, sizeof(sum));
330 if (unlikely((size_t) csum->to >= packets[id].len))
331 csum->to = packets[id].len - 1;
333 switch (csum->which) {
334 case CSUM_IP:
335 sum = calc_csum(packets[id].payload + csum->from,
336 csum->to - csum->from + 1);
337 break;
338 case CSUM_UDP:
339 sum = p4_csum((void *) packets[id].payload + csum->from,
340 packets[id].payload + csum->to,
341 (packets[id].len - csum->to),
342 IPPROTO_UDP);
343 break;
344 case CSUM_TCP:
345 sum = p4_csum((void *) packets[id].payload + csum->from,
346 packets[id].payload + csum->to,
347 (packets[id].len - csum->to),
348 IPPROTO_TCP);
349 break;
350 case CSUM_UDP6:
351 sum = p6_csum((void *) packets[id].payload + csum->from,
352 packets[id].payload + csum->to,
353 (packets[id].len - csum->to),
354 IPPROTO_UDP);
355 break;
356 case CSUM_TCP6:
357 sum = p6_csum((void *) packets[id].payload + csum->from,
358 packets[id].payload + csum->to,
359 (packets[id].len - csum->to),
360 IPPROTO_TCP);
361 break;
362 default:
363 bug();
364 break;
367 fmemcpy(&packets[id].payload[csum->off], &sum, sizeof(sum));
371 static void preprocess_packets(void)
373 size_t i;
375 for (i = 0; i < plen; i++) {
376 struct packet_dyn *pktd = &packet_dyn[i];
378 if (packet_dyn_has_only_csums(pktd)) {
379 apply_csum16(i);
380 pktd->slen = 0;
381 xfree(pktd->csum);
386 static struct cpu_stats *setup_shared_var(unsigned int cpus)
388 int fd;
389 size_t len = cpus * sizeof(struct cpu_stats);
390 char *zbuff, file[256];
391 struct cpu_stats *buff;
393 zbuff = xzmalloc(len);
394 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
396 fd = creat(file, S_IRUSR | S_IWUSR);
397 bug_on(fd < 0);
398 close(fd);
400 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
401 S_IRUSR | S_IWUSR);
402 write_or_die(fd, zbuff, len);
403 xfree(zbuff);
405 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
406 MAP_SHARED, fd, 0);
407 if (buff == MAP_FAILED)
408 panic("Cannot setup shared variable!\n");
410 close(fd);
411 unlink(file);
413 memset(buff, 0, len);
414 return buff;
417 static void destroy_shared_var(void *buff, unsigned int cpus)
419 munmap(buff, cpus * sizeof(struct cpu_stats));
422 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
424 size_t i;
426 printf("{");
427 for (i = 0; i < len; ++i) {
428 if (i % 15 == 0)
429 printf("\n ");
430 printf("0x%02x, ", payload[i]);
432 printf("\n}\n");
433 fflush(stdout);
436 static int xmit_smoke_setup(struct ctx *ctx)
438 int icmp_sock, ret, ttl = 64;
439 struct icmp_filter filter;
441 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
442 if (icmp_sock < 0)
443 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
445 filter.data = ~(1 << ICMP_ECHOREPLY);
447 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
448 if (ret < 0)
449 panic("Cannot install filter!\n");
451 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
452 if (ret < 0)
453 panic("Cannot set TTL!\n");
455 memset(&ctx->dest, 0, sizeof(ctx->dest));
456 ctx->dest.sin_family = AF_INET;
457 ctx->dest.sin_port = 0;
459 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
460 if (ret < 0)
461 panic("Cannot resolve address!\n");
463 return icmp_sock;
466 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
468 int ret;
469 unsigned int i, j;
470 short ident, cnt = 1, idstore[SMOKE_N_PROBES];
471 uint8_t outpack[512], *data;
472 struct icmphdr *icmp;
473 struct iphdr *ip;
474 size_t len = sizeof(*icmp) + 56;
475 struct sockaddr_in from;
476 socklen_t from_len;
477 struct pollfd fds = {
478 .fd = icmp_sock,
479 .events = POLLIN,
482 fmemset(idstore, 0, sizeof(idstore));
483 for (j = 0; j < SMOKE_N_PROBES; j++) {
484 while ((ident = htons((short) rand())) == 0)
485 sleep(0);
486 idstore[j] = ident;
488 memset(outpack, 0, sizeof(outpack));
489 icmp = (void *) outpack;
490 icmp->type = ICMP_ECHO;
491 icmp->un.echo.id = ident;
492 icmp->un.echo.sequence = htons(cnt++);
494 data = ((uint8_t *) outpack + sizeof(*icmp));
495 for (i = 0; i < 56; ++i)
496 data[i] = (uint8_t) rand();
498 icmp->checksum = csum((unsigned short *) outpack,
499 len / sizeof(unsigned short));
501 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
502 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
503 if (unlikely(ret != (int) len))
504 panic("Cannot send out probe: %s!\n", strerror(errno));
506 ret = poll(&fds, 1, 50);
507 if (ret < 0)
508 panic("Poll failed!\n");
510 if (fds.revents & POLLIN) {
511 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
512 (struct sockaddr *) &from, &from_len);
513 if (unlikely(ret <= 0))
514 panic("Probe receive failed!\n");
515 if (unlikely(from_len != sizeof(ctx->dest)))
516 continue;
517 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
518 continue;
519 if (unlikely((size_t) ret < sizeof(*ip) + sizeof(*icmp)))
520 continue;
521 ip = (void *) outpack;
522 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > (size_t) ret))
523 continue;
524 icmp = (void *) outpack + ip->ihl * 4;
525 for (i = 0; i < array_size(idstore); ++i) {
526 if (unlikely(icmp->un.echo.id != idstore[i]))
527 continue;
528 return 0;
533 return -1;
536 static void xmit_slowpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
538 int ret, icmp_sock = -1;
539 unsigned long num = 1, i = 0;
540 struct timeval start, end, diff;
541 unsigned long long tx_bytes = 0, tx_packets = 0;
542 struct packet_dyn *pktd;
543 struct sockaddr_ll saddr = {
544 .sll_family = PF_PACKET,
545 .sll_halen = ETH_ALEN,
546 .sll_ifindex = device_ifindex(ctx->device),
549 if (ctx->num > 0)
550 num = ctx->num;
551 if (ctx->num == 0 && orig_num > 0)
552 num = 0;
554 if (ctx->smoke_test)
555 icmp_sock = xmit_smoke_setup(ctx);
557 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
559 preprocess_packets();
561 bug_on(gettimeofday(&start, NULL));
563 while (likely(sigint == 0 && num > 0 && plen > 0)) {
564 pktd = &packet_dyn[i];
565 if (packet_dyn_has_elems(pktd)) {
566 apply_counter(i);
567 apply_randomizer(i);
568 apply_csum16(i);
570 retry:
571 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
572 (struct sockaddr *) &saddr, sizeof(saddr));
573 if (unlikely(ret < 0)) {
574 if (errno == ENOBUFS) {
575 sched_yield();
576 goto retry;
578 if (ctx->smoke_test)
579 panic("Sendto error: %s!\n", strerror(errno));
582 tx_bytes += packets[i].len;
583 tx_packets++;
585 if (ctx->smoke_test) {
586 ret = xmit_smoke_probe(icmp_sock, ctx);
587 if (unlikely(ret < 0)) {
588 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
589 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
590 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
591 i, seed);
593 dump_trafgen_snippet(packets[i].payload, packets[i].len);
594 break;
598 if (!ctx->rand) {
599 i++;
600 if (i >= plen)
601 i = 0;
602 } else
603 i = rand() % plen;
605 if (ctx->num > 0)
606 num--;
608 if ((ctx->gap.tv_sec | ctx->gap.tv_nsec) > 0)
609 nanosleep(&ctx->gap, NULL);
612 bug_on(gettimeofday(&end, NULL));
613 timersub(&end, &start, &diff);
615 if (ctx->smoke_test)
616 close(icmp_sock);
618 stats[cpu].tx_packets = tx_packets;
619 stats[cpu].tx_bytes = tx_bytes;
620 stats[cpu].tv_sec = diff.tv_sec;
621 stats[cpu].tv_usec = diff.tv_usec;
623 stats[cpu].state |= CPU_STATS_STATE_RES;
626 static void xmit_fastpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
628 int ifindex = device_ifindex(ctx->device);
629 uint8_t *out = NULL;
630 unsigned int it = 0;
631 unsigned long num = 1, i = 0;
632 size_t size = ring_size(ctx->device, ctx->reserve_size);
633 struct ring tx_ring;
634 struct frame_map *hdr;
635 struct timeval start, end, diff;
636 struct packet_dyn *pktd;
637 unsigned long long tx_bytes = 0, tx_packets = 0;
639 set_sock_prio(sock, 512);
641 ring_tx_setup(&tx_ring, sock, size, ifindex, ctx->jumbo_support, ctx->verbose);
643 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
645 if (ctx->num > 0)
646 num = ctx->num;
647 if (ctx->num == 0 && orig_num > 0)
648 num = 0;
650 preprocess_packets();
652 bug_on(gettimeofday(&start, NULL));
654 while (likely(sigint == 0 && num > 0 && plen > 0)) {
655 if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
656 int ret = pull_and_flush_tx_ring(sock);
657 if (unlikely(ret < 0)) {
658 /* We could hit EBADF if the socket has been closed before
659 * the timer was triggered.
661 if (errno != EBADF && errno != ENOBUFS)
662 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
665 continue;
668 hdr = tx_ring.frames[it].iov_base;
669 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
671 hdr->tp_h.tp_snaplen = packets[i].len;
672 hdr->tp_h.tp_len = packets[i].len;
674 pktd = &packet_dyn[i];
675 if (packet_dyn_has_elems(pktd)) {
676 apply_counter(i);
677 apply_randomizer(i);
678 apply_csum16(i);
681 fmemcpy(out, packets[i].payload, packets[i].len);
683 tx_bytes += packets[i].len;
684 tx_packets++;
686 if (!ctx->rand) {
687 i++;
688 if (i >= plen)
689 i = 0;
690 } else
691 i = rand() % plen;
693 kernel_may_pull_from_tx(&hdr->tp_h);
695 it++;
696 if (it >= tx_ring.layout.tp_frame_nr)
697 it = 0;
699 if (ctx->num > 0)
700 num--;
703 bug_on(gettimeofday(&end, NULL));
704 timersub(&end, &start, &diff);
706 pull_and_flush_tx_ring_wait(sock);
707 destroy_tx_ring(sock, &tx_ring);
709 stats[cpu].tx_packets = tx_packets;
710 stats[cpu].tx_bytes = tx_bytes;
711 stats[cpu].tv_sec = diff.tv_sec;
712 stats[cpu].tv_usec = diff.tv_usec;
714 stats[cpu].state |= CPU_STATS_STATE_RES;
717 static inline void __set_state(unsigned int cpu, sig_atomic_t s)
719 stats[cpu].state = s;
722 static inline sig_atomic_t __get_state(unsigned int cpu)
724 return stats[cpu].state;
727 static unsigned long __wait_and_sum_others(struct ctx *ctx, unsigned int cpu)
729 unsigned int i;
730 unsigned long total;
732 for (i = 0, total = plen; i < ctx->cpus; i++) {
733 if (i == cpu)
734 continue;
736 while ((__get_state(i) &
737 (CPU_STATS_STATE_CFG |
738 CPU_STATS_STATE_RES)) == 0 &&
739 sigint == 0)
740 sched_yield();
742 total += stats[i].cf_packets;
745 return total;
748 static void __correct_global_delta(struct ctx *ctx, unsigned int cpu, unsigned long orig)
750 unsigned int i;
751 unsigned long total;
752 int cpu_sel;
753 long long delta_correction = 0;
755 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
756 if (i == cpu)
757 continue;
759 while ((__get_state(i) &
760 (CPU_STATS_STATE_CHK |
761 CPU_STATS_STATE_RES)) == 0 &&
762 sigint == 0)
763 sched_yield();
765 total += stats[i].cd_packets;
768 if (total > orig)
769 delta_correction = -1 * ((long long) total - orig);
770 if (total < orig)
771 delta_correction = +1 * ((long long) orig - total);
773 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
774 if (stats[i].cd_packets > 0) {
775 if ((long long) stats[i].cd_packets +
776 delta_correction >= 0) {
777 cpu_sel = i;
778 break;
783 if ((int) cpu == cpu_sel)
784 ctx->num += delta_correction;
787 static void __set_state_cf(unsigned int cpu, unsigned long p, unsigned long b,
788 sig_atomic_t s)
790 stats[cpu].cf_packets = p;
791 stats[cpu].cf_bytes = b;
792 stats[cpu].state = s;
795 static void __set_state_cd(unsigned int cpu, unsigned long p, sig_atomic_t s)
797 stats[cpu].cd_packets = p;
798 stats[cpu].state = s;
801 static void xmit_packet_precheck(struct ctx *ctx, unsigned int cpu)
803 unsigned long plen_total, orig = ctx->num;
804 size_t total_len = 0;
805 unsigned int i;
807 bug_on(plen != dlen);
809 for (i = 0; i < plen; ++i)
810 total_len += packets[i].len;
812 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
813 plen_total = __wait_and_sum_others(ctx, cpu);
815 if (orig > 0) {
816 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
818 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
819 CPU_STATS_STATE_CFG);
820 __correct_global_delta(ctx, cpu, orig);
823 if (plen == 0) {
824 __set_state(cpu, CPU_STATS_STATE_RES);
825 return;
829 static void main_loop(struct ctx *ctx, char *confname, bool slow,
830 unsigned int cpu, bool invoke_cpp, unsigned long orig_num)
832 if (ctx->packet_str)
833 compile_packets_str(ctx->packet_str, ctx->verbose, cpu);
834 else
835 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
837 xmit_packet_precheck(ctx, cpu);
839 if (cpu == 0) {
840 unsigned int i;
841 size_t total_len = 0, total_pkts = 0;
843 for (i = 0; i < ctx->cpus; ++i) {
844 total_len += stats[i].cf_bytes;
845 total_pkts += stats[i].cf_packets;
848 printf("%6zu packets to schedule\n", total_pkts);
849 printf("%6zu bytes in total\n", total_len);
850 printf("Running! Hang up with ^C!\n\n");
851 fflush(stdout);
854 sock = pf_socket();
856 if (ctx->qdisc_path == false)
857 set_sock_qdisc_bypass(sock, ctx->verbose);
859 if (slow)
860 xmit_slowpath_or_die(ctx, cpu, orig_num);
861 else
862 xmit_fastpath_or_die(ctx, cpu, orig_num);
864 close(sock);
866 cleanup_packets();
869 static unsigned int generate_srand_seed(void)
871 int fd;
872 unsigned int _seed;
874 fd = open("/dev/urandom", O_RDONLY);
875 if (fd < 0)
876 return time(NULL);
878 read_or_die(fd, &_seed, sizeof(_seed));
880 close(fd);
881 return _seed;
884 static void on_panic_del_rfmon(void *arg)
886 leave_rfmon_mac80211(arg);
889 int main(int argc, char **argv)
891 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
892 bool prio_high = false, set_irq_aff = true, set_sock_mem = true;
893 int c, opt_index, vals[4] = {0}, irq;
894 uint64_t gap = 0;
895 unsigned int i, j;
896 char *confname = NULL, *ptr;
897 unsigned long cpus_tmp, orig_num = 0;
898 unsigned long long tx_packets, tx_bytes;
899 struct ctx ctx;
900 int min_opts = 5;
902 fmemset(&ctx, 0, sizeof(ctx));
903 ctx.cpus = get_number_cpus_online();
904 ctx.uid = getuid();
905 ctx.gid = getgid();
906 ctx.qdisc_path = false;
908 /* Keep an initial small default size to reduce cache-misses. */
909 ctx.reserve_size = 512 * (1 << 10);
911 while ((c = getopt_long(argc, argv, short_options, long_options,
912 &opt_index)) != EOF) {
913 switch (c) {
914 case 'h':
915 help();
916 break;
917 case 'v':
918 version();
919 break;
920 case 'C':
921 cpustats = false;
922 break;
923 case 'e':
924 example();
925 break;
926 case 'p':
927 invoke_cpp = true;
928 break;
929 case 'V':
930 ctx.verbose = true;
931 break;
932 case 'P':
933 cpus_tmp = strtoul(optarg, NULL, 0);
934 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
935 ctx.cpus = cpus_tmp;
936 break;
937 case 'd':
938 case 'o':
939 ctx.device = xstrndup(optarg, IFNAMSIZ);
940 break;
941 case 'H':
942 prio_high = true;
943 break;
944 case 'A':
945 set_sock_mem = false;
946 break;
947 case 'Q':
948 set_irq_aff = false;
949 break;
950 case 'q':
951 ctx.qdisc_path = true;
952 break;
953 case 'r':
954 ctx.rand = true;
955 break;
956 case 's':
957 slow = true;
958 ctx.cpus = 1;
959 ctx.smoke_test = true;
960 ctx.rhost = xstrdup(optarg);
961 break;
962 case 'R':
963 ctx.rfraw = true;
964 break;
965 case 'J':
966 ctx.jumbo_support = true;
967 break;
968 case 'c':
969 case 'i':
970 confname = xstrdup(optarg);
971 if (!strncmp("-", confname, strlen("-")))
972 ctx.cpus = 1;
973 break;
974 case 'u':
975 ctx.uid = strtoul(optarg, NULL, 0);
976 ctx.enforce = true;
977 break;
978 case 'g':
979 ctx.gid = strtoul(optarg, NULL, 0);
980 ctx.enforce = true;
981 break;
982 case 'k':
983 printf("Option -k/--kernel-pull is no longer used and "
984 "will be removed in a future release!\n");
985 break;
986 case 'E':
987 seed = strtoul(optarg, NULL, 0);
988 reseed = false;
989 break;
990 case 'n':
991 orig_num = strtoul(optarg, NULL, 0);
992 ctx.num = orig_num;
993 break;
994 case 't':
995 slow = true;
996 ptr = optarg;
997 prctl(PR_SET_TIMERSLACK, 1UL);
998 gap = strtoul(optarg, NULL, 0);
1000 for (j = i = strlen(optarg); i > 0; --i) {
1001 if (!isdigit(optarg[j - i]))
1002 break;
1003 ptr++;
1006 if (!strncmp(ptr, "ns", strlen("ns"))) {
1007 ctx.gap.tv_sec = gap / 1000000000;
1008 ctx.gap.tv_nsec = gap % 1000000000;
1009 } else if (*ptr == '\0' || !strncmp(ptr, "us", strlen("us"))) {
1010 /* Default to microseconds for backwards
1011 * compatibility if no postfix is given.
1013 ctx.gap.tv_sec = gap / 1000000;
1014 ctx.gap.tv_nsec = (gap % 1000000) * 1000;
1015 } else if (!strncmp(ptr, "ms", strlen("ms"))) {
1016 ctx.gap.tv_sec = gap / 1000;
1017 ctx.gap.tv_nsec = (gap % 1000) * 1000000;
1018 } else if (!strncmp(ptr, "s", strlen("s"))) {
1019 ctx.gap.tv_sec = gap;
1020 ctx.gap.tv_nsec = 0;
1021 } else
1022 panic("Syntax error in time param!\n");
1024 if (gap > 0)
1025 /* Fall back to single core to not mess up
1026 * correct timing. We are slow anyway!
1028 ctx.cpus = 1;
1029 break;
1030 case 'S':
1031 ptr = optarg;
1033 for (j = i = strlen(optarg); i > 0; --i) {
1034 if (!isdigit(optarg[j - i]))
1035 break;
1036 ptr++;
1039 if (!strncmp(ptr, "KiB", strlen("KiB")))
1040 ctx.reserve_size = 1 << 10;
1041 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1042 ctx.reserve_size = 1 << 20;
1043 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1044 ctx.reserve_size = 1 << 30;
1045 else
1046 panic("Syntax error in ring size param!\n");
1048 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1049 break;
1050 case '?':
1051 switch (optopt) {
1052 case 'd':
1053 case 'c':
1054 case 'n':
1055 case 'S':
1056 case 's':
1057 case 'P':
1058 case 'o':
1059 case 'E':
1060 case 'i':
1061 case 'k':
1062 case 'u':
1063 case 'g':
1064 case 't':
1065 panic("Option -%c requires an argument!\n",
1066 optopt);
1067 default:
1068 if (isprint(optopt))
1069 printf("Unknown option character `0x%X\'!\n", optopt);
1070 die();
1072 default:
1073 break;
1077 if (argc >= optind) {
1078 min_opts = 4;
1079 ctx.packet_str = argv2str(optind, argc, argv);
1082 if (argc < min_opts)
1083 help();
1084 if (ctx.device == NULL)
1085 panic("No networking device given!\n");
1086 if (confname == NULL && !ctx.packet_str)
1087 panic("No configuration file given!\n");
1088 if (device_mtu(ctx.device) == 0)
1089 panic("This is no networking device!\n");
1091 register_signal(SIGINT, signal_handler);
1092 register_signal(SIGQUIT, signal_handler);
1093 register_signal(SIGTERM, signal_handler);
1094 register_signal(SIGHUP, signal_handler);
1096 if (prio_high) {
1097 set_proc_prio(-20);
1098 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1101 if (set_sock_mem)
1102 set_system_socket_memory(vals, array_size(vals));
1103 xlockme();
1105 if (ctx.rfraw) {
1106 ctx.device_trans = xstrdup(ctx.device);
1107 xfree(ctx.device);
1109 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1110 panic_handler_add(on_panic_del_rfmon, ctx.device);
1111 sleep(0);
1115 * If number of packets is smaller than number of CPUs use only as
1116 * many CPUs as there are packets. Otherwise we end up sending more
1117 * packets than intended or none at all.
1119 if (ctx.num)
1120 ctx.cpus = min_t(unsigned int, ctx.num, ctx.cpus);
1122 irq = device_irq_number(ctx.device);
1123 if (set_irq_aff)
1124 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1126 stats = setup_shared_var(ctx.cpus);
1128 for (i = 0; i < ctx.cpus; i++) {
1129 pid_t pid = fork();
1131 switch (pid) {
1132 case 0:
1133 if (reseed)
1134 seed = generate_srand_seed();
1135 srand(seed);
1137 cpu_affinity(i);
1138 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1140 goto thread_out;
1141 case -1:
1142 panic("Cannot fork processes!\n");
1146 for (i = 0; i < ctx.cpus; i++) {
1147 int status;
1149 wait(&status);
1150 if (WEXITSTATUS(status) == EXIT_FAILURE)
1151 die();
1154 if (ctx.rfraw)
1155 leave_rfmon_mac80211(ctx.device);
1157 if (set_sock_mem)
1158 reset_system_socket_memory(vals, array_size(vals));
1160 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1161 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1162 sched_yield();
1164 tx_packets += stats[i].tx_packets;
1165 tx_bytes += stats[i].tx_bytes;
1168 fflush(stdout);
1169 printf("\n");
1170 printf("\r%12llu packets outgoing\n", tx_packets);
1171 printf("\r%12llu bytes outgoing\n", tx_bytes);
1172 for (i = 0; cpustats && i < ctx.cpus; i++) {
1173 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1174 stats[i].tv_sec, stats[i].tv_usec, i,
1175 stats[i].tx_packets);
1178 thread_out:
1179 xunlockme();
1180 destroy_shared_var(stats, ctx.cpus);
1181 if (set_irq_aff)
1182 device_restore_irq_affinity_list();
1184 free(ctx.device);
1185 free(ctx.device_trans);
1186 free(ctx.rhost);
1187 free(confname);
1188 free(ctx.packet_str);
1190 return 0;