trafgen: ipv4: Do not use user-provided 'ihl' field to calculate csum
[netsniff-ng-new.git] / trafgen.c
blob002b01abcc87ec056e86cf60d1788ca9132b2ef6
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"
57 #include "trafgen_proto.h"
59 #ifndef timeval_to_timespec
60 #define timeval_to_timespec(tv, ts) { \
61 (ts)->tv_sec = (tv)->tv_sec; \
62 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
64 #endif
66 enum shaper_type {
67 SHAPER_NONE,
68 SHAPER_PKTS,
69 SHAPER_BYTES,
72 struct shaper {
73 enum shaper_type type;
74 unsigned long long sent;
75 unsigned long long rate;
76 struct timeval start;
77 struct timeval end;
78 struct timespec delay;
81 struct ctx {
82 bool rand, rfraw, jumbo_support, verbose, smoke_test, enforce, qdisc_path;
83 size_t reserve_size;
84 unsigned long num;
85 unsigned int cpus;
86 uid_t uid; gid_t gid;
87 char *device, *device_trans, *rhost;
88 struct sockaddr_in dest;
89 struct shaper sh;
90 char *packet_str;
93 struct cpu_stats {
94 unsigned long tv_sec, tv_usec;
95 unsigned long long tx_packets, tx_bytes;
96 unsigned long long cf_packets, cf_bytes;
97 unsigned long long cd_packets;
98 sig_atomic_t state;
101 static sig_atomic_t sigint = 0;
103 struct packet *packets = NULL;
104 size_t plen = 0;
106 struct packet_dyn *packet_dyn = NULL;
107 size_t dlen = 0;
109 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:CHQqD:b:";
110 static const struct option long_options[] = {
111 {"dev", required_argument, NULL, 'd'},
112 {"out", required_argument, NULL, 'o'},
113 {"in", required_argument, NULL, 'i'},
114 {"conf", required_argument, NULL, 'c'},
115 {"num", required_argument, NULL, 'n'},
116 {"gap", required_argument, NULL, 't'},
117 {"rate", required_argument, NULL, 'b'},
118 {"cpus", required_argument, NULL, 'P'},
119 {"ring-size", required_argument, NULL, 'S'},
120 {"kernel-pull", required_argument, NULL, 'k'},
121 {"smoke-test", required_argument, NULL, 's'},
122 {"seed", required_argument, NULL, 'E'},
123 {"user", required_argument, NULL, 'u'},
124 {"group", required_argument, NULL, 'g'},
125 {"prio-high", no_argument, NULL, 'H'},
126 {"notouch-irq", no_argument, NULL, 'Q'},
127 {"no-sock-mem", no_argument, NULL, 'A'},
128 {"qdisc-path", no_argument, NULL, 'q'},
129 {"jumbo-support", no_argument, NULL, 'J'},
130 {"no-cpu-stats", no_argument, NULL, 'C'},
131 {"cpp", no_argument, NULL, 'p'},
132 {"define", required_argument, NULL, 'D'},
133 {"rfraw", no_argument, NULL, 'R'},
134 {"rand", no_argument, NULL, 'r'},
135 {"verbose", no_argument, NULL, 'V'},
136 {"version", no_argument, NULL, 'v'},
137 {"example", no_argument, NULL, 'e'},
138 {"help", no_argument, NULL, 'h'},
139 {NULL, 0, NULL, 0}
142 static const char *copyright = "Please report bugs to <netsniff-ng@googlegroups.com>\n"
143 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
144 "Swiss federal institute of technology (ETH Zurich)\n"
145 "License: GNU GPL version 2.0\n"
146 "This is free software: you are free to change and redistribute it.\n"
147 "There is NO WARRANTY, to the extent permitted by law.";
149 static int sock;
150 static struct cpu_stats *stats;
151 static unsigned int seed;
153 #define CPU_STATS_STATE_CFG 1
154 #define CPU_STATS_STATE_CHK 2
155 #define CPU_STATS_STATE_RES 4
157 #ifndef ICMP_FILTER
158 # define ICMP_FILTER 1
160 struct icmp_filter {
161 __u32 data;
163 #endif
165 #define SMOKE_N_PROBES 100
167 #define PKT_MIN_LEN 14
169 static void signal_handler(int number)
171 switch (number) {
172 case SIGINT:
173 case SIGQUIT:
174 case SIGTERM:
175 sigint = 1;
176 case SIGHUP:
177 default:
178 break;
182 static void __noreturn help(void)
184 printf("trafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
185 puts("http://www.netsniff-ng.org\n\n"
186 "Usage: trafgen [options] [packet]\n"
187 "Options:\n"
188 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
189 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
190 " -p|--cpp Run packet config through C preprocessor\n"
191 " -D|--define Add macro/define for C preprocessor\n"
192 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
193 " -R|--rfraw Inject raw 802.11 frames\n"
194 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
195 " -n|--num <uint> Number of packets until exit (def: 0)\n"
196 " -r|--rand Randomize packet selection (def: round robin)\n"
197 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
198 " -t|--gap <time> Set approx. interpacket gap (s/ms/us/ns, def: us)\n"
199 " -b|--rate <rate> Send traffic at specified rate (pps/B/kB/MB/GB/kbit/Mbit/Gbit/KiB/MiB/GiB)\n"
200 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
201 " -E|--seed <uint> Manually set srand(3) seed\n"
202 " -u|--user <userid> Drop privileges and change to userid\n"
203 " -g|--group <groupid> Drop privileges and change to groupid\n"
204 " -H|--prio-high Make this high priority process\n"
205 " -A|--no-sock-mem Don't tune core socket memory\n"
206 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
207 " -q|--qdisc-path Enabled qdisc kernel path (default off since 3.14)\n"
208 " -V|--verbose Be more verbose\n"
209 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
210 " -v|--version Show version and exit\n"
211 " -e|--example Show built-in packet config example\n"
212 " -h|--help Guess what?!\n\n"
213 "Examples:\n"
214 " trafgen --dev eth0 --conf trafgen.cfg\n"
215 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
216 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
217 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
218 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000us\n"
219 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
220 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n"
221 " trafgen --dev eth0 '{ fill(0xff, 6), 0x00, 0x02, 0xb3, rnd(3), c16(0x0800), fill(0xca, 64) }'\n\n"
222 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
223 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
224 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
225 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
226 "Generate config files from existing pcap using netsniff-ng:\n"
227 " netsniff-ng --in dump.pcap --out dump.cfg\n\n"
228 "Note:\n"
229 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
230 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
231 " we assume the kernel crashed, thus we print the packet and quit.\n"
232 " In case you find a ping-of-death, please mention trafgen in your\n"
233 " commit message of the fix!\n\n"
234 " For introducing bit errors, delays with random variation and more,\n"
235 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
236 " For generating different package distributions, you can use scripting\n"
237 " to generate a trafgen config file with packet ratios as:\n\n"
238 " IMIX 64:7, 570:4, 1518:1\n"
239 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
240 " Cisco 64:7, 594:4, 1518:1\n"
241 " RPR Trimodal 64:60, 512:20, 1518:20\n"
242 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n");
243 puts(copyright);
244 die();
247 static void __noreturn example(void)
249 const char *e =
250 "/* Note: dynamic elements make trafgen slower! */\n"
251 "#include <stddef.h>\n\n"
252 "{\n"
253 " /* MAC Destination */\n"
254 " fill(0xff, ETH_ALEN),\n"
255 " /* MAC Source */\n"
256 " 0x00, 0x02, 0xb3, drnd(3),\n"
257 " /* IPv4 Protocol */\n"
258 " c16(ETH_P_IP),\n"
259 " /* IPv4 Version, IHL, TOS */\n"
260 " 0b01000101, 0,\n"
261 " /* IPv4 Total Len */\n"
262 " c16(59),\n"
263 " /* IPv4 Ident */\n"
264 " drnd(2),\n"
265 " /* IPv4 Flags, Frag Off */\n"
266 " 0b01000000, 0,\n"
267 " /* IPv4 TTL */\n"
268 " 64,\n"
269 " /* Proto TCP */\n"
270 " 0x06,\n"
271 " /* IPv4 Checksum (IP header from, to) */\n"
272 " csumip(14, 33),\n"
273 " /* Source IP */\n"
274 " drnd(4),\n"
275 " /* Dest IP */\n"
276 " drnd(4),\n"
277 " /* TCP Source Port */\n"
278 " drnd(2),\n"
279 " /* TCP Dest Port */\n"
280 " c16(80),\n"
281 " /* TCP Sequence Number */\n"
282 " drnd(4),\n"
283 " /* TCP Ackn. Number */\n"
284 " c32(0),\n"
285 " /* TCP Header length + TCP SYN/ECN Flag */\n"
286 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
287 " /* Window Size */\n"
288 " c16(16),\n"
289 " /* TCP Checksum (offset IP, offset TCP) */\n"
290 " csumtcp(14, 34),\n"
291 " /* TCP Options */\n"
292 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
293 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
294 " /* Data blob */\n"
295 " \"gotcha!\",\n"
296 "}";
297 puts(e);
298 die();
301 static void __noreturn version(void)
303 printf("trafgen %s, Git id: %s\n", VERSION_LONG, GITVERSION);
304 puts("multithreaded zero-copy network packet generator\n"
305 "http://www.netsniff-ng.org\n");
306 puts(copyright);
307 die();
310 static void apply_counter(int id)
312 size_t j, counter_max = packet_dyn[id].clen;
314 for (j = 0; j < counter_max; ++j) {
315 uint8_t val;
316 struct counter *counter = &packet_dyn[id].cnt[j];
318 val = counter->val - counter->min;
320 switch (counter->type) {
321 case TYPE_INC:
322 val = (val + counter->inc) % (counter->max - counter->min + 1);
323 break;
324 case TYPE_DEC:
325 val = (val - counter->inc) % (counter->min - counter->max + 1);
326 break;
327 default:
328 bug();
331 counter->val = val + counter->min;
332 packets[id].payload[counter->off] = val;
336 static void apply_randomizer(int id)
338 size_t j, rand_max = packet_dyn[id].rlen;
340 for (j = 0; j < rand_max; ++j) {
341 uint8_t val = (uint8_t) rand();
342 struct randomizer *randomizer = &packet_dyn[id].rnd[j];
344 packets[id].payload[randomizer->off] = val;
348 static void apply_csum16(int id)
350 size_t j, csum_max = packet_dyn[id].slen;
352 for (j = 0; j < csum_max; ++j) {
353 uint16_t sum = 0;
354 struct csum16 *csum = &packet_dyn[id].csum[j];
356 fmemset(&packets[id].payload[csum->off], 0, sizeof(sum));
357 if (unlikely((size_t) csum->to >= packets[id].len))
358 csum->to = packets[id].len - 1;
360 switch (csum->which) {
361 case CSUM_IP:
362 sum = calc_csum(packets[id].payload + csum->from,
363 csum->to - csum->from + 1);
364 break;
365 case CSUM_UDP:
366 sum = p4_csum((void *) packets[id].payload + csum->from,
367 packets[id].payload + csum->to,
368 (packets[id].len - csum->to),
369 IPPROTO_UDP);
370 break;
371 case CSUM_TCP:
372 sum = p4_csum((void *) packets[id].payload + csum->from,
373 packets[id].payload + csum->to,
374 (packets[id].len - csum->to),
375 IPPROTO_TCP);
376 break;
377 case CSUM_UDP6:
378 sum = p6_csum((void *) packets[id].payload + csum->from,
379 packets[id].payload + csum->to,
380 (packets[id].len - csum->to),
381 IPPROTO_UDP);
382 break;
383 case CSUM_TCP6:
384 sum = p6_csum((void *) packets[id].payload + csum->from,
385 packets[id].payload + csum->to,
386 (packets[id].len - csum->to),
387 IPPROTO_TCP);
388 break;
389 default:
390 bug();
391 break;
394 fmemcpy(&packets[id].payload[csum->off], &sum, sizeof(sum));
398 static void preprocess_packets(void)
400 size_t i;
402 for (i = 0; i < plen; i++) {
403 struct packet_dyn *pktd = &packet_dyn[i];
405 if (packet_dyn_has_only_csums(pktd)) {
406 apply_csum16(i);
407 pktd->slen = 0;
408 xfree(pktd->csum);
413 static struct cpu_stats *setup_shared_var(unsigned int cpus)
415 int fd;
416 size_t len = cpus * sizeof(struct cpu_stats);
417 char *zbuff, file[256];
418 struct cpu_stats *buff;
420 slprintf(file, sizeof(file), ".tmp_mmap.XXXXXX");
421 fd = mkostemp_or_die(file, O_RDWR | O_CREAT | O_TRUNC);
422 zbuff = xzmalloc(len);
423 write_or_die(fd, zbuff, len);
424 xfree(zbuff);
426 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
427 MAP_SHARED, fd, 0);
428 if (buff == MAP_FAILED)
429 panic("Cannot setup shared variable!\n");
431 close(fd);
432 unlink(file);
434 memset(buff, 0, len);
435 return buff;
438 static void destroy_shared_var(void *buff, unsigned int cpus)
440 munmap(buff, cpus * sizeof(struct cpu_stats));
443 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
445 size_t i;
447 printf("{");
448 for (i = 0; i < len; ++i) {
449 if (i % 15 == 0)
450 printf("\n ");
451 printf("0x%02x, ", payload[i]);
453 printf("\n}\n");
454 fflush(stdout);
457 static int xmit_smoke_setup(struct ctx *ctx)
459 int icmp_sock, ret, ttl = 64;
460 struct icmp_filter filter;
462 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
463 if (icmp_sock < 0)
464 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
466 filter.data = ~(1 << ICMP_ECHOREPLY);
468 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
469 if (ret < 0)
470 panic("Cannot install filter!\n");
472 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
473 if (ret < 0)
474 panic("Cannot set TTL!\n");
476 memset(&ctx->dest, 0, sizeof(ctx->dest));
477 ctx->dest.sin_family = AF_INET;
478 ctx->dest.sin_port = 0;
480 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
481 if (ret < 0)
482 panic("Cannot resolve address!\n");
484 return icmp_sock;
487 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
489 int ret;
490 unsigned int i, j;
491 short ident, cnt = 1, idstore[SMOKE_N_PROBES];
492 uint8_t outpack[512], *data;
493 struct icmphdr *icmp;
494 struct iphdr *ip;
495 size_t len = sizeof(*icmp) + 56;
496 struct sockaddr_in from;
497 socklen_t from_len;
498 struct pollfd fds = {
499 .fd = icmp_sock,
500 .events = POLLIN,
503 fmemset(idstore, 0, sizeof(idstore));
504 for (j = 0; j < SMOKE_N_PROBES; j++) {
505 while ((ident = htons((short) rand())) == 0)
506 sleep(0);
507 idstore[j] = ident;
509 memset(outpack, 0, sizeof(outpack));
510 icmp = (void *) outpack;
511 icmp->type = ICMP_ECHO;
512 icmp->un.echo.id = ident;
513 icmp->un.echo.sequence = htons(cnt++);
515 data = ((uint8_t *) outpack + sizeof(*icmp));
516 for (i = 0; i < 56; ++i)
517 data[i] = (uint8_t) rand();
519 icmp->checksum = csum((unsigned short *) outpack,
520 len / sizeof(unsigned short));
522 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
523 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
524 if (unlikely(ret != (int) len))
525 panic("Cannot send out probe: %s!\n", strerror(errno));
527 ret = poll(&fds, 1, 50);
528 if (ret < 0)
529 panic("Poll failed!\n");
531 if (fds.revents & POLLIN) {
532 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
533 (struct sockaddr *) &from, &from_len);
534 if (unlikely(ret <= 0))
535 panic("Probe receive failed!\n");
536 if (unlikely(from_len != sizeof(ctx->dest)))
537 continue;
538 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
539 continue;
540 if (unlikely((size_t) ret < sizeof(*ip) + sizeof(*icmp)))
541 continue;
542 ip = (void *) outpack;
543 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > (size_t) ret))
544 continue;
545 icmp = (void *) outpack + ip->ihl * 4;
546 for (i = 0; i < array_size(idstore); ++i) {
547 if (unlikely(icmp->un.echo.id != idstore[i]))
548 continue;
549 return 0;
554 return -1;
557 static bool shaper_is_set(struct shaper *sh)
559 if ((sh->delay.tv_sec | sh->delay.tv_nsec) > 0)
560 return true;
562 return sh->type != SHAPER_NONE;
565 static void shaper_init(struct shaper *sh)
567 if (sh->type == SHAPER_NONE)
568 return;
570 memset(&sh->delay, 0, sizeof(struct timespec));
571 bug_on(gettimeofday(&sh->start, NULL));
572 sh->sent = 0;
575 static void shaper_set_delay(struct shaper *sh, time_t sec, long int ns)
577 sh->delay.tv_sec = sec;
578 sh->delay.tv_nsec = ns;
581 static void shaper_set_rate(struct shaper *sh, unsigned long long rate,
582 enum shaper_type type)
584 memset(sh, 0, sizeof(struct shaper));
585 sh->rate = rate;
586 sh->type = type;
589 static void shaper_delay(struct shaper *sh, unsigned long pkt_len)
591 if (sh->type != SHAPER_NONE)
592 sh->sent += sh->type == SHAPER_BYTES ? pkt_len : 1;
594 if (sh->sent >= sh->rate && sh->rate > 0) {
595 struct timeval delay_us;
596 struct timeval time_sent;
597 struct timeval time_1s = { .tv_sec = 1 };
599 bug_on(gettimeofday(&sh->end, NULL));
600 timersub(&sh->end, &sh->start, &time_sent);
602 if (timercmp(&time_1s, &time_sent, > )) {
603 timersub(&time_1s, &time_sent, &delay_us);
604 timeval_to_timespec(&delay_us, &sh->delay);
608 if ((sh->delay.tv_sec | sh->delay.tv_nsec) > 0) {
609 nanosleep(&sh->delay, NULL);
611 shaper_init(sh);
615 static void xmit_slowpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
617 int ret, icmp_sock = -1;
618 unsigned long num = 1, i = 0;
619 struct timeval start, end, diff;
620 unsigned long long tx_bytes = 0, tx_packets = 0;
621 struct packet_dyn *pktd;
622 struct sockaddr_ll saddr = {
623 .sll_family = PF_PACKET,
624 .sll_halen = ETH_ALEN,
625 .sll_ifindex = device_ifindex(ctx->device),
628 if (ctx->num > 0)
629 num = ctx->num;
630 if (ctx->num == 0 && orig_num > 0)
631 num = 0;
633 if (ctx->smoke_test)
634 icmp_sock = xmit_smoke_setup(ctx);
636 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
638 bug_on(gettimeofday(&start, NULL));
640 if (shaper_is_set(&ctx->sh))
641 shaper_init(&ctx->sh);
643 while (likely(sigint == 0 && num > 0 && plen > 0)) {
644 pktd = &packet_dyn[i];
645 if (packet_dyn_has_elems(pktd)) {
646 apply_counter(i);
647 apply_randomizer(i);
648 apply_csum16(i);
650 retry:
651 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
652 (struct sockaddr *) &saddr, sizeof(saddr));
653 if (unlikely(ret < 0)) {
654 if (errno == ENOBUFS) {
655 sched_yield();
656 goto retry;
658 if (ctx->smoke_test)
659 panic("Sendto error: %s!\n", strerror(errno));
662 tx_bytes += packets[i].len;
663 tx_packets++;
665 if (ctx->smoke_test) {
666 ret = xmit_smoke_probe(icmp_sock, ctx);
667 if (unlikely(ret < 0)) {
668 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
669 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
670 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
671 i, seed);
673 dump_trafgen_snippet(packets[i].payload, packets[i].len);
674 break;
678 if (!ctx->rand) {
679 i++;
680 if (i >= plen)
681 i = 0;
682 } else
683 i = rand() % plen;
685 if (ctx->num > 0)
686 num--;
688 if (shaper_is_set(&ctx->sh))
689 shaper_delay(&ctx->sh, packets[i].len);
692 bug_on(gettimeofday(&end, NULL));
693 timersub(&end, &start, &diff);
695 if (ctx->smoke_test)
696 close(icmp_sock);
698 stats[cpu].tx_packets = tx_packets;
699 stats[cpu].tx_bytes = tx_bytes;
700 stats[cpu].tv_sec = diff.tv_sec;
701 stats[cpu].tv_usec = diff.tv_usec;
703 stats[cpu].state |= CPU_STATS_STATE_RES;
706 static void xmit_fastpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
708 int ifindex = device_ifindex(ctx->device);
709 uint8_t *out = NULL;
710 unsigned int it = 0;
711 unsigned long num = 1, i = 0;
712 size_t size = ring_size(ctx->device, ctx->reserve_size);
713 struct ring tx_ring;
714 struct frame_map *hdr;
715 struct timeval start, end, diff;
716 struct packet_dyn *pktd;
717 unsigned long long tx_bytes = 0, tx_packets = 0;
719 set_sock_prio(sock, 512);
721 ring_tx_setup(&tx_ring, sock, size, ifindex, ctx->jumbo_support, ctx->verbose);
723 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
725 if (ctx->num > 0)
726 num = ctx->num;
727 if (ctx->num == 0 && orig_num > 0)
728 num = 0;
730 bug_on(gettimeofday(&start, NULL));
732 while (likely(sigint == 0 && num > 0 && plen > 0)) {
733 if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
734 int ret = pull_and_flush_tx_ring(sock);
735 if (unlikely(ret < 0)) {
736 /* We could hit EBADF if the socket has been closed before
737 * the timer was triggered.
739 if (errno != EBADF && errno != ENOBUFS)
740 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
743 continue;
746 hdr = tx_ring.frames[it].iov_base;
747 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
749 hdr->tp_h.tp_snaplen = packets[i].len;
750 hdr->tp_h.tp_len = packets[i].len;
752 pktd = &packet_dyn[i];
753 if (packet_dyn_has_elems(pktd)) {
754 apply_counter(i);
755 apply_randomizer(i);
756 apply_csum16(i);
759 fmemcpy(out, packets[i].payload, packets[i].len);
761 tx_bytes += packets[i].len;
762 tx_packets++;
764 if (!ctx->rand) {
765 i++;
766 if (i >= plen)
767 i = 0;
768 } else
769 i = rand() % plen;
771 kernel_may_pull_from_tx(&hdr->tp_h);
773 it++;
774 if (it >= tx_ring.layout.tp_frame_nr)
775 it = 0;
777 if (ctx->num > 0)
778 num--;
781 bug_on(gettimeofday(&end, NULL));
782 timersub(&end, &start, &diff);
784 pull_and_flush_tx_ring_wait(sock);
785 destroy_tx_ring(sock, &tx_ring);
787 stats[cpu].tx_packets = tx_packets;
788 stats[cpu].tx_bytes = tx_bytes;
789 stats[cpu].tv_sec = diff.tv_sec;
790 stats[cpu].tv_usec = diff.tv_usec;
792 stats[cpu].state |= CPU_STATS_STATE_RES;
795 static inline void __set_state(unsigned int cpu, sig_atomic_t s)
797 stats[cpu].state = s;
800 static inline sig_atomic_t __get_state(unsigned int cpu)
802 return stats[cpu].state;
805 static unsigned long __wait_and_sum_others(struct ctx *ctx, unsigned int cpu)
807 unsigned int i;
808 unsigned long total;
810 for (i = 0, total = plen; i < ctx->cpus; i++) {
811 if (i == cpu)
812 continue;
814 while ((__get_state(i) &
815 (CPU_STATS_STATE_CFG |
816 CPU_STATS_STATE_RES)) == 0 &&
817 sigint == 0)
818 sched_yield();
820 total += stats[i].cf_packets;
823 return total;
826 static void __correct_global_delta(struct ctx *ctx, unsigned int cpu, unsigned long orig)
828 unsigned int i;
829 unsigned long total;
830 int cpu_sel;
831 long long delta_correction = 0;
833 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
834 if (i == cpu)
835 continue;
837 while ((__get_state(i) &
838 (CPU_STATS_STATE_CHK |
839 CPU_STATS_STATE_RES)) == 0 &&
840 sigint == 0)
841 sched_yield();
843 total += stats[i].cd_packets;
846 if (total > orig)
847 delta_correction = -1 * ((long long) total - orig);
848 if (total < orig)
849 delta_correction = +1 * ((long long) orig - total);
851 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
852 if (stats[i].cd_packets > 0) {
853 if ((long long) stats[i].cd_packets +
854 delta_correction >= 0) {
855 cpu_sel = i;
856 break;
861 if ((int) cpu == cpu_sel)
862 ctx->num += delta_correction;
865 static void __set_state_cf(unsigned int cpu, unsigned long p, unsigned long b,
866 sig_atomic_t s)
868 stats[cpu].cf_packets = p;
869 stats[cpu].cf_bytes = b;
870 stats[cpu].state = s;
873 static void __set_state_cd(unsigned int cpu, unsigned long p, sig_atomic_t s)
875 stats[cpu].cd_packets = p;
876 stats[cpu].state = s;
879 static void xmit_packet_precheck(struct ctx *ctx, unsigned int cpu)
881 unsigned long plen_total, orig = ctx->num;
882 size_t total_len = 0;
883 unsigned int i;
885 bug_on(plen != dlen);
887 for (i = 0; i < plen; ++i)
888 total_len += packets[i].len;
890 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
891 plen_total = __wait_and_sum_others(ctx, cpu);
893 if (orig > 0) {
894 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
896 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
897 CPU_STATS_STATE_CFG);
898 __correct_global_delta(ctx, cpu, orig);
901 if (plen == 0) {
902 __set_state(cpu, CPU_STATS_STATE_RES);
903 return;
907 static void main_loop(struct ctx *ctx, char *confname, bool slow,
908 unsigned int cpu, bool invoke_cpp, char **cpp_argv,
909 unsigned long orig_num)
911 if (ctx->packet_str)
912 compile_packets_str(ctx->packet_str, ctx->verbose, cpu);
913 else
914 compile_packets(confname, ctx->verbose, cpu, invoke_cpp, cpp_argv);
916 preprocess_packets();
918 xmit_packet_precheck(ctx, cpu);
920 if (cpu == 0) {
921 unsigned int i;
922 size_t total_len = 0, total_pkts = 0;
924 for (i = 0; i < ctx->cpus; ++i) {
925 total_len += stats[i].cf_bytes;
926 total_pkts += stats[i].cf_packets;
929 printf("%6zu packets to schedule\n", total_pkts);
930 printf("%6zu bytes in total\n", total_len);
931 printf("Running! Hang up with ^C!\n\n");
932 fflush(stdout);
935 sock = pf_socket();
937 if (ctx->qdisc_path == false)
938 set_sock_qdisc_bypass(sock, ctx->verbose);
940 if (slow)
941 xmit_slowpath_or_die(ctx, cpu, orig_num);
942 else
943 xmit_fastpath_or_die(ctx, cpu, orig_num);
945 close(sock);
947 cleanup_packets();
950 static unsigned int generate_srand_seed(void)
952 int fd;
953 unsigned int _seed;
955 fd = open("/dev/urandom", O_RDONLY);
956 if (fd < 0)
957 return time(NULL);
959 read_or_die(fd, &_seed, sizeof(_seed));
961 close(fd);
962 return _seed;
965 static void on_panic_del_rfmon(void *arg)
967 leave_rfmon_mac80211(arg);
970 int main(int argc, char **argv)
972 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
973 bool prio_high = false, set_irq_aff = true, set_sock_mem = true;
974 int c, opt_index, vals[4] = {0}, irq;
975 uint64_t gap = 0;
976 unsigned int i;
977 char *confname = NULL, *ptr;
978 unsigned long cpus_tmp, orig_num = 0;
979 unsigned long long tx_packets, tx_bytes;
980 struct ctx ctx;
981 int min_opts = 5;
982 char **cpp_argv = NULL;
983 size_t cpp_argc = 0;
984 unsigned long long rate;
985 enum shaper_type shape_type;
986 struct timespec delay;
988 fmemset(&ctx, 0, sizeof(ctx));
989 ctx.cpus = get_number_cpus_online();
990 ctx.uid = getuid();
991 ctx.gid = getgid();
992 ctx.qdisc_path = false;
994 /* Keep an initial small default size to reduce cache-misses. */
995 ctx.reserve_size = 512 * (1 << 10);
997 while ((c = getopt_long(argc, argv, short_options, long_options,
998 &opt_index)) != EOF) {
999 switch (c) {
1000 case 'h':
1001 help();
1002 break;
1003 case 'v':
1004 version();
1005 break;
1006 case 'C':
1007 cpustats = false;
1008 break;
1009 case 'e':
1010 example();
1011 break;
1012 case 'p':
1013 invoke_cpp = true;
1014 break;
1015 case 'D':
1016 cpp_argv = argv_insert(cpp_argv, &cpp_argc, "-D");
1017 cpp_argv = argv_insert(cpp_argv, &cpp_argc, optarg);
1018 break;
1019 case 'V':
1020 ctx.verbose = true;
1021 break;
1022 case 'P':
1023 cpus_tmp = strtoul(optarg, NULL, 0);
1024 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
1025 ctx.cpus = cpus_tmp;
1026 break;
1027 case 'd':
1028 case 'o':
1029 ctx.device = xstrndup(optarg, IFNAMSIZ);
1030 break;
1031 case 'H':
1032 prio_high = true;
1033 break;
1034 case 'A':
1035 set_sock_mem = false;
1036 break;
1037 case 'Q':
1038 set_irq_aff = false;
1039 break;
1040 case 'q':
1041 ctx.qdisc_path = true;
1042 break;
1043 case 'r':
1044 ctx.rand = true;
1045 break;
1046 case 's':
1047 slow = true;
1048 ctx.cpus = 1;
1049 ctx.smoke_test = true;
1050 ctx.rhost = xstrdup(optarg);
1051 break;
1052 case 'R':
1053 ctx.rfraw = true;
1054 break;
1055 case 'J':
1056 ctx.jumbo_support = true;
1057 break;
1058 case 'c':
1059 case 'i':
1060 confname = xstrdup(optarg);
1061 if (!strncmp("-", confname, strlen("-")))
1062 ctx.cpus = 1;
1063 break;
1064 case 'u':
1065 ctx.uid = strtoul(optarg, NULL, 0);
1066 ctx.enforce = true;
1067 break;
1068 case 'g':
1069 ctx.gid = strtoul(optarg, NULL, 0);
1070 ctx.enforce = true;
1071 break;
1072 case 'k':
1073 printf("Option -k/--kernel-pull is no longer used and "
1074 "will be removed in a future release!\n");
1075 break;
1076 case 'E':
1077 seed = strtoul(optarg, NULL, 0);
1078 reseed = false;
1079 break;
1080 case 'n':
1081 orig_num = strtoul(optarg, NULL, 0);
1082 ctx.num = orig_num;
1083 break;
1084 case 't':
1085 gap = strtoul(optarg, &ptr, 0);
1086 if (!gap && optarg == ptr)
1087 panic("Invalid gap param\n");
1089 if (!strncmp(ptr, "ns", strlen("ns"))) {
1090 delay.tv_sec = gap / 1000000000;
1091 delay.tv_nsec = gap % 1000000000;
1092 } else if (*ptr == '\0' || !strncmp(ptr, "us", strlen("us"))) {
1093 /* Default to microseconds for backwards
1094 * compatibility if no postfix is given.
1096 delay.tv_sec = gap / 1000000;
1097 delay.tv_nsec = (gap % 1000000) * 1000;
1098 } else if (!strncmp(ptr, "ms", strlen("ms"))) {
1099 delay.tv_sec = gap / 1000;
1100 delay.tv_nsec = (gap % 1000) * 1000000;
1101 } else if (!strncmp(ptr, "s", strlen("s"))) {
1102 delay.tv_sec = gap;
1103 delay.tv_nsec = 0;
1104 } else {
1105 panic("Syntax error in time param!\n");
1108 shaper_set_delay(&ctx.sh, delay.tv_sec, delay.tv_nsec);
1109 break;
1110 case 'b':
1111 rate = strtoul(optarg, &ptr, 0);
1112 if (!rate || optarg == ptr)
1113 panic("Invalid rate param\n");
1115 if (strncmp(ptr, "pps", strlen("pps")) == 0) {
1116 shape_type = SHAPER_PKTS;
1117 } else if (strncmp(ptr, "B", strlen("B")) == 0) {
1118 shape_type = SHAPER_BYTES;
1119 } else if (strncmp(ptr, "kB", strlen("kB")) == 0) {
1120 shape_type = SHAPER_BYTES;
1121 rate *= 1000;
1122 } else if (strncmp(ptr, "MB", strlen("MB")) == 0) {
1123 shape_type = SHAPER_BYTES;
1124 rate *= 1000 * 1000;
1125 } else if (strncmp(ptr, "GB", strlen("GB")) == 0) {
1126 shape_type = SHAPER_BYTES;
1127 rate *= 1000 * 1000 * 1000;
1128 } else if (strncmp(ptr, "kbit", strlen("kbit")) == 0) {
1129 shape_type = SHAPER_BYTES;
1130 rate *= 1000 / 8;
1131 } else if (strncmp(ptr, "Mbit", strlen("Mbit")) == 0) {
1132 shape_type = SHAPER_BYTES;
1133 rate *= 1000 * 1000 / 8;
1134 } else if (strncmp(ptr, "Gbit", strlen("Gbit")) == 0) {
1135 shape_type = SHAPER_BYTES;
1136 rate *= 1000 * 1000 * 1000 / 8;
1137 } else if (strncmp(ptr, "KiB", strlen("KiB")) == 0) {
1138 shape_type = SHAPER_BYTES;
1139 rate *= 1 << 10;
1140 } else if (strncmp(ptr, "MiB", strlen("MiB")) == 0) {
1141 shape_type = SHAPER_BYTES;
1142 rate *= 1 << 20;
1143 } else if (strncmp(ptr, "GiB", strlen("GiB")) == 0) {
1144 shape_type = SHAPER_BYTES;
1145 rate *= 1 << 30;
1146 } else {
1147 panic("Invalid unit type for rate\n");
1150 shaper_set_rate(&ctx.sh, rate, shape_type);
1151 break;
1152 case 'S':
1153 ctx.reserve_size = strtoul(optarg, &ptr, 0);
1154 if (ctx.reserve_size == 0 && ptr == optarg)
1155 panic("Invalid ring size param\n");
1157 if (!strncmp(ptr, "KiB", strlen("KiB")))
1158 ctx.reserve_size *= 1 << 10;
1159 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1160 ctx.reserve_size = 1 << 20;
1161 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1162 ctx.reserve_size *= 1 << 30;
1163 else
1164 panic("Invalid ring size unit type\n");
1166 break;
1167 case '?':
1168 switch (optopt) {
1169 case 'd':
1170 case 'c':
1171 case 'n':
1172 case 'S':
1173 case 's':
1174 case 'P':
1175 case 'o':
1176 case 'E':
1177 case 'i':
1178 case 'k':
1179 case 'u':
1180 case 'g':
1181 case 't':
1182 panic("Option -%c requires an argument!\n",
1183 optopt);
1184 default:
1185 if (isprint(optopt))
1186 printf("Unknown option character `0x%X\'!\n", optopt);
1187 die();
1189 default:
1190 break;
1194 if (argc >= optind) {
1195 min_opts = 4;
1196 ctx.packet_str = argv2str(optind, argc, argv);
1199 if (argc < min_opts)
1200 help();
1201 if (ctx.device == NULL)
1202 panic("No networking device given!\n");
1203 if (confname == NULL && !ctx.packet_str)
1204 panic("No configuration file or packet string given!\n");
1205 if (device_mtu(ctx.device) == 0)
1206 panic("This is no networking device!\n");
1208 register_signal(SIGINT, signal_handler);
1209 register_signal(SIGQUIT, signal_handler);
1210 register_signal(SIGTERM, signal_handler);
1211 register_signal(SIGHUP, signal_handler);
1213 protos_init(ctx.device);
1215 if (prio_high) {
1216 set_proc_prio(-20);
1217 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1220 if (set_sock_mem)
1221 set_system_socket_memory(vals, array_size(vals));
1222 xlockme();
1224 if (ctx.rfraw) {
1225 ctx.device_trans = xstrdup(ctx.device);
1226 xfree(ctx.device);
1228 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1229 panic_handler_add(on_panic_del_rfmon, ctx.device);
1230 sleep(0);
1233 if (shaper_is_set(&ctx.sh)) {
1234 prctl(PR_SET_TIMERSLACK, 1UL);
1235 /* Fall back to single core to not mess up correct timing.
1236 * We are slow anyway!
1238 ctx.cpus = 1;
1239 slow = true;
1243 * If number of packets is smaller than number of CPUs use only as
1244 * many CPUs as there are packets. Otherwise we end up sending more
1245 * packets than intended or none at all.
1247 if (ctx.num)
1248 ctx.cpus = min_t(unsigned int, ctx.num, ctx.cpus);
1250 irq = device_irq_number(ctx.device);
1251 if (set_irq_aff)
1252 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1254 stats = setup_shared_var(ctx.cpus);
1256 for (i = 0; i < ctx.cpus; i++) {
1257 pid_t pid = fork();
1259 switch (pid) {
1260 case 0:
1261 if (reseed)
1262 seed = generate_srand_seed();
1263 srand(seed);
1265 cpu_affinity(i);
1266 main_loop(&ctx, confname, slow, i, invoke_cpp,
1267 cpp_argv, orig_num);
1269 goto thread_out;
1270 case -1:
1271 panic("Cannot fork processes!\n");
1275 for (i = 0; i < ctx.cpus; i++) {
1276 int status;
1278 wait(&status);
1279 if (WEXITSTATUS(status) == EXIT_FAILURE)
1280 die();
1283 if (ctx.rfraw)
1284 leave_rfmon_mac80211(ctx.device);
1286 if (set_sock_mem)
1287 reset_system_socket_memory(vals, array_size(vals));
1289 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1290 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1291 sched_yield();
1293 tx_packets += stats[i].tx_packets;
1294 tx_bytes += stats[i].tx_bytes;
1297 fflush(stdout);
1298 printf("\n");
1299 printf("\r%12llu packets outgoing\n", tx_packets);
1300 printf("\r%12llu bytes outgoing\n", tx_bytes);
1301 for (i = 0; cpustats && i < ctx.cpus; i++) {
1302 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1303 stats[i].tv_sec, stats[i].tv_usec, i,
1304 stats[i].tx_packets);
1307 thread_out:
1308 xunlockme();
1309 destroy_shared_var(stats, ctx.cpus);
1310 if (set_irq_aff)
1311 device_restore_irq_affinity_list();
1313 argv_free(cpp_argv);
1314 free(ctx.device);
1315 free(ctx.device_trans);
1316 free(ctx.rhost);
1317 free(confname);
1318 free(ctx.packet_str);
1320 return 0;