trafgen: Don't modify optarg/argv
[netsniff-ng.git] / trafgen.c
blobea7d98333d3ec4b3a662032e8d32ab2a84efa2b2
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/stat.h>
18 #include <sys/time.h>
19 #include <sys/wait.h>
20 #include <sys/mman.h>
21 #include <net/ethernet.h>
22 #include <netinet/in.h>
23 #include <netinet/ip.h>
24 #include <linux/icmp.h>
25 #include <linux/if.h>
26 #include <arpa/inet.h>
27 #include <signal.h>
28 #include <stdint.h>
29 #include <stdlib.h>
30 #include <fcntl.h>
31 #include <time.h>
32 #include <poll.h>
33 #include <netdb.h>
34 #include <math.h>
35 #include <unistd.h>
37 #include "xmalloc.h"
38 #include "die.h"
39 #include "str.h"
40 #include "sig.h"
41 #include "sock.h"
42 #include "cpus.h"
43 #include "lockme.h"
44 #include "privs.h"
45 #include "proc.h"
46 #include "mac80211.h"
47 #include "ioops.h"
48 #include "irq.h"
49 #include "config.h"
50 #include "built_in.h"
51 #include "trafgen_conf.h"
52 #include "tprintf.h"
53 #include "timer.h"
54 #include "ring_tx.h"
55 #include "csum.h"
57 struct ctx {
58 bool rand, rfraw, jumbo_support, verbose, smoke_test, enforce, qdisc_path;
59 unsigned long kpull, num, reserve_size;
60 unsigned int cpus;
61 uid_t uid; gid_t gid;
62 char *device, *device_trans, *rhost;
63 struct timespec gap;
64 struct sockaddr_in dest;
67 struct cpu_stats {
68 unsigned long tv_sec, tv_usec;
69 unsigned long long tx_packets, tx_bytes;
70 unsigned long long cf_packets, cf_bytes;
71 unsigned long long cd_packets;
72 sig_atomic_t state;
75 static sig_atomic_t sigint = 0;
77 struct packet *packets = NULL;
78 size_t plen = 0;
80 struct packet_dyn *packet_dyn = NULL;
81 size_t dlen = 0;
83 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:CHQq";
84 static const struct option long_options[] = {
85 {"dev", required_argument, NULL, 'd'},
86 {"out", required_argument, NULL, 'o'},
87 {"in", required_argument, NULL, 'i'},
88 {"conf", required_argument, NULL, 'c'},
89 {"num", required_argument, NULL, 'n'},
90 {"gap", required_argument, NULL, 't'},
91 {"cpus", required_argument, NULL, 'P'},
92 {"ring-size", required_argument, NULL, 'S'},
93 {"kernel-pull", required_argument, NULL, 'k'},
94 {"smoke-test", required_argument, NULL, 's'},
95 {"seed", required_argument, NULL, 'E'},
96 {"user", required_argument, NULL, 'u'},
97 {"group", required_argument, NULL, 'g'},
98 {"prio-high", no_argument, NULL, 'H'},
99 {"notouch-irq", no_argument, NULL, 'Q'},
100 {"qdisc-path", no_argument, NULL, 'q'},
101 {"jumbo-support", no_argument, NULL, 'J'},
102 {"no-cpu-stats", no_argument, NULL, 'C'},
103 {"cpp", no_argument, NULL, 'p'},
104 {"rfraw", no_argument, NULL, 'R'},
105 {"rand", no_argument, NULL, 'r'},
106 {"verbose", no_argument, NULL, 'V'},
107 {"version", no_argument, NULL, 'v'},
108 {"example", no_argument, NULL, 'e'},
109 {"help", no_argument, NULL, 'h'},
110 {NULL, 0, NULL, 0}
113 static int sock;
114 static struct itimerval itimer;
115 static unsigned long interval = TX_KERNEL_PULL_INT;
116 static struct cpu_stats *stats;
117 static unsigned int seed;
119 #define CPU_STATS_STATE_CFG 1
120 #define CPU_STATS_STATE_CHK 2
121 #define CPU_STATS_STATE_RES 4
123 #ifndef ICMP_FILTER
124 # define ICMP_FILTER 1
126 struct icmp_filter {
127 __u32 data;
129 #endif
131 static void signal_handler(int number)
133 switch (number) {
134 case SIGINT:
135 sigint = 1;
136 case SIGHUP:
137 default:
138 break;
142 static void timer_elapsed(int unused __maybe_unused)
144 int ret = pull_and_flush_tx_ring(sock);
145 if (unlikely(ret < 0)) {
146 /* We could hit EBADF if the socket has been closed before
147 * the timer was triggered.
149 if (errno != EBADF && errno != ENOBUFS)
150 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
153 set_itimer_interval_value(&itimer, 0, interval);
154 setitimer(ITIMER_REAL, &itimer, NULL);
157 static void timer_purge(void)
159 int ret;
161 ret = pull_and_flush_tx_ring_wait(sock);
162 if (unlikely(ret < 0)) {
163 /* We could hit EBADF if the socket has been closed before
164 * the timer was triggered.
166 if (errno != EBADF && errno != ENOBUFS)
167 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
170 set_itimer_interval_value(&itimer, 0, 0);
171 setitimer(ITIMER_REAL, &itimer, NULL);
174 static void __noreturn help(void)
176 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
177 puts("http://www.netsniff-ng.org\n\n"
178 "Usage: trafgen [options]\n"
179 "Options:\n"
180 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
181 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
182 " -p|--cpp Run packet config through C preprocessor\n"
183 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
184 " -R|--rfraw Inject raw 802.11 frames\n"
185 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
186 " -n|--num <uint> Number of packets until exit (def: 0)\n"
187 " -r|--rand Randomize packet selection (def: round robin)\n"
188 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
189 " -t|--gap <time> Set approx. interpacket gap (s/ms/us/ns, def: us)\n"
190 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
191 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
192 " -E|--seed <uint> Manually set srand(3) seed\n"
193 " -u|--user <userid> Drop privileges and change to userid\n"
194 " -g|--group <groupid> Drop privileges and change to groupid\n"
195 " -H|--prio-high Make this high priority process\n"
196 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
197 " -q|--qdisc-path Enabled qdisc kernel path (default off since 3.14)\n"
198 " -V|--verbose Be more verbose\n"
199 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
200 " -v|--version Show version and exit\n"
201 " -e|--example Show built-in packet config example\n"
202 " -h|--help Guess what?!\n\n"
203 "Examples:\n"
204 " See trafgen.txf for configuration file examples.\n"
205 " trafgen --dev eth0 --conf trafgen.cfg\n"
206 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
207 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
208 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
209 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000us\n"
210 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
211 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n\n"
212 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
213 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
214 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
215 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
216 "Note:\n"
217 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
218 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
219 " we assume the kernel crashed, thus we print the packet and quit.\n"
220 " In case you find a ping-of-death, please mention trafgen in your\n"
221 " commit message of the fix!\n\n"
222 " For introducing bit errors, delays with random variation and more,\n"
223 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
224 " For generating different package distributions, you can use scripting\n"
225 " to generate a trafgen config file with packet ratios as:\n\n"
226 " IMIX 64:7, 570:4, 1518:1\n"
227 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
228 " Cisco 64:7, 594:4, 1518:1\n"
229 " RPR Trimodal 64:60, 512:20, 1518:20\n"
230 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
231 "Please report bugs to <bugs@netsniff-ng.org>\n"
232 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
233 "Swiss federal institute of technology (ETH Zurich)\n"
234 "License: GNU GPL version 2.0\n"
235 "This is free software: you are free to change and redistribute it.\n"
236 "There is NO WARRANTY, to the extent permitted by law.\n");
237 die();
240 static void __noreturn example(void)
242 const char *e =
243 "/* Note: dynamic elements make trafgen slower! */\n"
244 "#include <stddef.h>\n\n"
245 "{\n"
246 " /* MAC Destination */\n"
247 " fill(0xff, ETH_ALEN),\n"
248 " /* MAC Source */\n"
249 " 0x00, 0x02, 0xb3, drnd(3),\n"
250 " /* IPv4 Protocol */\n"
251 " c16(ETH_P_IP),\n"
252 " /* IPv4 Version, IHL, TOS */\n"
253 " 0b01000101, 0,\n"
254 " /* IPv4 Total Len */\n"
255 " c16(59),\n"
256 " /* IPv4 Ident */\n"
257 " drnd(2),\n"
258 " /* IPv4 Flags, Frag Off */\n"
259 " 0b01000000, 0,\n"
260 " /* IPv4 TTL */\n"
261 " 64,\n"
262 " /* Proto TCP */\n"
263 " 0x06,\n"
264 " /* IPv4 Checksum (IP header from, to) */\n"
265 " csumip(14, 33),\n"
266 " /* Source IP */\n"
267 " drnd(4),\n"
268 " /* Dest IP */\n"
269 " drnd(4),\n"
270 " /* TCP Source Port */\n"
271 " drnd(2),\n"
272 " /* TCP Dest Port */\n"
273 " c16(80),\n"
274 " /* TCP Sequence Number */\n"
275 " drnd(4),\n"
276 " /* TCP Ackn. Number */\n"
277 " c32(0),\n"
278 " /* TCP Header length + TCP SYN/ECN Flag */\n"
279 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
280 " /* Window Size */\n"
281 " c16(16),\n"
282 " /* TCP Checksum (offset IP, offset TCP) */\n"
283 " csumtcp(14, 34),\n"
284 " /* TCP Options */\n"
285 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
286 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
287 " /* Data blob */\n"
288 " \"gotcha!\",\n"
289 "}";
290 puts(e);
291 die();
294 static void __noreturn version(void)
296 printf("\ntrafgen %s, Git id: %s\n", VERSION_LONG, GITVERSION);
297 puts("multithreaded zero-copy network packet generator\n"
298 "http://www.netsniff-ng.org\n\n"
299 "Please report bugs to <bugs@netsniff-ng.org>\n"
300 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
301 "Swiss federal institute of technology (ETH Zurich)\n"
302 "License: GNU GPL version 2.0\n"
303 "This is free software: you are free to change and redistribute it.\n"
304 "There is NO WARRANTY, to the extent permitted by law.\n");
305 die();
308 static void apply_counter(int id)
310 size_t j, counter_max = packet_dyn[id].clen;
312 for (j = 0; j < counter_max; ++j) {
313 uint8_t val;
314 struct counter *counter = &packet_dyn[id].cnt[j];
316 val = counter->val - counter->min;
318 switch (counter->type) {
319 case TYPE_INC:
320 val = (val + counter->inc) % (counter->max - counter->min + 1);
321 break;
322 case TYPE_DEC:
323 val = (val - counter->inc) % (counter->min - counter->max + 1);
324 break;
325 default:
326 bug();
329 counter->val = val + counter->min;
330 packets[id].payload[counter->off] = val;
334 static void apply_randomizer(int id)
336 size_t j, rand_max = packet_dyn[id].rlen;
338 for (j = 0; j < rand_max; ++j) {
339 uint8_t val = (uint8_t) rand();
340 struct randomizer *randomizer = &packet_dyn[id].rnd[j];
342 packets[id].payload[randomizer->off] = val;
346 static void apply_csum16(int id)
348 size_t j, csum_max = packet_dyn[id].slen;
350 for (j = 0; j < csum_max; ++j) {
351 uint16_t sum = 0;
352 struct csum16 *csum = &packet_dyn[id].csum[j];
354 fmemset(&packets[id].payload[csum->off], 0, sizeof(sum));
355 if (unlikely((size_t) csum->to >= packets[id].len))
356 csum->to = packets[id].len - 1;
358 switch (csum->which) {
359 case CSUM_IP:
360 sum = calc_csum(packets[id].payload + csum->from,
361 csum->to - csum->from + 1, 0);
362 break;
363 case CSUM_UDP:
364 sum = p4_csum((void *) packets[id].payload + csum->from,
365 packets[id].payload + csum->to,
366 (packets[id].len - csum->to),
367 IPPROTO_UDP);
368 break;
369 case CSUM_TCP:
370 sum = p4_csum((void *) packets[id].payload + csum->from,
371 packets[id].payload + csum->to,
372 (packets[id].len - csum->to),
373 IPPROTO_TCP);
374 break;
375 default:
376 bug();
377 break;
380 fmemcpy(&packets[id].payload[csum->off], &sum, sizeof(sum));
384 static struct cpu_stats *setup_shared_var(unsigned long cpus)
386 int fd;
387 size_t len = cpus * sizeof(struct cpu_stats);
388 char zbuff[len], file[256];
389 struct cpu_stats *buff;
391 fmemset(zbuff, 0, len);
392 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
394 fd = creat(file, S_IRUSR | S_IWUSR);
395 bug_on(fd < 0);
396 close(fd);
398 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
399 S_IRUSR | S_IWUSR);
400 write_or_die(fd, zbuff, len);
402 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
403 MAP_SHARED, fd, 0);
404 if (buff == MAP_FAILED)
405 panic("Cannot setup shared variable!\n");
407 close(fd);
408 unlink(file);
410 memset(buff, 0, len);
411 return buff;
414 static void destroy_shared_var(void *buff, unsigned long cpus)
416 munmap(buff, cpus * sizeof(struct cpu_stats));
419 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
421 size_t i;
423 printf("{");
424 for (i = 0; i < len; ++i) {
425 if (i % 15 == 0)
426 printf("\n ");
427 printf("0x%02x, ", payload[i]);
429 printf("\n}\n");
430 fflush(stdout);
433 static int xmit_smoke_setup(struct ctx *ctx)
435 int icmp_sock, ret, ttl = 64;
436 struct icmp_filter filter;
438 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
439 if (icmp_sock < 0)
440 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
442 filter.data = ~(1 << ICMP_ECHOREPLY);
444 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
445 if (ret < 0)
446 panic("Cannot install filter!\n");
448 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
449 if (ret < 0)
450 panic("Cannot set TTL!\n");
452 memset(&ctx->dest, 0, sizeof(ctx->dest));
453 ctx->dest.sin_family = AF_INET;
454 ctx->dest.sin_port = 0;
456 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
457 if (ret < 0)
458 panic("Cannot resolv address!\n");
460 return icmp_sock;
463 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
465 int ret;
466 unsigned int i, j = 0, probes = 100;
467 short ident, cnt = 1, idstore[probes];
468 uint8_t outpack[512], *data;
469 struct icmphdr *icmp;
470 struct iphdr *ip;
471 size_t len = sizeof(*icmp) + 56;
472 struct sockaddr_in from;
473 socklen_t from_len;
474 struct pollfd fds = {
475 .fd = icmp_sock,
476 .events = POLLIN,
479 fmemset(idstore, 0, sizeof(idstore));
480 while (probes-- > 0) {
481 while ((ident = htons((short) rand())) == 0)
482 sleep(0);
483 idstore[j++] = ident;
485 memset(outpack, 0, sizeof(outpack));
486 icmp = (void *) outpack;
487 icmp->type = ICMP_ECHO;
488 icmp->un.echo.id = ident;
489 icmp->un.echo.sequence = htons(cnt++);
491 data = ((uint8_t *) outpack + sizeof(*icmp));
492 for (i = 0; i < 56; ++i)
493 data[i] = (uint8_t) rand();
495 icmp->checksum = csum((unsigned short *) outpack,
496 len / sizeof(unsigned short));
498 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
499 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
500 if (unlikely(ret != (int) len))
501 panic("Cannot send out probe: %s!\n", strerror(errno));
503 ret = poll(&fds, 1, 50);
504 if (ret < 0)
505 panic("Poll failed!\n");
507 if (fds.revents & POLLIN) {
508 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
509 (struct sockaddr *) &from, &from_len);
510 if (unlikely(ret <= 0))
511 panic("Probe receive failed!\n");
512 if (unlikely(from_len != sizeof(ctx->dest)))
513 continue;
514 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
515 continue;
516 if (unlikely((size_t) ret < sizeof(*ip) + sizeof(*icmp)))
517 continue;
518 ip = (void *) outpack;
519 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > (size_t) ret))
520 continue;
521 icmp = (void *) outpack + ip->ihl * 4;
522 for (i = 0; i < array_size(idstore); ++i) {
523 if (unlikely(icmp->un.echo.id != idstore[i]))
524 continue;
525 return 0;
530 return -1;
533 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
535 int ret, icmp_sock = -1;
536 unsigned long num = 1, i = 0;
537 struct timeval start, end, diff;
538 unsigned long long tx_bytes = 0, tx_packets = 0;
539 struct packet_dyn *pktd;
540 struct sockaddr_ll saddr = {
541 .sll_family = PF_PACKET,
542 .sll_halen = ETH_ALEN,
543 .sll_ifindex = device_ifindex(ctx->device),
546 if (ctx->num > 0)
547 num = ctx->num;
548 if (ctx->num == 0 && orig_num > 0)
549 num = 0;
551 if (ctx->smoke_test)
552 icmp_sock = xmit_smoke_setup(ctx);
554 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
556 bug_on(gettimeofday(&start, NULL));
558 while (likely(sigint == 0 && num > 0 && plen > 0)) {
559 pktd = &packet_dyn[i];
560 if (pktd->clen + pktd->rlen + pktd->slen) {
561 apply_counter(i);
562 apply_randomizer(i);
563 apply_csum16(i);
565 retry:
566 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
567 (struct sockaddr *) &saddr, sizeof(saddr));
568 if (unlikely(ret < 0)) {
569 if (errno == ENOBUFS) {
570 sched_yield();
571 goto retry;
573 if (ctx->smoke_test)
574 panic("Sendto error: %s!\n", strerror(errno));
577 tx_bytes += packets[i].len;
578 tx_packets++;
580 if (ctx->smoke_test) {
581 ret = xmit_smoke_probe(icmp_sock, ctx);
582 if (unlikely(ret < 0)) {
583 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
584 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
585 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
586 i, seed);
588 dump_trafgen_snippet(packets[i].payload, packets[i].len);
589 break;
593 if (!ctx->rand) {
594 i++;
595 if (i >= plen)
596 i = 0;
597 } else
598 i = rand() % plen;
600 if (ctx->num > 0)
601 num--;
603 if ((ctx->gap.tv_sec | ctx->gap.tv_nsec) > 0)
604 nanosleep(&ctx->gap, NULL);
607 bug_on(gettimeofday(&end, NULL));
608 timersub(&end, &start, &diff);
610 if (ctx->smoke_test)
611 close(icmp_sock);
613 stats[cpu].tx_packets = tx_packets;
614 stats[cpu].tx_bytes = tx_bytes;
615 stats[cpu].tv_sec = diff.tv_sec;
616 stats[cpu].tv_usec = diff.tv_usec;
618 stats[cpu].state |= CPU_STATS_STATE_RES;
621 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
623 int ifindex = device_ifindex(ctx->device);
624 uint8_t *out = NULL;
625 unsigned int it = 0;
626 unsigned long num = 1, i = 0, size;
627 struct ring tx_ring;
628 struct frame_map *hdr;
629 struct timeval start, end, diff;
630 struct packet_dyn *pktd;
631 unsigned long long tx_bytes = 0, tx_packets = 0;
633 fmemset(&tx_ring, 0, sizeof(tx_ring));
635 size = ring_size(ctx->device, ctx->reserve_size);
637 set_sock_prio(sock, 512);
638 set_packet_loss_discard(sock);
640 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
641 create_tx_ring(sock, &tx_ring, ctx->verbose);
642 mmap_tx_ring(sock, &tx_ring);
643 alloc_tx_ring_frames(sock, &tx_ring);
644 bind_tx_ring(sock, &tx_ring, ifindex);
646 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
648 if (ctx->kpull)
649 interval = ctx->kpull;
650 if (ctx->num > 0)
651 num = ctx->num;
652 if (ctx->num == 0 && orig_num > 0)
653 num = 0;
655 set_itimer_interval_value(&itimer, 0, interval);
656 setitimer(ITIMER_REAL, &itimer, NULL);
658 bug_on(gettimeofday(&start, NULL));
660 while (likely(sigint == 0 && num > 0 && plen > 0)) {
661 if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
662 sched_yield();
663 continue;
666 hdr = tx_ring.frames[it].iov_base;
667 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
669 hdr->tp_h.tp_snaplen = packets[i].len;
670 hdr->tp_h.tp_len = packets[i].len;
672 pktd = &packet_dyn[i];
673 if (pktd->clen + pktd->rlen + pktd->slen) {
674 apply_counter(i);
675 apply_randomizer(i);
676 apply_csum16(i);
679 fmemcpy(out, packets[i].payload, packets[i].len);
681 tx_bytes += packets[i].len;
682 tx_packets++;
684 if (!ctx->rand) {
685 i++;
686 if (i >= plen)
687 i = 0;
688 } else
689 i = rand() % plen;
691 kernel_may_pull_from_tx(&hdr->tp_h);
693 it++;
694 if (it >= tx_ring.layout.tp_frame_nr)
695 it = 0;
697 if (ctx->num > 0)
698 num--;
701 bug_on(gettimeofday(&end, NULL));
702 timersub(&end, &start, &diff);
704 timer_purge();
706 destroy_tx_ring(sock, &tx_ring);
708 stats[cpu].tx_packets = tx_packets;
709 stats[cpu].tx_bytes = tx_bytes;
710 stats[cpu].tv_sec = diff.tv_sec;
711 stats[cpu].tv_usec = diff.tv_usec;
713 stats[cpu].state |= CPU_STATS_STATE_RES;
716 static inline void __set_state(int cpu, sig_atomic_t s)
718 stats[cpu].state = s;
721 static inline sig_atomic_t __get_state(int cpu)
723 return stats[cpu].state;
726 static unsigned long __wait_and_sum_others(struct ctx *ctx, unsigned int cpu)
728 unsigned int i;
729 unsigned long total;
731 for (i = 0, total = plen; i < ctx->cpus; i++) {
732 if (i == cpu)
733 continue;
735 while ((__get_state(i) &
736 (CPU_STATS_STATE_CFG |
737 CPU_STATS_STATE_RES)) == 0 &&
738 sigint == 0)
739 sched_yield();
741 total += stats[i].cf_packets;
744 return total;
747 static void __correct_global_delta(struct ctx *ctx, unsigned int cpu, unsigned long orig)
749 unsigned int i;
750 unsigned long total;
751 int cpu_sel;
752 long long delta_correction = 0;
754 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
755 if (i == cpu)
756 continue;
758 while ((__get_state(i) &
759 (CPU_STATS_STATE_CHK |
760 CPU_STATS_STATE_RES)) == 0 &&
761 sigint == 0)
762 sched_yield();
764 total += stats[i].cd_packets;
767 if (total > orig)
768 delta_correction = -1 * ((long long) total - orig);
769 if (total < orig)
770 delta_correction = +1 * ((long long) orig - total);
772 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
773 if (stats[i].cd_packets > 0) {
774 if ((long long) stats[i].cd_packets +
775 delta_correction >= 0) {
776 cpu_sel = i;
777 break;
782 if ((int) cpu == cpu_sel)
783 ctx->num += delta_correction;
786 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
787 sig_atomic_t s)
789 stats[cpu].cf_packets = p;
790 stats[cpu].cf_bytes = b;
791 stats[cpu].state = s;
794 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
796 stats[cpu].cd_packets = p;
797 stats[cpu].state = s;
800 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
802 unsigned int i;
803 unsigned long plen_total, orig = ctx->num;
804 size_t mtu, total_len = 0;
806 bug_on(plen != dlen);
808 for (i = 0; i < plen; ++i)
809 total_len += packets[i].len;
811 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
812 plen_total = __wait_and_sum_others(ctx, cpu);
814 if (orig > 0) {
815 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
817 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
818 CPU_STATS_STATE_CFG);
819 __correct_global_delta(ctx, cpu, orig);
822 if (plen == 0) {
823 __set_state(cpu, CPU_STATS_STATE_RES);
824 return 0;
827 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
828 if (packets[i].len > mtu + 14)
829 panic("Device MTU < than packet%d's size!\n", i);
830 if (packets[i].len <= 14)
831 panic("Packet%d's size too short!\n", i);
834 return 0;
837 static void main_loop(struct ctx *ctx, char *confname, bool slow,
838 unsigned int cpu, bool invoke_cpp, unsigned long orig_num)
840 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
841 if (xmit_packet_precheck(ctx, cpu) < 0)
842 return;
844 if (cpu == 0) {
845 unsigned int i;
846 size_t total_len = 0, total_pkts = 0;
848 for (i = 0; i < ctx->cpus; ++i) {
849 total_len += stats[i].cf_bytes;
850 total_pkts += stats[i].cf_packets;
853 printf("%6zu packets to schedule\n", total_pkts);
854 printf("%6zu bytes in total\n", total_len);
855 printf("Running! Hang up with ^C!\n\n");
856 fflush(stdout);
859 sock = pf_tx_socket();
861 if (ctx->qdisc_path == false)
862 set_sock_qdisc_bypass(sock, ctx->verbose);
864 if (slow)
865 xmit_slowpath_or_die(ctx, cpu, orig_num);
866 else
867 xmit_fastpath_or_die(ctx, cpu, orig_num);
869 close(sock);
871 cleanup_packets();
874 static unsigned int generate_srand_seed(void)
876 int fd;
877 unsigned int _seed;
879 fd = open("/dev/urandom", O_RDONLY);
880 if (fd < 0)
881 return time(NULL);
883 read_or_die(fd, &_seed, sizeof(_seed));
885 close(fd);
886 return _seed;
889 int main(int argc, char **argv)
891 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
892 bool prio_high = false, set_irq_aff = true;
893 int c, opt_index, vals[4] = {0}, irq;
894 uint64_t gap = 0;
895 unsigned int i, j;
896 char *confname = NULL, *ptr;
897 unsigned long cpus_tmp, orig_num = 0;
898 unsigned long long tx_packets, tx_bytes;
899 struct ctx ctx;
901 fmemset(&ctx, 0, sizeof(ctx));
902 ctx.cpus = get_number_cpus_online();
903 ctx.uid = getuid();
904 ctx.gid = getgid();
905 ctx.qdisc_path = false;
907 while ((c = getopt_long(argc, argv, short_options, long_options,
908 &opt_index)) != EOF) {
909 switch (c) {
910 case 'h':
911 help();
912 break;
913 case 'v':
914 version();
915 break;
916 case 'C':
917 cpustats = false;
918 break;
919 case 'e':
920 example();
921 break;
922 case 'p':
923 invoke_cpp = true;
924 break;
925 case 'V':
926 ctx.verbose = true;
927 break;
928 case 'P':
929 cpus_tmp = strtoul(optarg, NULL, 0);
930 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
931 ctx.cpus = cpus_tmp;
932 break;
933 case 'd':
934 case 'o':
935 ctx.device = xstrndup(optarg, IFNAMSIZ);
936 break;
937 case 'H':
938 prio_high = true;
939 break;
940 case 'Q':
941 set_irq_aff = false;
942 break;
943 case 'q':
944 ctx.qdisc_path = true;
945 break;
946 case 'r':
947 ctx.rand = true;
948 break;
949 case 's':
950 slow = true;
951 ctx.cpus = 1;
952 ctx.smoke_test = true;
953 ctx.rhost = xstrdup(optarg);
954 break;
955 case 'R':
956 ctx.rfraw = true;
957 break;
958 case 'J':
959 ctx.jumbo_support = true;
960 break;
961 case 'c':
962 case 'i':
963 confname = xstrdup(optarg);
964 if (!strncmp("-", confname, strlen("-")))
965 ctx.cpus = 1;
966 break;
967 case 'u':
968 ctx.uid = strtoul(optarg, NULL, 0);
969 ctx.enforce = true;
970 break;
971 case 'g':
972 ctx.gid = strtoul(optarg, NULL, 0);
973 ctx.enforce = true;
974 break;
975 case 'k':
976 ctx.kpull = strtoul(optarg, NULL, 0);
977 break;
978 case 'E':
979 seed = strtoul(optarg, NULL, 0);
980 reseed = false;
981 break;
982 case 'n':
983 orig_num = strtoul(optarg, NULL, 0);
984 ctx.num = orig_num;
985 break;
986 case 't':
987 slow = true;
988 ptr = optarg;
989 gap = strtoul(optarg, NULL, 0);
991 for (j = i = strlen(optarg); i > 0; --i) {
992 if (!isdigit(optarg[j - i]))
993 break;
994 ptr++;
997 if (!strncmp(ptr, "ns", strlen("ns"))) {
998 ctx.gap.tv_sec = gap / 1000000000;
999 ctx.gap.tv_nsec = gap % 1000000000;
1000 } else if (*ptr == '\0' || !strncmp(ptr, "us", strlen("us"))) {
1001 /* Default to microseconds for backwards
1002 * compatibility if no postfix is given.
1004 ctx.gap.tv_sec = gap / 1000000;
1005 ctx.gap.tv_nsec = (gap % 1000000) * 1000;
1006 } else if (!strncmp(ptr, "ms", strlen("ms"))) {
1007 ctx.gap.tv_sec = gap / 1000;
1008 ctx.gap.tv_nsec = (gap % 1000) * 1000000;
1009 } else if (!strncmp(ptr, "s", strlen("s"))) {
1010 ctx.gap.tv_sec = gap;
1011 ctx.gap.tv_nsec = 0;
1012 } else
1013 panic("Syntax error in time param!\n");
1015 if (gap > 0)
1016 /* Fall back to single core to not mess up
1017 * correct timing. We are slow anyway!
1019 ctx.cpus = 1;
1020 break;
1021 case 'S':
1022 ptr = optarg;
1023 ctx.reserve_size = 0;
1025 for (j = i = strlen(optarg); i > 0; --i) {
1026 if (!isdigit(optarg[j - i]))
1027 break;
1028 ptr++;
1031 if (!strncmp(ptr, "KiB", strlen("KiB")))
1032 ctx.reserve_size = 1 << 10;
1033 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1034 ctx.reserve_size = 1 << 20;
1035 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1036 ctx.reserve_size = 1 << 30;
1037 else
1038 panic("Syntax error in ring size param!\n");
1040 ctx.reserve_size *= strtol(optarg, NULL, 0);
1041 break;
1042 case '?':
1043 switch (optopt) {
1044 case 'd':
1045 case 'c':
1046 case 'n':
1047 case 'S':
1048 case 's':
1049 case 'P':
1050 case 'o':
1051 case 'E':
1052 case 'i':
1053 case 'k':
1054 case 'u':
1055 case 'g':
1056 case 't':
1057 panic("Option -%c requires an argument!\n",
1058 optopt);
1059 default:
1060 if (isprint(optopt))
1061 printf("Unknown option character `0x%X\'!\n", optopt);
1062 die();
1064 default:
1065 break;
1069 if (argc < 5)
1070 help();
1071 if (ctx.device == NULL)
1072 panic("No networking device given!\n");
1073 if (confname == NULL)
1074 panic("No configuration file given!\n");
1075 if (device_mtu(ctx.device) == 0)
1076 panic("This is no networking device!\n");
1078 register_signal(SIGINT, signal_handler);
1079 register_signal(SIGHUP, signal_handler);
1080 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1082 if (prio_high) {
1083 set_proc_prio(-20);
1084 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1087 set_system_socket_memory(vals, array_size(vals));
1088 xlockme();
1090 if (ctx.rfraw) {
1091 ctx.device_trans = xstrdup(ctx.device);
1092 xfree(ctx.device);
1094 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1095 sleep(0);
1098 irq = device_irq_number(ctx.device);
1099 if (set_irq_aff)
1100 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1102 stats = setup_shared_var(ctx.cpus);
1104 for (i = 0; i < ctx.cpus; i++) {
1105 pid_t pid = fork();
1107 switch (pid) {
1108 case 0:
1109 if (reseed)
1110 seed = generate_srand_seed();
1111 srand(seed);
1113 cpu_affinity(i);
1114 main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);
1116 goto thread_out;
1117 case -1:
1118 panic("Cannot fork processes!\n");
1122 for (i = 0; i < ctx.cpus; i++) {
1123 int status;
1125 wait(&status);
1126 if (WEXITSTATUS(status) == EXIT_FAILURE)
1127 die();
1130 if (ctx.rfraw)
1131 leave_rfmon_mac80211(ctx.device);
1133 reset_system_socket_memory(vals, array_size(vals));
1135 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1136 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1137 sched_yield();
1139 tx_packets += stats[i].tx_packets;
1140 tx_bytes += stats[i].tx_bytes;
1143 fflush(stdout);
1144 printf("\n");
1145 printf("\r%12llu packets outgoing\n", tx_packets);
1146 printf("\r%12llu bytes outgoing\n", tx_bytes);
1147 for (i = 0; cpustats && i < ctx.cpus; i++) {
1148 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1149 stats[i].tv_sec, stats[i].tv_usec, i,
1150 stats[i].tx_packets);
1153 thread_out:
1154 xunlockme();
1155 destroy_shared_var(stats, ctx.cpus);
1156 if (set_irq_aff)
1157 device_restore_irq_affinity_list();
1159 free(ctx.device);
1160 free(ctx.device_trans);
1161 free(ctx.rhost);
1162 free(confname);
1164 return 0;