netsniff-ng: nlmsg: Print genl ops & mcast groups attributes
[netsniff-ng.git] / trafgen.c
blobd01f1602c4ea67bdf4c255c89c5cc298a7da8c57
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 bug_on(gettimeofday(&start, NULL));
561 while (likely(sigint == 0 && num > 0 && plen > 0)) {
562 pktd = &packet_dyn[i];
563 if (packet_dyn_has_elems(pktd)) {
564 apply_counter(i);
565 apply_randomizer(i);
566 apply_csum16(i);
568 retry:
569 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
570 (struct sockaddr *) &saddr, sizeof(saddr));
571 if (unlikely(ret < 0)) {
572 if (errno == ENOBUFS) {
573 sched_yield();
574 goto retry;
576 if (ctx->smoke_test)
577 panic("Sendto error: %s!\n", strerror(errno));
580 tx_bytes += packets[i].len;
581 tx_packets++;
583 if (ctx->smoke_test) {
584 ret = xmit_smoke_probe(icmp_sock, ctx);
585 if (unlikely(ret < 0)) {
586 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
587 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
588 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
589 i, seed);
591 dump_trafgen_snippet(packets[i].payload, packets[i].len);
592 break;
596 if (!ctx->rand) {
597 i++;
598 if (i >= plen)
599 i = 0;
600 } else
601 i = rand() % plen;
603 if (ctx->num > 0)
604 num--;
606 if ((ctx->gap.tv_sec | ctx->gap.tv_nsec) > 0)
607 nanosleep(&ctx->gap, NULL);
610 bug_on(gettimeofday(&end, NULL));
611 timersub(&end, &start, &diff);
613 if (ctx->smoke_test)
614 close(icmp_sock);
616 stats[cpu].tx_packets = tx_packets;
617 stats[cpu].tx_bytes = tx_bytes;
618 stats[cpu].tv_sec = diff.tv_sec;
619 stats[cpu].tv_usec = diff.tv_usec;
621 stats[cpu].state |= CPU_STATS_STATE_RES;
624 static void xmit_fastpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
626 int ifindex = device_ifindex(ctx->device);
627 uint8_t *out = NULL;
628 unsigned int it = 0;
629 unsigned long num = 1, i = 0;
630 size_t size = ring_size(ctx->device, ctx->reserve_size);
631 struct ring tx_ring;
632 struct frame_map *hdr;
633 struct timeval start, end, diff;
634 struct packet_dyn *pktd;
635 unsigned long long tx_bytes = 0, tx_packets = 0;
637 set_sock_prio(sock, 512);
639 ring_tx_setup(&tx_ring, sock, size, ifindex, ctx->jumbo_support, ctx->verbose);
641 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
643 if (ctx->num > 0)
644 num = ctx->num;
645 if (ctx->num == 0 && orig_num > 0)
646 num = 0;
648 bug_on(gettimeofday(&start, NULL));
650 while (likely(sigint == 0 && num > 0 && plen > 0)) {
651 if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
652 int ret = pull_and_flush_tx_ring(sock);
653 if (unlikely(ret < 0)) {
654 /* We could hit EBADF if the socket has been closed before
655 * the timer was triggered.
657 if (errno != EBADF && errno != ENOBUFS)
658 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
661 continue;
664 hdr = tx_ring.frames[it].iov_base;
665 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
667 hdr->tp_h.tp_snaplen = packets[i].len;
668 hdr->tp_h.tp_len = packets[i].len;
670 pktd = &packet_dyn[i];
671 if (packet_dyn_has_elems(pktd)) {
672 apply_counter(i);
673 apply_randomizer(i);
674 apply_csum16(i);
677 fmemcpy(out, packets[i].payload, packets[i].len);
679 tx_bytes += packets[i].len;
680 tx_packets++;
682 if (!ctx->rand) {
683 i++;
684 if (i >= plen)
685 i = 0;
686 } else
687 i = rand() % plen;
689 kernel_may_pull_from_tx(&hdr->tp_h);
691 it++;
692 if (it >= tx_ring.layout.tp_frame_nr)
693 it = 0;
695 if (ctx->num > 0)
696 num--;
699 bug_on(gettimeofday(&end, NULL));
700 timersub(&end, &start, &diff);
702 pull_and_flush_tx_ring_wait(sock);
703 destroy_tx_ring(sock, &tx_ring);
705 stats[cpu].tx_packets = tx_packets;
706 stats[cpu].tx_bytes = tx_bytes;
707 stats[cpu].tv_sec = diff.tv_sec;
708 stats[cpu].tv_usec = diff.tv_usec;
710 stats[cpu].state |= CPU_STATS_STATE_RES;
713 static inline void __set_state(unsigned int cpu, sig_atomic_t s)
715 stats[cpu].state = s;
718 static inline sig_atomic_t __get_state(unsigned int cpu)
720 return stats[cpu].state;
723 static unsigned long __wait_and_sum_others(struct ctx *ctx, unsigned int cpu)
725 unsigned int i;
726 unsigned long total;
728 for (i = 0, total = plen; i < ctx->cpus; i++) {
729 if (i == cpu)
730 continue;
732 while ((__get_state(i) &
733 (CPU_STATS_STATE_CFG |
734 CPU_STATS_STATE_RES)) == 0 &&
735 sigint == 0)
736 sched_yield();
738 total += stats[i].cf_packets;
741 return total;
744 static void __correct_global_delta(struct ctx *ctx, unsigned int cpu, unsigned long orig)
746 unsigned int i;
747 unsigned long total;
748 int cpu_sel;
749 long long delta_correction = 0;
751 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
752 if (i == cpu)
753 continue;
755 while ((__get_state(i) &
756 (CPU_STATS_STATE_CHK |
757 CPU_STATS_STATE_RES)) == 0 &&
758 sigint == 0)
759 sched_yield();
761 total += stats[i].cd_packets;
764 if (total > orig)
765 delta_correction = -1 * ((long long) total - orig);
766 if (total < orig)
767 delta_correction = +1 * ((long long) orig - total);
769 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
770 if (stats[i].cd_packets > 0) {
771 if ((long long) stats[i].cd_packets +
772 delta_correction >= 0) {
773 cpu_sel = i;
774 break;
779 if ((int) cpu == cpu_sel)
780 ctx->num += delta_correction;
783 static void __set_state_cf(unsigned int cpu, unsigned long p, unsigned long b,
784 sig_atomic_t s)
786 stats[cpu].cf_packets = p;
787 stats[cpu].cf_bytes = b;
788 stats[cpu].state = s;
791 static void __set_state_cd(unsigned int cpu, unsigned long p, sig_atomic_t s)
793 stats[cpu].cd_packets = p;
794 stats[cpu].state = s;
797 static void xmit_packet_precheck(struct ctx *ctx, unsigned int cpu)
799 unsigned long plen_total, orig = ctx->num;
800 size_t total_len = 0;
801 unsigned int i;
803 bug_on(plen != dlen);
805 for (i = 0; i < plen; ++i)
806 total_len += packets[i].len;
808 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
809 plen_total = __wait_and_sum_others(ctx, cpu);
811 if (orig > 0) {
812 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
814 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
815 CPU_STATS_STATE_CFG);
816 __correct_global_delta(ctx, cpu, orig);
819 if (plen == 0) {
820 __set_state(cpu, CPU_STATS_STATE_RES);
821 return;
825 static void main_loop(struct ctx *ctx, char *confname, bool slow,
826 unsigned int cpu, bool invoke_cpp, unsigned long orig_num)
828 if (ctx->packet_str)
829 compile_packets_str(ctx->packet_str, ctx->verbose, cpu);
830 else
831 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
833 preprocess_packets();
835 xmit_packet_precheck(ctx, cpu);
837 if (cpu == 0) {
838 unsigned int i;
839 size_t total_len = 0, total_pkts = 0;
841 for (i = 0; i < ctx->cpus; ++i) {
842 total_len += stats[i].cf_bytes;
843 total_pkts += stats[i].cf_packets;
846 printf("%6zu packets to schedule\n", total_pkts);
847 printf("%6zu bytes in total\n", total_len);
848 printf("Running! Hang up with ^C!\n\n");
849 fflush(stdout);
852 sock = pf_socket();
854 if (ctx->qdisc_path == false)
855 set_sock_qdisc_bypass(sock, ctx->verbose);
857 if (slow)
858 xmit_slowpath_or_die(ctx, cpu, orig_num);
859 else
860 xmit_fastpath_or_die(ctx, cpu, orig_num);
862 close(sock);
864 cleanup_packets();
867 static unsigned int generate_srand_seed(void)
869 int fd;
870 unsigned int _seed;
872 fd = open("/dev/urandom", O_RDONLY);
873 if (fd < 0)
874 return time(NULL);
876 read_or_die(fd, &_seed, sizeof(_seed));
878 close(fd);
879 return _seed;
882 static void on_panic_del_rfmon(void *arg)
884 leave_rfmon_mac80211(arg);
887 int main(int argc, char **argv)
889 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
890 bool prio_high = false, set_irq_aff = true, set_sock_mem = true;
891 int c, opt_index, vals[4] = {0}, irq;
892 uint64_t gap = 0;
893 unsigned int i, j;
894 char *confname = NULL, *ptr;
895 unsigned long cpus_tmp, orig_num = 0;
896 unsigned long long tx_packets, tx_bytes;
897 struct ctx ctx;
898 int min_opts = 5;
900 fmemset(&ctx, 0, sizeof(ctx));
901 ctx.cpus = get_number_cpus_online();
902 ctx.uid = getuid();
903 ctx.gid = getgid();
904 ctx.qdisc_path = false;
906 /* Keep an initial small default size to reduce cache-misses. */
907 ctx.reserve_size = 512 * (1 << 10);
909 while ((c = getopt_long(argc, argv, short_options, long_options,
910 &opt_index)) != EOF) {
911 switch (c) {
912 case 'h':
913 help();
914 break;
915 case 'v':
916 version();
917 break;
918 case 'C':
919 cpustats = false;
920 break;
921 case 'e':
922 example();
923 break;
924 case 'p':
925 invoke_cpp = true;
926 break;
927 case 'V':
928 ctx.verbose = true;
929 break;
930 case 'P':
931 cpus_tmp = strtoul(optarg, NULL, 0);
932 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
933 ctx.cpus = cpus_tmp;
934 break;
935 case 'd':
936 case 'o':
937 ctx.device = xstrndup(optarg, IFNAMSIZ);
938 break;
939 case 'H':
940 prio_high = true;
941 break;
942 case 'A':
943 set_sock_mem = false;
944 break;
945 case 'Q':
946 set_irq_aff = false;
947 break;
948 case 'q':
949 ctx.qdisc_path = true;
950 break;
951 case 'r':
952 ctx.rand = true;
953 break;
954 case 's':
955 slow = true;
956 ctx.cpus = 1;
957 ctx.smoke_test = true;
958 ctx.rhost = xstrdup(optarg);
959 break;
960 case 'R':
961 ctx.rfraw = true;
962 break;
963 case 'J':
964 ctx.jumbo_support = true;
965 break;
966 case 'c':
967 case 'i':
968 confname = xstrdup(optarg);
969 if (!strncmp("-", confname, strlen("-")))
970 ctx.cpus = 1;
971 break;
972 case 'u':
973 ctx.uid = strtoul(optarg, NULL, 0);
974 ctx.enforce = true;
975 break;
976 case 'g':
977 ctx.gid = strtoul(optarg, NULL, 0);
978 ctx.enforce = true;
979 break;
980 case 'k':
981 printf("Option -k/--kernel-pull is no longer used and "
982 "will be removed in a future release!\n");
983 break;
984 case 'E':
985 seed = strtoul(optarg, NULL, 0);
986 reseed = false;
987 break;
988 case 'n':
989 orig_num = strtoul(optarg, NULL, 0);
990 ctx.num = orig_num;
991 break;
992 case 't':
993 slow = true;
994 ptr = optarg;
995 prctl(PR_SET_TIMERSLACK, 1UL);
996 gap = strtoul(optarg, NULL, 0);
998 for (j = i = strlen(optarg); i > 0; --i) {
999 if (!isdigit(optarg[j - i]))
1000 break;
1001 ptr++;
1004 if (!strncmp(ptr, "ns", strlen("ns"))) {
1005 ctx.gap.tv_sec = gap / 1000000000;
1006 ctx.gap.tv_nsec = gap % 1000000000;
1007 } else if (*ptr == '\0' || !strncmp(ptr, "us", strlen("us"))) {
1008 /* Default to microseconds for backwards
1009 * compatibility if no postfix is given.
1011 ctx.gap.tv_sec = gap / 1000000;
1012 ctx.gap.tv_nsec = (gap % 1000000) * 1000;
1013 } else if (!strncmp(ptr, "ms", strlen("ms"))) {
1014 ctx.gap.tv_sec = gap / 1000;
1015 ctx.gap.tv_nsec = (gap % 1000) * 1000000;
1016 } else if (!strncmp(ptr, "s", strlen("s"))) {
1017 ctx.gap.tv_sec = gap;
1018 ctx.gap.tv_nsec = 0;
1019 } else
1020 panic("Syntax error in time param!\n");
1022 if (gap > 0)
1023 /* Fall back to single core to not mess up
1024 * correct timing. We are slow anyway!
1026 ctx.cpus = 1;
1027 break;
1028 case 'S':
1029 ptr = optarg;
1031 for (j = i = strlen(optarg); i > 0; --i) {
1032 if (!isdigit(optarg[j - i]))
1033 break;
1034 ptr++;
1037 if (!strncmp(ptr, "KiB", strlen("KiB")))
1038 ctx.reserve_size = 1 << 10;
1039 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1040 ctx.reserve_size = 1 << 20;
1041 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1042 ctx.reserve_size = 1 << 30;
1043 else
1044 panic("Syntax error in ring size param!\n");
1046 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1047 break;
1048 case '?':
1049 switch (optopt) {
1050 case 'd':
1051 case 'c':
1052 case 'n':
1053 case 'S':
1054 case 's':
1055 case 'P':
1056 case 'o':
1057 case 'E':
1058 case 'i':
1059 case 'k':
1060 case 'u':
1061 case 'g':
1062 case 't':
1063 panic("Option -%c requires an argument!\n",
1064 optopt);
1065 default:
1066 if (isprint(optopt))
1067 printf("Unknown option character `0x%X\'!\n", optopt);
1068 die();
1070 default:
1071 break;
1075 if (argc >= optind) {
1076 min_opts = 4;
1077 ctx.packet_str = argv2str(optind, argc, argv);
1080 if (argc < min_opts)
1081 help();
1082 if (ctx.device == NULL)
1083 panic("No networking device given!\n");
1084 if (confname == NULL && !ctx.packet_str)
1085 panic("No configuration file or packet string given!\n");
1086 if (device_mtu(ctx.device) == 0)
1087 panic("This is no networking device!\n");
1089 register_signal(SIGINT, signal_handler);
1090 register_signal(SIGQUIT, signal_handler);
1091 register_signal(SIGTERM, signal_handler);
1092 register_signal(SIGHUP, signal_handler);
1094 if (prio_high) {
1095 set_proc_prio(-20);
1096 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1099 if (set_sock_mem)
1100 set_system_socket_memory(vals, array_size(vals));
1101 xlockme();
1103 if (ctx.rfraw) {
1104 ctx.device_trans = xstrdup(ctx.device);
1105 xfree(ctx.device);
1107 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1108 panic_handler_add(on_panic_del_rfmon, ctx.device);
1109 sleep(0);
1113 * If number of packets is smaller than number of CPUs use only as
1114 * many CPUs as there are packets. Otherwise we end up sending more
1115 * packets than intended or none at all.
1117 if (ctx.num)
1118 ctx.cpus = min_t(unsigned int, ctx.num, ctx.cpus);
1120 irq = device_irq_number(ctx.device);
1121 if (set_irq_aff)
1122 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1124 stats = setup_shared_var(ctx.cpus);
1126 for (i = 0; i < ctx.cpus; i++) {
1127 pid_t pid = fork();
1129 switch (pid) {
1130 case 0:
1131 if (reseed)
1132 seed = generate_srand_seed();
1133 srand(seed);
1135 cpu_affinity(i);
1136 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1138 goto thread_out;
1139 case -1:
1140 panic("Cannot fork processes!\n");
1144 for (i = 0; i < ctx.cpus; i++) {
1145 int status;
1147 wait(&status);
1148 if (WEXITSTATUS(status) == EXIT_FAILURE)
1149 die();
1152 if (ctx.rfraw)
1153 leave_rfmon_mac80211(ctx.device);
1155 if (set_sock_mem)
1156 reset_system_socket_memory(vals, array_size(vals));
1158 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1159 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1160 sched_yield();
1162 tx_packets += stats[i].tx_packets;
1163 tx_bytes += stats[i].tx_bytes;
1166 fflush(stdout);
1167 printf("\n");
1168 printf("\r%12llu packets outgoing\n", tx_packets);
1169 printf("\r%12llu bytes outgoing\n", tx_bytes);
1170 for (i = 0; cpustats && i < ctx.cpus; i++) {
1171 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1172 stats[i].tv_sec, stats[i].tv_usec, i,
1173 stats[i].tx_packets);
1176 thread_out:
1177 xunlockme();
1178 destroy_shared_var(stats, ctx.cpus);
1179 if (set_irq_aff)
1180 device_restore_irq_affinity_list();
1182 free(ctx.device);
1183 free(ctx.device_trans);
1184 free(ctx.rhost);
1185 free(confname);
1186 free(ctx.packet_str);
1188 return 0;