dissectors: arp: Print hardware & protocol addresses
[netsniff-ng.git] / trafgen.c
blobc74a97328285d5c23460d361e92f589718f70cc9
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 #ifndef timeval_to_timespec
59 #define timeval_to_timespec(tv, ts) { \
60 (ts)->tv_sec = (tv)->tv_sec; \
61 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
63 #endif
65 enum shaper_type {
66 SHAPER_NONE,
67 SHAPER_PKTS,
68 SHAPER_BYTES,
71 struct shaper {
72 enum shaper_type type;
73 unsigned long long sent;
74 unsigned long long rate;
75 struct timeval start;
76 struct timeval end;
77 struct timespec delay;
80 struct ctx {
81 bool rand, rfraw, jumbo_support, verbose, smoke_test, enforce, qdisc_path;
82 size_t reserve_size;
83 unsigned long num;
84 unsigned int cpus;
85 uid_t uid; gid_t gid;
86 char *device, *device_trans, *rhost;
87 struct sockaddr_in dest;
88 struct shaper sh;
89 char *packet_str;
92 struct cpu_stats {
93 unsigned long tv_sec, tv_usec;
94 unsigned long long tx_packets, tx_bytes;
95 unsigned long long cf_packets, cf_bytes;
96 unsigned long long cd_packets;
97 sig_atomic_t state;
100 static sig_atomic_t sigint = 0;
102 struct packet *packets = NULL;
103 size_t plen = 0;
105 struct packet_dyn *packet_dyn = NULL;
106 size_t dlen = 0;
108 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:CHQqD:b:";
109 static const struct option long_options[] = {
110 {"dev", required_argument, NULL, 'd'},
111 {"out", required_argument, NULL, 'o'},
112 {"in", required_argument, NULL, 'i'},
113 {"conf", required_argument, NULL, 'c'},
114 {"num", required_argument, NULL, 'n'},
115 {"gap", required_argument, NULL, 't'},
116 {"rate", required_argument, NULL, 'b'},
117 {"cpus", required_argument, NULL, 'P'},
118 {"ring-size", required_argument, NULL, 'S'},
119 {"kernel-pull", required_argument, NULL, 'k'},
120 {"smoke-test", required_argument, NULL, 's'},
121 {"seed", required_argument, NULL, 'E'},
122 {"user", required_argument, NULL, 'u'},
123 {"group", required_argument, NULL, 'g'},
124 {"prio-high", no_argument, NULL, 'H'},
125 {"notouch-irq", no_argument, NULL, 'Q'},
126 {"no-sock-mem", no_argument, NULL, 'A'},
127 {"qdisc-path", no_argument, NULL, 'q'},
128 {"jumbo-support", no_argument, NULL, 'J'},
129 {"no-cpu-stats", no_argument, NULL, 'C'},
130 {"cpp", no_argument, NULL, 'p'},
131 {"define", required_argument, NULL, 'D'},
132 {"rfraw", no_argument, NULL, 'R'},
133 {"rand", no_argument, NULL, 'r'},
134 {"verbose", no_argument, NULL, 'V'},
135 {"version", no_argument, NULL, 'v'},
136 {"example", no_argument, NULL, 'e'},
137 {"help", no_argument, NULL, 'h'},
138 {NULL, 0, NULL, 0}
141 static const char *copyright = "Please report bugs to <netsniff-ng@googlegroups.com>\n"
142 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
143 "Swiss federal institute of technology (ETH Zurich)\n"
144 "License: GNU GPL version 2.0\n"
145 "This is free software: you are free to change and redistribute it.\n"
146 "There is NO WARRANTY, to the extent permitted by law.";
148 static int sock;
149 static struct cpu_stats *stats;
150 static unsigned int seed;
152 #define CPU_STATS_STATE_CFG 1
153 #define CPU_STATS_STATE_CHK 2
154 #define CPU_STATS_STATE_RES 4
156 #ifndef ICMP_FILTER
157 # define ICMP_FILTER 1
159 struct icmp_filter {
160 __u32 data;
162 #endif
164 #define SMOKE_N_PROBES 100
166 #define PKT_MIN_LEN 14
168 static void signal_handler(int number)
170 switch (number) {
171 case SIGINT:
172 case SIGQUIT:
173 case SIGTERM:
174 sigint = 1;
175 case SIGHUP:
176 default:
177 break;
181 static void __noreturn help(void)
183 printf("trafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
184 puts("http://www.netsniff-ng.org\n\n"
185 "Usage: trafgen [options] [packet]\n"
186 "Options:\n"
187 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
188 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
189 " -p|--cpp Run packet config through C preprocessor\n"
190 " -D|--define Add macro/define for C preprocessor\n"
191 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
192 " -R|--rfraw Inject raw 802.11 frames\n"
193 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
194 " -n|--num <uint> Number of packets until exit (def: 0)\n"
195 " -r|--rand Randomize packet selection (def: round robin)\n"
196 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
197 " -t|--gap <time> Set approx. interpacket gap (s/ms/us/ns, def: us)\n"
198 " -b|--rate <rate> Send traffic at specified rate (pps/B/kB/MB/GB/kbit/Mbit/Gbit/KiB/MiB/GiB)\n"
199 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
200 " -E|--seed <uint> Manually set srand(3) seed\n"
201 " -u|--user <userid> Drop privileges and change to userid\n"
202 " -g|--group <groupid> Drop privileges and change to groupid\n"
203 " -H|--prio-high Make this high priority process\n"
204 " -A|--no-sock-mem Don't tune core socket memory\n"
205 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
206 " -q|--qdisc-path Enabled qdisc kernel path (default off since 3.14)\n"
207 " -V|--verbose Be more verbose\n"
208 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
209 " -v|--version Show version and exit\n"
210 " -e|--example Show built-in packet config example\n"
211 " -h|--help Guess what?!\n\n"
212 "Examples:\n"
213 " trafgen --dev eth0 --conf trafgen.cfg\n"
214 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
215 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
216 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
217 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000us\n"
218 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
219 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n"
220 " trafgen --dev eth0 '{ fill(0xff, 6), 0x00, 0x02, 0xb3, rnd(3), c16(0x0800), fill(0xca, 64) }'\n\n"
221 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
222 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
223 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
224 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
225 "Generate config files from existing pcap using netsniff-ng:\n"
226 " netsniff-ng --in dump.pcap --out dump.cfg\n\n"
227 "Note:\n"
228 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
229 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
230 " we assume the kernel crashed, thus we print the packet and quit.\n"
231 " In case you find a ping-of-death, please mention trafgen in your\n"
232 " commit message of the fix!\n\n"
233 " For introducing bit errors, delays with random variation and more,\n"
234 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
235 " For generating different package distributions, you can use scripting\n"
236 " to generate a trafgen config file with packet ratios as:\n\n"
237 " IMIX 64:7, 570:4, 1518:1\n"
238 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
239 " Cisco 64:7, 594:4, 1518:1\n"
240 " RPR Trimodal 64:60, 512:20, 1518:20\n"
241 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n");
242 puts(copyright);
243 die();
246 static void __noreturn example(void)
248 const char *e =
249 "/* Note: dynamic elements make trafgen slower! */\n"
250 "#include <stddef.h>\n\n"
251 "{\n"
252 " /* MAC Destination */\n"
253 " fill(0xff, ETH_ALEN),\n"
254 " /* MAC Source */\n"
255 " 0x00, 0x02, 0xb3, drnd(3),\n"
256 " /* IPv4 Protocol */\n"
257 " c16(ETH_P_IP),\n"
258 " /* IPv4 Version, IHL, TOS */\n"
259 " 0b01000101, 0,\n"
260 " /* IPv4 Total Len */\n"
261 " c16(59),\n"
262 " /* IPv4 Ident */\n"
263 " drnd(2),\n"
264 " /* IPv4 Flags, Frag Off */\n"
265 " 0b01000000, 0,\n"
266 " /* IPv4 TTL */\n"
267 " 64,\n"
268 " /* Proto TCP */\n"
269 " 0x06,\n"
270 " /* IPv4 Checksum (IP header from, to) */\n"
271 " csumip(14, 33),\n"
272 " /* Source IP */\n"
273 " drnd(4),\n"
274 " /* Dest IP */\n"
275 " drnd(4),\n"
276 " /* TCP Source Port */\n"
277 " drnd(2),\n"
278 " /* TCP Dest Port */\n"
279 " c16(80),\n"
280 " /* TCP Sequence Number */\n"
281 " drnd(4),\n"
282 " /* TCP Ackn. Number */\n"
283 " c32(0),\n"
284 " /* TCP Header length + TCP SYN/ECN Flag */\n"
285 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
286 " /* Window Size */\n"
287 " c16(16),\n"
288 " /* TCP Checksum (offset IP, offset TCP) */\n"
289 " csumtcp(14, 34),\n"
290 " /* TCP Options */\n"
291 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
292 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
293 " /* Data blob */\n"
294 " \"gotcha!\",\n"
295 "}";
296 puts(e);
297 die();
300 static void __noreturn version(void)
302 printf("trafgen %s, Git id: %s\n", VERSION_LONG, GITVERSION);
303 puts("multithreaded zero-copy network packet generator\n"
304 "http://www.netsniff-ng.org\n");
305 puts(copyright);
306 die();
309 static void apply_counter(int id)
311 size_t j, counter_max = packet_dyn[id].clen;
313 for (j = 0; j < counter_max; ++j) {
314 uint8_t val;
315 struct counter *counter = &packet_dyn[id].cnt[j];
317 val = counter->val - counter->min;
319 switch (counter->type) {
320 case TYPE_INC:
321 val = (val + counter->inc) % (counter->max - counter->min + 1);
322 break;
323 case TYPE_DEC:
324 val = (val - counter->inc) % (counter->min - counter->max + 1);
325 break;
326 default:
327 bug();
330 counter->val = val + counter->min;
331 packets[id].payload[counter->off] = val;
335 static void apply_randomizer(int id)
337 size_t j, rand_max = packet_dyn[id].rlen;
339 for (j = 0; j < rand_max; ++j) {
340 uint8_t val = (uint8_t) rand();
341 struct randomizer *randomizer = &packet_dyn[id].rnd[j];
343 packets[id].payload[randomizer->off] = val;
347 static void apply_csum16(int id)
349 size_t j, csum_max = packet_dyn[id].slen;
351 for (j = 0; j < csum_max; ++j) {
352 uint16_t sum = 0;
353 struct csum16 *csum = &packet_dyn[id].csum[j];
355 fmemset(&packets[id].payload[csum->off], 0, sizeof(sum));
356 if (unlikely((size_t) csum->to >= packets[id].len))
357 csum->to = packets[id].len - 1;
359 switch (csum->which) {
360 case CSUM_IP:
361 sum = calc_csum(packets[id].payload + csum->from,
362 csum->to - csum->from + 1);
363 break;
364 case CSUM_UDP:
365 sum = p4_csum((void *) packets[id].payload + csum->from,
366 packets[id].payload + csum->to,
367 (packets[id].len - csum->to),
368 IPPROTO_UDP);
369 break;
370 case CSUM_TCP:
371 sum = p4_csum((void *) packets[id].payload + csum->from,
372 packets[id].payload + csum->to,
373 (packets[id].len - csum->to),
374 IPPROTO_TCP);
375 break;
376 case CSUM_UDP6:
377 sum = p6_csum((void *) packets[id].payload + csum->from,
378 packets[id].payload + csum->to,
379 (packets[id].len - csum->to),
380 IPPROTO_UDP);
381 break;
382 case CSUM_TCP6:
383 sum = p6_csum((void *) packets[id].payload + csum->from,
384 packets[id].payload + csum->to,
385 (packets[id].len - csum->to),
386 IPPROTO_TCP);
387 break;
388 default:
389 bug();
390 break;
393 fmemcpy(&packets[id].payload[csum->off], &sum, sizeof(sum));
397 static void preprocess_packets(void)
399 size_t i;
401 for (i = 0; i < plen; i++) {
402 struct packet_dyn *pktd = &packet_dyn[i];
404 if (packet_dyn_has_only_csums(pktd)) {
405 apply_csum16(i);
406 pktd->slen = 0;
407 xfree(pktd->csum);
412 static struct cpu_stats *setup_shared_var(unsigned int cpus)
414 int fd;
415 size_t len = cpus * sizeof(struct cpu_stats);
416 char *zbuff, file[256];
417 struct cpu_stats *buff;
419 zbuff = xzmalloc(len);
420 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
422 fd = creat(file, S_IRUSR | S_IWUSR);
423 bug_on(fd < 0);
424 close(fd);
426 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
427 S_IRUSR | S_IWUSR);
428 write_or_die(fd, zbuff, len);
429 xfree(zbuff);
431 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
432 MAP_SHARED, fd, 0);
433 if (buff == MAP_FAILED)
434 panic("Cannot setup shared variable!\n");
436 close(fd);
437 unlink(file);
439 memset(buff, 0, len);
440 return buff;
443 static void destroy_shared_var(void *buff, unsigned int cpus)
445 munmap(buff, cpus * sizeof(struct cpu_stats));
448 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
450 size_t i;
452 printf("{");
453 for (i = 0; i < len; ++i) {
454 if (i % 15 == 0)
455 printf("\n ");
456 printf("0x%02x, ", payload[i]);
458 printf("\n}\n");
459 fflush(stdout);
462 static int xmit_smoke_setup(struct ctx *ctx)
464 int icmp_sock, ret, ttl = 64;
465 struct icmp_filter filter;
467 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
468 if (icmp_sock < 0)
469 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
471 filter.data = ~(1 << ICMP_ECHOREPLY);
473 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
474 if (ret < 0)
475 panic("Cannot install filter!\n");
477 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
478 if (ret < 0)
479 panic("Cannot set TTL!\n");
481 memset(&ctx->dest, 0, sizeof(ctx->dest));
482 ctx->dest.sin_family = AF_INET;
483 ctx->dest.sin_port = 0;
485 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
486 if (ret < 0)
487 panic("Cannot resolve address!\n");
489 return icmp_sock;
492 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
494 int ret;
495 unsigned int i, j;
496 short ident, cnt = 1, idstore[SMOKE_N_PROBES];
497 uint8_t outpack[512], *data;
498 struct icmphdr *icmp;
499 struct iphdr *ip;
500 size_t len = sizeof(*icmp) + 56;
501 struct sockaddr_in from;
502 socklen_t from_len;
503 struct pollfd fds = {
504 .fd = icmp_sock,
505 .events = POLLIN,
508 fmemset(idstore, 0, sizeof(idstore));
509 for (j = 0; j < SMOKE_N_PROBES; j++) {
510 while ((ident = htons((short) rand())) == 0)
511 sleep(0);
512 idstore[j] = ident;
514 memset(outpack, 0, sizeof(outpack));
515 icmp = (void *) outpack;
516 icmp->type = ICMP_ECHO;
517 icmp->un.echo.id = ident;
518 icmp->un.echo.sequence = htons(cnt++);
520 data = ((uint8_t *) outpack + sizeof(*icmp));
521 for (i = 0; i < 56; ++i)
522 data[i] = (uint8_t) rand();
524 icmp->checksum = csum((unsigned short *) outpack,
525 len / sizeof(unsigned short));
527 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
528 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
529 if (unlikely(ret != (int) len))
530 panic("Cannot send out probe: %s!\n", strerror(errno));
532 ret = poll(&fds, 1, 50);
533 if (ret < 0)
534 panic("Poll failed!\n");
536 if (fds.revents & POLLIN) {
537 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
538 (struct sockaddr *) &from, &from_len);
539 if (unlikely(ret <= 0))
540 panic("Probe receive failed!\n");
541 if (unlikely(from_len != sizeof(ctx->dest)))
542 continue;
543 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
544 continue;
545 if (unlikely((size_t) ret < sizeof(*ip) + sizeof(*icmp)))
546 continue;
547 ip = (void *) outpack;
548 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > (size_t) ret))
549 continue;
550 icmp = (void *) outpack + ip->ihl * 4;
551 for (i = 0; i < array_size(idstore); ++i) {
552 if (unlikely(icmp->un.echo.id != idstore[i]))
553 continue;
554 return 0;
559 return -1;
562 static bool shaper_is_set(struct shaper *sh)
564 if ((sh->delay.tv_sec | sh->delay.tv_nsec) > 0)
565 return true;
567 return sh->type != SHAPER_NONE;
570 static void shaper_init(struct shaper *sh)
572 if (sh->type == SHAPER_NONE)
573 return;
575 memset(&sh->delay, 0, sizeof(struct timespec));
576 bug_on(gettimeofday(&sh->start, NULL));
577 sh->sent = 0;
580 static void shaper_set_delay(struct shaper *sh, time_t sec, long int ns)
582 sh->delay.tv_sec = sec;
583 sh->delay.tv_nsec = ns;
586 static void shaper_set_rate(struct shaper *sh, unsigned long long rate,
587 enum shaper_type type)
589 memset(sh, 0, sizeof(struct shaper));
590 sh->rate = rate;
591 sh->type = type;
594 static void shaper_delay(struct shaper *sh, unsigned long pkt_len)
596 if (sh->type != SHAPER_NONE)
597 sh->sent += sh->type == SHAPER_BYTES ? pkt_len : 1;
599 if (sh->sent >= sh->rate && sh->rate > 0) {
600 struct timeval delay_us;
601 struct timeval time_sent;
602 struct timeval time_1s = { .tv_sec = 1 };
604 bug_on(gettimeofday(&sh->end, NULL));
605 timersub(&sh->end, &sh->start, &time_sent);
607 if (timercmp(&time_1s, &time_sent, > )) {
608 timersub(&time_1s, &time_sent, &delay_us);
609 timeval_to_timespec(&delay_us, &sh->delay);
613 if ((sh->delay.tv_sec | sh->delay.tv_nsec) > 0) {
614 nanosleep(&sh->delay, NULL);
616 shaper_init(sh);
620 static void xmit_slowpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
622 int ret, icmp_sock = -1;
623 unsigned long num = 1, i = 0;
624 struct timeval start, end, diff;
625 unsigned long long tx_bytes = 0, tx_packets = 0;
626 struct packet_dyn *pktd;
627 struct sockaddr_ll saddr = {
628 .sll_family = PF_PACKET,
629 .sll_halen = ETH_ALEN,
630 .sll_ifindex = device_ifindex(ctx->device),
633 if (ctx->num > 0)
634 num = ctx->num;
635 if (ctx->num == 0 && orig_num > 0)
636 num = 0;
638 if (ctx->smoke_test)
639 icmp_sock = xmit_smoke_setup(ctx);
641 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
643 bug_on(gettimeofday(&start, NULL));
645 if (shaper_is_set(&ctx->sh))
646 shaper_init(&ctx->sh);
648 while (likely(sigint == 0 && num > 0 && plen > 0)) {
649 pktd = &packet_dyn[i];
650 if (packet_dyn_has_elems(pktd)) {
651 apply_counter(i);
652 apply_randomizer(i);
653 apply_csum16(i);
655 retry:
656 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
657 (struct sockaddr *) &saddr, sizeof(saddr));
658 if (unlikely(ret < 0)) {
659 if (errno == ENOBUFS) {
660 sched_yield();
661 goto retry;
663 if (ctx->smoke_test)
664 panic("Sendto error: %s!\n", strerror(errno));
667 tx_bytes += packets[i].len;
668 tx_packets++;
670 if (ctx->smoke_test) {
671 ret = xmit_smoke_probe(icmp_sock, ctx);
672 if (unlikely(ret < 0)) {
673 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
674 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
675 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
676 i, seed);
678 dump_trafgen_snippet(packets[i].payload, packets[i].len);
679 break;
683 if (!ctx->rand) {
684 i++;
685 if (i >= plen)
686 i = 0;
687 } else
688 i = rand() % plen;
690 if (ctx->num > 0)
691 num--;
693 if (shaper_is_set(&ctx->sh))
694 shaper_delay(&ctx->sh, packets[i].len);
697 bug_on(gettimeofday(&end, NULL));
698 timersub(&end, &start, &diff);
700 if (ctx->smoke_test)
701 close(icmp_sock);
703 stats[cpu].tx_packets = tx_packets;
704 stats[cpu].tx_bytes = tx_bytes;
705 stats[cpu].tv_sec = diff.tv_sec;
706 stats[cpu].tv_usec = diff.tv_usec;
708 stats[cpu].state |= CPU_STATS_STATE_RES;
711 static void xmit_fastpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
713 int ifindex = device_ifindex(ctx->device);
714 uint8_t *out = NULL;
715 unsigned int it = 0;
716 unsigned long num = 1, i = 0;
717 size_t size = ring_size(ctx->device, ctx->reserve_size);
718 struct ring tx_ring;
719 struct frame_map *hdr;
720 struct timeval start, end, diff;
721 struct packet_dyn *pktd;
722 unsigned long long tx_bytes = 0, tx_packets = 0;
724 set_sock_prio(sock, 512);
726 ring_tx_setup(&tx_ring, sock, size, ifindex, ctx->jumbo_support, ctx->verbose);
728 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
730 if (ctx->num > 0)
731 num = ctx->num;
732 if (ctx->num == 0 && orig_num > 0)
733 num = 0;
735 bug_on(gettimeofday(&start, NULL));
737 while (likely(sigint == 0 && num > 0 && plen > 0)) {
738 if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
739 int ret = pull_and_flush_tx_ring(sock);
740 if (unlikely(ret < 0)) {
741 /* We could hit EBADF if the socket has been closed before
742 * the timer was triggered.
744 if (errno != EBADF && errno != ENOBUFS)
745 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
748 continue;
751 hdr = tx_ring.frames[it].iov_base;
752 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
754 hdr->tp_h.tp_snaplen = packets[i].len;
755 hdr->tp_h.tp_len = packets[i].len;
757 pktd = &packet_dyn[i];
758 if (packet_dyn_has_elems(pktd)) {
759 apply_counter(i);
760 apply_randomizer(i);
761 apply_csum16(i);
764 fmemcpy(out, packets[i].payload, packets[i].len);
766 tx_bytes += packets[i].len;
767 tx_packets++;
769 if (!ctx->rand) {
770 i++;
771 if (i >= plen)
772 i = 0;
773 } else
774 i = rand() % plen;
776 kernel_may_pull_from_tx(&hdr->tp_h);
778 it++;
779 if (it >= tx_ring.layout.tp_frame_nr)
780 it = 0;
782 if (ctx->num > 0)
783 num--;
786 bug_on(gettimeofday(&end, NULL));
787 timersub(&end, &start, &diff);
789 pull_and_flush_tx_ring_wait(sock);
790 destroy_tx_ring(sock, &tx_ring);
792 stats[cpu].tx_packets = tx_packets;
793 stats[cpu].tx_bytes = tx_bytes;
794 stats[cpu].tv_sec = diff.tv_sec;
795 stats[cpu].tv_usec = diff.tv_usec;
797 stats[cpu].state |= CPU_STATS_STATE_RES;
800 static inline void __set_state(unsigned int cpu, sig_atomic_t s)
802 stats[cpu].state = s;
805 static inline sig_atomic_t __get_state(unsigned int cpu)
807 return stats[cpu].state;
810 static unsigned long __wait_and_sum_others(struct ctx *ctx, unsigned int cpu)
812 unsigned int i;
813 unsigned long total;
815 for (i = 0, total = plen; i < ctx->cpus; i++) {
816 if (i == cpu)
817 continue;
819 while ((__get_state(i) &
820 (CPU_STATS_STATE_CFG |
821 CPU_STATS_STATE_RES)) == 0 &&
822 sigint == 0)
823 sched_yield();
825 total += stats[i].cf_packets;
828 return total;
831 static void __correct_global_delta(struct ctx *ctx, unsigned int cpu, unsigned long orig)
833 unsigned int i;
834 unsigned long total;
835 int cpu_sel;
836 long long delta_correction = 0;
838 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
839 if (i == cpu)
840 continue;
842 while ((__get_state(i) &
843 (CPU_STATS_STATE_CHK |
844 CPU_STATS_STATE_RES)) == 0 &&
845 sigint == 0)
846 sched_yield();
848 total += stats[i].cd_packets;
851 if (total > orig)
852 delta_correction = -1 * ((long long) total - orig);
853 if (total < orig)
854 delta_correction = +1 * ((long long) orig - total);
856 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
857 if (stats[i].cd_packets > 0) {
858 if ((long long) stats[i].cd_packets +
859 delta_correction >= 0) {
860 cpu_sel = i;
861 break;
866 if ((int) cpu == cpu_sel)
867 ctx->num += delta_correction;
870 static void __set_state_cf(unsigned int cpu, unsigned long p, unsigned long b,
871 sig_atomic_t s)
873 stats[cpu].cf_packets = p;
874 stats[cpu].cf_bytes = b;
875 stats[cpu].state = s;
878 static void __set_state_cd(unsigned int cpu, unsigned long p, sig_atomic_t s)
880 stats[cpu].cd_packets = p;
881 stats[cpu].state = s;
884 static void xmit_packet_precheck(struct ctx *ctx, unsigned int cpu)
886 unsigned long plen_total, orig = ctx->num;
887 size_t total_len = 0;
888 unsigned int i;
890 bug_on(plen != dlen);
892 for (i = 0; i < plen; ++i)
893 total_len += packets[i].len;
895 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
896 plen_total = __wait_and_sum_others(ctx, cpu);
898 if (orig > 0) {
899 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
901 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
902 CPU_STATS_STATE_CFG);
903 __correct_global_delta(ctx, cpu, orig);
906 if (plen == 0) {
907 __set_state(cpu, CPU_STATS_STATE_RES);
908 return;
912 static void main_loop(struct ctx *ctx, char *confname, bool slow,
913 unsigned int cpu, bool invoke_cpp, char **cpp_argv,
914 unsigned long orig_num)
916 if (ctx->packet_str)
917 compile_packets_str(ctx->packet_str, ctx->verbose, cpu);
918 else
919 compile_packets(confname, ctx->verbose, cpu, invoke_cpp, cpp_argv);
921 preprocess_packets();
923 xmit_packet_precheck(ctx, cpu);
925 if (cpu == 0) {
926 unsigned int i;
927 size_t total_len = 0, total_pkts = 0;
929 for (i = 0; i < ctx->cpus; ++i) {
930 total_len += stats[i].cf_bytes;
931 total_pkts += stats[i].cf_packets;
934 printf("%6zu packets to schedule\n", total_pkts);
935 printf("%6zu bytes in total\n", total_len);
936 printf("Running! Hang up with ^C!\n\n");
937 fflush(stdout);
940 sock = pf_socket();
942 if (ctx->qdisc_path == false)
943 set_sock_qdisc_bypass(sock, ctx->verbose);
945 if (slow)
946 xmit_slowpath_or_die(ctx, cpu, orig_num);
947 else
948 xmit_fastpath_or_die(ctx, cpu, orig_num);
950 close(sock);
952 cleanup_packets();
955 static unsigned int generate_srand_seed(void)
957 int fd;
958 unsigned int _seed;
960 fd = open("/dev/urandom", O_RDONLY);
961 if (fd < 0)
962 return time(NULL);
964 read_or_die(fd, &_seed, sizeof(_seed));
966 close(fd);
967 return _seed;
970 static void on_panic_del_rfmon(void *arg)
972 leave_rfmon_mac80211(arg);
975 int main(int argc, char **argv)
977 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
978 bool prio_high = false, set_irq_aff = true, set_sock_mem = true;
979 int c, opt_index, vals[4] = {0}, irq;
980 uint64_t gap = 0;
981 unsigned int i;
982 char *confname = NULL, *ptr;
983 unsigned long cpus_tmp, orig_num = 0;
984 unsigned long long tx_packets, tx_bytes;
985 struct ctx ctx;
986 int min_opts = 5;
987 char **cpp_argv = NULL;
988 size_t cpp_argc = 0;
989 unsigned long long rate;
990 enum shaper_type shape_type;
991 struct timespec delay;
993 fmemset(&ctx, 0, sizeof(ctx));
994 ctx.cpus = get_number_cpus_online();
995 ctx.uid = getuid();
996 ctx.gid = getgid();
997 ctx.qdisc_path = false;
999 /* Keep an initial small default size to reduce cache-misses. */
1000 ctx.reserve_size = 512 * (1 << 10);
1002 while ((c = getopt_long(argc, argv, short_options, long_options,
1003 &opt_index)) != EOF) {
1004 switch (c) {
1005 case 'h':
1006 help();
1007 break;
1008 case 'v':
1009 version();
1010 break;
1011 case 'C':
1012 cpustats = false;
1013 break;
1014 case 'e':
1015 example();
1016 break;
1017 case 'p':
1018 invoke_cpp = true;
1019 break;
1020 case 'D':
1021 cpp_argv = argv_insert(cpp_argv, &cpp_argc, "-D");
1022 cpp_argv = argv_insert(cpp_argv, &cpp_argc, optarg);
1023 break;
1024 case 'V':
1025 ctx.verbose = true;
1026 break;
1027 case 'P':
1028 cpus_tmp = strtoul(optarg, NULL, 0);
1029 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
1030 ctx.cpus = cpus_tmp;
1031 break;
1032 case 'd':
1033 case 'o':
1034 ctx.device = xstrndup(optarg, IFNAMSIZ);
1035 break;
1036 case 'H':
1037 prio_high = true;
1038 break;
1039 case 'A':
1040 set_sock_mem = false;
1041 break;
1042 case 'Q':
1043 set_irq_aff = false;
1044 break;
1045 case 'q':
1046 ctx.qdisc_path = true;
1047 break;
1048 case 'r':
1049 ctx.rand = true;
1050 break;
1051 case 's':
1052 slow = true;
1053 ctx.cpus = 1;
1054 ctx.smoke_test = true;
1055 ctx.rhost = xstrdup(optarg);
1056 break;
1057 case 'R':
1058 ctx.rfraw = true;
1059 break;
1060 case 'J':
1061 ctx.jumbo_support = true;
1062 break;
1063 case 'c':
1064 case 'i':
1065 confname = xstrdup(optarg);
1066 if (!strncmp("-", confname, strlen("-")))
1067 ctx.cpus = 1;
1068 break;
1069 case 'u':
1070 ctx.uid = strtoul(optarg, NULL, 0);
1071 ctx.enforce = true;
1072 break;
1073 case 'g':
1074 ctx.gid = strtoul(optarg, NULL, 0);
1075 ctx.enforce = true;
1076 break;
1077 case 'k':
1078 printf("Option -k/--kernel-pull is no longer used and "
1079 "will be removed in a future release!\n");
1080 break;
1081 case 'E':
1082 seed = strtoul(optarg, NULL, 0);
1083 reseed = false;
1084 break;
1085 case 'n':
1086 orig_num = strtoul(optarg, NULL, 0);
1087 ctx.num = orig_num;
1088 break;
1089 case 't':
1090 gap = strtoul(optarg, &ptr, 0);
1091 if (!gap && optarg == ptr)
1092 panic("Invalid gap param\n");
1094 if (!strncmp(ptr, "ns", strlen("ns"))) {
1095 delay.tv_sec = gap / 1000000000;
1096 delay.tv_nsec = gap % 1000000000;
1097 } else if (*ptr == '\0' || !strncmp(ptr, "us", strlen("us"))) {
1098 /* Default to microseconds for backwards
1099 * compatibility if no postfix is given.
1101 delay.tv_sec = gap / 1000000;
1102 delay.tv_nsec = (gap % 1000000) * 1000;
1103 } else if (!strncmp(ptr, "ms", strlen("ms"))) {
1104 delay.tv_sec = gap / 1000;
1105 delay.tv_nsec = (gap % 1000) * 1000000;
1106 } else if (!strncmp(ptr, "s", strlen("s"))) {
1107 delay.tv_sec = gap;
1108 delay.tv_nsec = 0;
1109 } else {
1110 panic("Syntax error in time param!\n");
1113 shaper_set_delay(&ctx.sh, delay.tv_sec, delay.tv_nsec);
1114 break;
1115 case 'b':
1116 rate = strtoul(optarg, &ptr, 0);
1117 if (!rate || optarg == ptr)
1118 panic("Invalid rate param\n");
1120 if (strncmp(ptr, "pps", strlen("pps")) == 0) {
1121 shape_type = SHAPER_PKTS;
1122 } else if (strncmp(ptr, "B", strlen("B")) == 0) {
1123 shape_type = SHAPER_BYTES;
1124 } else if (strncmp(ptr, "kB", strlen("kB")) == 0) {
1125 shape_type = SHAPER_BYTES;
1126 rate *= 1000;
1127 } else if (strncmp(ptr, "MB", strlen("MB")) == 0) {
1128 shape_type = SHAPER_BYTES;
1129 rate *= 1000 * 1000;
1130 } else if (strncmp(ptr, "GB", strlen("GB")) == 0) {
1131 shape_type = SHAPER_BYTES;
1132 rate *= 1000 * 1000 * 1000;
1133 } else if (strncmp(ptr, "kbit", strlen("kbit")) == 0) {
1134 shape_type = SHAPER_BYTES;
1135 rate *= 1000 / 8;
1136 } else if (strncmp(ptr, "Mbit", strlen("Mbit")) == 0) {
1137 shape_type = SHAPER_BYTES;
1138 rate *= 1000 * 1000 / 8;
1139 } else if (strncmp(ptr, "Gbit", strlen("Gbit")) == 0) {
1140 shape_type = SHAPER_BYTES;
1141 rate *= 1000 * 1000 * 1000 / 8;
1142 } else if (strncmp(ptr, "KiB", strlen("KiB")) == 0) {
1143 shape_type = SHAPER_BYTES;
1144 rate *= 1 << 10;
1145 } else if (strncmp(ptr, "MiB", strlen("MiB")) == 0) {
1146 shape_type = SHAPER_BYTES;
1147 rate *= 1 << 20;
1148 } else if (strncmp(ptr, "GiB", strlen("GiB")) == 0) {
1149 shape_type = SHAPER_BYTES;
1150 rate *= 1 << 30;
1151 } else {
1152 panic("Invalid unit type for rate\n");
1155 shaper_set_rate(&ctx.sh, rate, shape_type);
1156 break;
1157 case 'S':
1158 ctx.reserve_size = strtoul(optarg, &ptr, 0);
1159 if (ctx.reserve_size == 0 && ptr == optarg)
1160 panic("Invalid ring size param\n");
1162 if (!strncmp(ptr, "KiB", strlen("KiB")))
1163 ctx.reserve_size *= 1 << 10;
1164 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1165 ctx.reserve_size = 1 << 20;
1166 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1167 ctx.reserve_size *= 1 << 30;
1168 else
1169 panic("Invalid ring size unit type\n");
1171 break;
1172 case '?':
1173 switch (optopt) {
1174 case 'd':
1175 case 'c':
1176 case 'n':
1177 case 'S':
1178 case 's':
1179 case 'P':
1180 case 'o':
1181 case 'E':
1182 case 'i':
1183 case 'k':
1184 case 'u':
1185 case 'g':
1186 case 't':
1187 panic("Option -%c requires an argument!\n",
1188 optopt);
1189 default:
1190 if (isprint(optopt))
1191 printf("Unknown option character `0x%X\'!\n", optopt);
1192 die();
1194 default:
1195 break;
1199 if (argc >= optind) {
1200 min_opts = 4;
1201 ctx.packet_str = argv2str(optind, argc, argv);
1204 if (argc < min_opts)
1205 help();
1206 if (ctx.device == NULL)
1207 panic("No networking device given!\n");
1208 if (confname == NULL && !ctx.packet_str)
1209 panic("No configuration file or packet string given!\n");
1210 if (device_mtu(ctx.device) == 0)
1211 panic("This is no networking device!\n");
1213 register_signal(SIGINT, signal_handler);
1214 register_signal(SIGQUIT, signal_handler);
1215 register_signal(SIGTERM, signal_handler);
1216 register_signal(SIGHUP, signal_handler);
1218 if (prio_high) {
1219 set_proc_prio(-20);
1220 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1223 if (set_sock_mem)
1224 set_system_socket_memory(vals, array_size(vals));
1225 xlockme();
1227 if (ctx.rfraw) {
1228 ctx.device_trans = xstrdup(ctx.device);
1229 xfree(ctx.device);
1231 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1232 panic_handler_add(on_panic_del_rfmon, ctx.device);
1233 sleep(0);
1236 if (shaper_is_set(&ctx.sh)) {
1237 prctl(PR_SET_TIMERSLACK, 1UL);
1238 /* Fall back to single core to not mess up correct timing.
1239 * We are slow anyway!
1241 ctx.cpus = 1;
1242 slow = true;
1246 * If number of packets is smaller than number of CPUs use only as
1247 * many CPUs as there are packets. Otherwise we end up sending more
1248 * packets than intended or none at all.
1250 if (ctx.num)
1251 ctx.cpus = min_t(unsigned int, ctx.num, ctx.cpus);
1253 irq = device_irq_number(ctx.device);
1254 if (set_irq_aff)
1255 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1257 stats = setup_shared_var(ctx.cpus);
1259 for (i = 0; i < ctx.cpus; i++) {
1260 pid_t pid = fork();
1262 switch (pid) {
1263 case 0:
1264 if (reseed)
1265 seed = generate_srand_seed();
1266 srand(seed);
1268 cpu_affinity(i);
1269 main_loop(&ctx, confname, slow, i, invoke_cpp,
1270 cpp_argv, orig_num);
1272 goto thread_out;
1273 case -1:
1274 panic("Cannot fork processes!\n");
1278 for (i = 0; i < ctx.cpus; i++) {
1279 int status;
1281 wait(&status);
1282 if (WEXITSTATUS(status) == EXIT_FAILURE)
1283 die();
1286 if (ctx.rfraw)
1287 leave_rfmon_mac80211(ctx.device);
1289 if (set_sock_mem)
1290 reset_system_socket_memory(vals, array_size(vals));
1292 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1293 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1294 sched_yield();
1296 tx_packets += stats[i].tx_packets;
1297 tx_bytes += stats[i].tx_bytes;
1300 fflush(stdout);
1301 printf("\n");
1302 printf("\r%12llu packets outgoing\n", tx_packets);
1303 printf("\r%12llu bytes outgoing\n", tx_bytes);
1304 for (i = 0; cpustats && i < ctx.cpus; i++) {
1305 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1306 stats[i].tv_sec, stats[i].tv_usec, i,
1307 stats[i].tx_packets);
1310 thread_out:
1311 xunlockme();
1312 destroy_shared_var(stats, ctx.cpus);
1313 if (set_irq_aff)
1314 device_restore_irq_affinity_list();
1316 argv_free(cpp_argv);
1317 free(ctx.device);
1318 free(ctx.device_trans);
1319 free(ctx.rhost);
1320 free(confname);
1321 free(ctx.packet_str);
1323 return 0;