netsniff-ng: capture and replay support for raw 802.11 frames
[netsniff-ng-old.git] / src / trafgen.c
blobb3b3f86d2572f5519adf88534c3104c7aff85e89
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * By Daniel Borkmann <daniel@netsniff-ng.org>
4 * Copyright 2011 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,
5 * Swiss federal institute of technology (ETH Zurich)
6 * Subject to the GPL, version 2.
8 * A high-performance network traffic generator that uses the zero-copy
9 * kernelspace TX_RING for network I/O. On comodity Gigabit hardware up
10 * to 1,488,095 pps 64 Byte pps have been achieved with 2 trafgen instances
11 * bound to different CPUs from the userspace and turned off pause frames,
12 * ask Ronald from NST (Network Security Toolkit) for more details. ;-)
13 * So, this line-rate result is the very same as pktgen from kernelspace!
15 * Who can now hold the fords when the King of the Nine Riders comes? And
16 * other armies will come. I am too late. All is lost. I tarried on the
17 * way. All is lost. Even if my errand is performed, no one will ever
18 * know. There will be no one I can tell. It will be in vain.
20 * -- The Lord of the Rings, Frodo thinking,
21 * Chapter 'The Stairs of Cirith Ungol'.
26 =head1 NAME
28 trafgen - a high-performance zero-copy network packet generator
30 =head1 SYNOPSIS
32 trafgen [-d|--dev <netdev>][-c|--conf <file>][-J|--jumbo-support]
33 [-x|--interactive][-n|--num <uint>][-r|--rand][-t|--gap <usec>]
34 [-S|--ring-size <size>][-k|--kernel-pull <usec>][-b|--bind-cpu <cpu>]
35 [-B|--unbind-cpu <cpu>][-H|--prio-high][-Q|--notouch-irq][-v|--version]
36 [-h|--help]
38 =head1 DESCRIPTION
40 A high-performance network traffic generator that uses the zero-copy TX_RING
41 for network I/O. For instance, on comodity Gigabit hardware up to 1,488,095 pps
42 64 Byte pps have been achieved with trafgen.
44 =head1 OPTIONS
46 =over
48 =item trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0
50 Use packet configuration trafgen.txf, eth0 as transmission device and CPU0
51 for binding the process.
53 =back
55 =head1 OPTIONS
57 =over
59 =item -h|--help
61 Print help text and lists all options.
63 =item -v|--version
65 Print version.
67 =item -d|--dev <netdev>
69 Device for transmission i.e., eth0.
71 =item -c|--conf <conf>
73 Path to packet configuration file.
75 =item -x|--interactive
77 Start trafgen in interactive mode.
79 =item -J|--jumbo-support
81 Support for 64KB Super Jumbo Frames
83 =item -n|--num <uint>
85 Number of packets to generate before exiting.
86 0 means forever until SIGINT.
88 =item -r|--rand
90 Randomize packet selection process instead of round-robin.
92 =item -t|--gap <uint>
94 Interpacket gap in microseconds.
96 =item -S|--ring-size <size>
98 Manually set ring size to <size>: mmap space in KB/MB/GB.
100 =item -k|--kernel-pull <uint>
102 Kernel pull from user interval in microseconds.
103 Default value is 10 microseconds.
105 =item -b|--bind-cpu <cpu>
107 Bind to specific CPU (or CPU-range).
109 =item -B|--unbind-cpu <cpu>
111 Forbid to use specific CPU (or CPU-range).
113 =item -H|--prio-high
115 Make this high priority process.
117 =item -Q|--notouch-irq
119 Do not touch IRQ CPU affinity of NIC.
121 =back
123 =head1 EXAMPLES
125 =over
127 =item Generate traffic defined in trafgen.txf on eth0 using CPU 0
129 trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0
131 =item Generate traffic on eth0 using CPU 0, wait 100 us between packets
133 trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0 --gap 100
135 =item Generate 100,000 packet on eth0 using CPU 0
137 trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0 --num 100000
139 =back
141 =head1 AUTHOR
143 Written by Daniel Borkmann <daniel@netsniff-ng.org>
145 =head1 DOCUMENTATION
147 Documentation by Emmanuel Roullit <emmanuel@netsniff-ng.org>
149 =head1 BUGS
151 Please report bugs to <bugs@netsniff-ng.org>
153 =cut
157 #include <stdio.h>
158 #include <string.h>
159 #include <getopt.h>
160 #include <ctype.h>
161 #include <stdbool.h>
162 #include <sys/socket.h>
163 #include <sys/types.h>
164 #include <sys/stat.h>
165 #include <sys/time.h>
166 #include <signal.h>
167 #include <stdint.h>
168 #include <stdlib.h>
169 #include <fcntl.h>
170 #include <time.h>
171 #include <net/ethernet.h>
173 #include "xmalloc.h"
174 #include "xstring.h"
175 #include "die.h"
176 #include "xsys.h"
177 #include "xio.h"
178 #include "trafgen_conf.h"
179 #include "tprintf.h"
180 #include "mtrand.h"
181 #include "ring_tx.h"
183 struct stats {
184 unsigned long tx_bytes;
185 unsigned long tx_packets;
188 struct mode {
189 #define CPU_UNKNOWN -1
190 #define CPU_NOTOUCH -2
191 struct stats stats;
192 char *device;
193 int cpu;
194 int rand;
195 int rfraw;
196 unsigned long kpull;
197 /* 0 for automatic, > 0 for manual */
198 unsigned int reserve_size;
199 int jumbo_support;
200 int verbose;
201 unsigned long num;
202 unsigned long gap;
205 static int sock;
206 static struct itimerval itimer;
207 static unsigned long interval = TX_KERNEL_PULL_INT;
209 __export sig_atomic_t sigint = 0;
211 __export struct packet *packets = NULL;
212 __export unsigned int packets_len = 0;
213 __export struct packet_dynamics *packet_dyns = NULL;
214 __export unsigned int packet_dyn_len = 0;
216 static const char *short_options = "d:c:n:t:vJhS:HQb:B:rk:xi:o:VR";
218 static struct option long_options[] = {
219 {"dev", required_argument, 0, 'd'},
220 {"out", required_argument, 0, 'o'},
221 {"in", required_argument, 0, 'i'},
222 {"conf", required_argument, 0, 'c'},
223 {"num", required_argument, 0, 'n'},
224 {"gap", required_argument, 0, 't'},
225 {"ring-size", required_argument, 0, 'S'},
226 {"bind-cpu", required_argument, 0, 'b'},
227 {"unbind-cpu", required_argument, 0, 'B'},
228 {"kernel-pull", required_argument, 0, 'k'},
229 {"jumbo-support", no_argument, 0, 'J'},
230 {"rfraw", no_argument, 0, 'R'},
231 {"interactive", no_argument, 0, 'x'},
232 {"rand", no_argument, 0, 'r'},
233 {"prio-high", no_argument, 0, 'H'},
234 {"notouch-irq", no_argument, 0, 'Q'},
235 {"verbose", no_argument, 0, 'V'},
236 {"version", no_argument, 0, 'v'},
237 {"help", no_argument, 0, 'h'},
238 {0, 0, 0, 0}
241 static void signal_handler(int number)
243 switch (number) {
244 case SIGINT:
245 sigint = 1;
246 break;
247 case SIGHUP:
248 default:
249 break;
253 static void timer_elapsed(int number)
255 itimer.it_interval.tv_sec = 0;
256 itimer.it_interval.tv_usec = interval;
257 itimer.it_value.tv_sec = 0;
258 itimer.it_value.tv_usec = interval;
260 pull_and_flush_tx_ring(sock);
261 setitimer(ITIMER_REAL, &itimer, NULL);
264 static void header(void)
266 printf("%s%s%s\n", colorize_start(bold), "trafgen "
267 VERSION_STRING, colorize_end());
270 static void help(void)
272 printf("\ntrafgen %s, high-perf zero-copy network packet generator\n",
273 VERSION_STRING);
274 printf("http://www.netsniff-ng.org\n\n");
275 printf("Usage: trafgen [options]\n");
276 printf("Options:\n");
277 printf(" -o|-d|--out|--dev <netdev|pcap> Networking Device i.e., eth0 or pcap\n");
278 printf(" -i|-c|--in|--conf <cfg-file> Packet configuration file\n");
279 printf(" -x|--interactive Start trafgen in interactive server mode\n");
280 printf(" -J|--jumbo-support Support for 64KB Super Jumbo Frames\n");
281 printf(" Default TX slot: 2048Byte\n");
282 printf(" -R|--rfraw Inject raw 802.11 frames\n");
283 printf(" -n|--num <uint> Number of packets until exit\n");
284 printf(" `-- 0 Loop until interrupt (default)\n");
285 printf(" `- n Send n packets and done\n");
286 printf(" -r|--rand Randomize packet selection process\n");
287 printf(" Instead of a round robin selection\n");
288 printf(" -t|--gap <uint> Interpacket gap in us (approx)\n");
289 printf(" -S|--ring-size <size> Manually set ring size to <size>:\n");
290 printf(" mmap space in KB/MB/GB, e.g. \'10MB\'\n");
291 printf(" -k|--kernel-pull <uint> Kernel pull from user interval in us\n");
292 printf(" Default is 10us where the TX_RING\n");
293 printf(" is populated with payload from uspace\n");
294 printf(" -b|--bind-cpu <cpu> Bind to specific CPU (or CPU-range)\n");
295 printf(" -B|--unbind-cpu <cpu> Forbid to use specific CPU (or CPU-range)\n");
296 printf(" -H|--prio-high Make this high priority process\n");
297 printf(" -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n");
298 printf(" -v|--version Show version\n");
299 printf(" -h|--help Guess what?!\n");
300 printf("\n");
301 printf("Examples:\n");
302 printf(" See trafgen.txf for configuration file examples.\n");
303 printf(" trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0\n");
304 printf(" trafgen --dev wlan0 --rfraw --conf beacon-test.txf --bind-cpu 0\n");
305 printf(" trafgen --out eth0 --in trafgen.txf --bind-cpu 0\n");
306 printf(" trafgen --out test.pcap --in trafgen.txf --bind-cpu 0\n");
307 printf(" trafgen --dev eth0 --conf trafgen.txf --rand --gap 1000\n");
308 printf(" trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0 --num 10 --rand\n");
309 printf(" trafgen --interactive\n");
310 printf(" trafgen --interactive --dev mgmt0 (only start server on mgmt0)\n");
311 printf(" trafgen --interactive --conf trafgen-cli.batch\n");
312 printf("\n");
313 printf("Note:\n");
314 printf(" This tool is targeted for network developers! You should\n");
315 printf(" be aware of what you are doing and what these options above\n");
316 printf(" mean! Only use this tool in an isolated LAN that you own!\n");
317 printf("\n");
318 printf("Please report bugs to <bugs@netsniff-ng.org>\n");
319 printf("Copyright (C) 2011-2012 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n");
320 printf("Swiss federal institute of technology (ETH Zurich)\n");
321 printf("License: GNU GPL version 2\n");
322 printf("This is free software: you are free to change and redistribute it.\n");
323 printf("There is NO WARRANTY, to the extent permitted by law.\n\n");
324 die();
327 static void version(void)
329 printf("\ntrafgen %s, high-perf zero-copy network packet generator\n",
330 VERSION_STRING);
331 printf("http://www.netsniff-ng.org\n\n");
332 printf("Please report bugs to <bugs@netsniff-ng.org>\n");
333 printf("Copyright (C) 2011-2012 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n");
334 printf("Swiss federal institute of technology (ETH Zurich)\n");
335 printf("License: GNU GPL version 2\n");
336 printf("This is free software: you are free to change and redistribute it.\n");
337 printf("There is NO WARRANTY, to the extent permitted by law.\n\n");
338 die();
341 static inline void apply_counter(int i)
343 int j;
345 for (j = 0; j < packet_dyns[i].counter_len; ++j) {
346 uint8_t val;
347 struct counter *counter = &packet_dyns[i].counter[j];
349 val = counter->val;
350 val -= counter->min;
352 if (counter->type == TYPE_INC)
353 val = (val + counter->inc) %
354 (counter->max - counter->min + 1);
355 else
356 val = (val - counter->inc) %
357 (counter->min - counter->max + 1);
359 val += counter->min;
360 counter->val = val;
362 packets[i].payload[counter->off] = val;
366 static inline void apply_randomizer(int i)
368 int j;
370 for (j = 0; j < packet_dyns[i].randomizer_len; ++j) {
371 uint8_t val = (uint8_t) mt_rand_int32();
372 struct randomizer *randomizer = &packet_dyns[i].randomizer[j];
374 randomizer->val = val;
375 packets[i].payload[randomizer->off] = val;
379 static void tx_precheck(struct mode *mode)
381 int i, mtu;
383 if (!mode)
384 panic("Panic over invalid args for TX trigger!\n");
385 if (packets_len == 0 || packets_len != packet_dyn_len)
386 panic("Panic over invalid args for TX trigger!\n");
387 if (!device_up_and_running(mode->device))
388 panic("Device not up and running!\n");
390 mtu = device_mtu(mode->device);
392 for (i = 0; i < packets_len; ++i) {
393 if (packets[i].len > mtu + 14)
394 panic("Device MTU < than your packet size!\n");
395 if (packets[i].len <= 14)
396 panic("Device packet size too short!\n");
400 static void tx_slowpath_or_die(struct mode *mode)
402 int ifindex, ret;
403 unsigned int i;
404 struct sockaddr_ll s_addr;
405 unsigned long num = 1;
407 tx_precheck(mode);
409 sock = pf_socket();
411 ifindex = device_ifindex(mode->device);
413 if (mode->num > 0)
414 num = mode->num;
415 if (mode->rand)
416 printf("Note: randomizes output makes trafgen slower!\n");
418 printf("MD: TX slowpath %s %luus %s\n\n", mode->rand ? "RND" : "RR",
419 mode->gap, mode->rfraw ? "802.11raw" : "");
420 printf("Running! Hang up with ^C!\n\n");
422 fmemset(&s_addr, 0, sizeof(s_addr));
423 s_addr.sll_family = PF_PACKET;
424 s_addr.sll_halen = ETH_ALEN;
425 s_addr.sll_ifindex = ifindex;
427 i = 0;
429 while (likely(sigint == 0) && likely(num > 0)) {
430 apply_counter(i);
431 apply_randomizer(i);
433 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
434 (struct sockaddr *) &s_addr, sizeof(s_addr));
435 if (ret < 0)
436 whine("sendto error!\n");
438 mode->stats.tx_bytes += packets[i].len;
439 mode->stats.tx_packets++;
441 if (mode->rand) {
442 i = mt_rand_int32() % packets_len;
443 } else {
444 i++;
445 atomic_cmp_swp(&i, packets_len, 0);
448 if (mode->num > 0)
449 num--;
451 usleep(mode->gap);
454 close(sock);
456 fflush(stdout);
457 printf("\n");
458 printf("\r%12lu frames outgoing\n", mode->stats.tx_packets);
459 printf("\r%12lu bytes outgoing\n", mode->stats.tx_bytes);
462 static void tx_fastpath_or_die(struct mode *mode)
464 int irq, ifindex;
465 unsigned int i, size, it = 0;
466 unsigned long num = 1;
467 uint8_t *out = NULL;
468 struct ring tx_ring;
469 struct frame_map *hdr;
471 tx_precheck(mode);
473 sock = pf_socket();
475 fmemset(&tx_ring, 0, sizeof(tx_ring));
476 ifindex = device_ifindex(mode->device);
477 size = ring_size(mode->device, mode->reserve_size);
479 set_packet_loss_discard(sock);
480 setup_tx_ring_layout(sock, &tx_ring, size, mode->jumbo_support);
481 create_tx_ring(sock, &tx_ring);
482 mmap_tx_ring(sock, &tx_ring);
483 alloc_tx_ring_frames(&tx_ring);
484 bind_tx_ring(sock, &tx_ring, ifindex);
486 if (mode->cpu >= 0 && ifindex > 0) {
487 irq = device_irq_number(mode->device);
488 device_bind_irq_to_cpu(mode->cpu, irq);
489 printf("IRQ: %s:%d > CPU%d\n", mode->device, irq,
490 mode->cpu);
493 if (mode->kpull)
494 interval = mode->kpull;
495 if (mode->num > 0)
496 num = mode->num;
497 if (mode->rand)
498 printf("Note: randomizes output makes trafgen slower!\n");
500 printf("MD: TX fastpath %s %luus %s\n\n", mode->rand ? "RND" : "RR",
501 interval, mode->rfraw ? "802.11raw" : "");
502 printf("Running! Hang up with ^C!\n\n");
504 itimer.it_interval.tv_sec = 0;
505 itimer.it_interval.tv_usec = interval;
506 itimer.it_value.tv_sec = 0;
507 itimer.it_value.tv_usec = interval;
508 setitimer(ITIMER_REAL, &itimer, NULL);
510 i = 0;
512 while (likely(sigint == 0) && likely(num > 0)) {
513 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) &&
514 likely(num > 0)) {
515 hdr = tx_ring.frames[it].iov_base;
517 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
518 * sizeof(struct sockaddr_ll); */
519 out = ((uint8_t *) hdr) + TPACKET_HDRLEN -
520 sizeof(struct sockaddr_ll);
522 hdr->tp_h.tp_snaplen = packets[i].len;
523 hdr->tp_h.tp_len = packets[i].len;
525 apply_counter(i);
526 apply_randomizer(i);
528 fmemcpy(out, packets[i].payload, packets[i].len);
530 mode->stats.tx_bytes += packets[i].len;
531 mode->stats.tx_packets++;
533 if (mode->rand) {
534 i = mt_rand_int32() % packets_len;
535 } else {
536 i++;
537 atomic_cmp_swp(&i, packets_len, 0);
540 kernel_may_pull_from_tx(&hdr->tp_h);
541 next_slot_prewr(&it, &tx_ring);
543 if (mode->num > 0)
544 num--;
545 if (unlikely(sigint == 1))
546 break;
550 destroy_tx_ring(sock, &tx_ring);
551 close(sock);
553 fflush(stdout);
554 printf("\n");
555 printf("\r%12lu frames outgoing\n", mode->stats.tx_packets);
556 printf("\r%12lu bytes outgoing\n", mode->stats.tx_bytes);
559 static void main_loop(struct mode *mode, char *confname)
561 compile_packets(confname, mode->verbose);
563 if (mode->gap > 0)
564 tx_slowpath_or_die(mode);
565 else
566 tx_fastpath_or_die(mode);
568 cleanup_packets();
571 int main(int argc, char **argv)
573 int c, opt_index, i, j, interactive = 0;
574 char *confname = NULL, *ptr;
575 bool prio_high = false;
576 struct mode mode;
578 check_for_root_maybe_die();
580 fmemset(&mode, 0, sizeof(mode));
581 mode.cpu = CPU_UNKNOWN;
582 mode.gap = 0;
583 mode.num = 0;
585 while ((c = getopt_long(argc, argv, short_options, long_options,
586 &opt_index)) != EOF) {
587 switch (c) {
588 case 'h':
589 help();
590 break;
591 case 'v':
592 version();
593 break;
594 case 'V':
595 mode.verbose = 1;
596 break;
597 case 'd':
598 case 'o':
599 mode.device = xstrndup(optarg, IFNAMSIZ);
600 break;
601 case 'x':
602 interactive = 1;
603 break;
604 case 'r':
605 mode.rand = 1;
606 break;
607 case 'R':
608 mode.rfraw = 1;
609 break;
610 case 'J':
611 mode.jumbo_support = 1;
612 break;
613 case 'c':
614 case 'i':
615 confname = xstrdup(optarg);
616 break;
617 case 'k':
618 mode.kpull = atol(optarg);
619 break;
620 case 'n':
621 mode.num = atol(optarg);
622 break;
623 case 't':
624 mode.gap = atol(optarg);
625 break;
626 case 'S':
627 ptr = optarg;
628 mode.reserve_size = 0;
630 for (j = i = strlen(optarg); i > 0; --i) {
631 if (!isdigit(optarg[j - i]))
632 break;
633 ptr++;
636 if (!strncmp(ptr, "KB", strlen("KB")))
637 mode.reserve_size = 1 << 10;
638 else if (!strncmp(ptr, "MB", strlen("MB")))
639 mode.reserve_size = 1 << 20;
640 else if (!strncmp(ptr, "GB", strlen("GB")))
641 mode.reserve_size = 1 << 30;
642 else
643 panic("Syntax error in ring size param!\n");
644 *ptr = 0;
646 mode.reserve_size *= atoi(optarg);
647 break;
648 case 'b':
649 set_cpu_affinity(optarg, 0);
650 /* Take the first CPU for rebinding the IRQ */
651 if (mode.cpu != CPU_NOTOUCH)
652 mode.cpu = atoi(optarg);
653 break;
654 case 'B':
655 set_cpu_affinity(optarg, 1);
656 break;
657 case 'H':
658 prio_high = true;
659 break;
660 case 'Q':
661 mode.cpu = CPU_NOTOUCH;
662 break;
663 case '?':
664 switch (optopt) {
665 case 'd':
666 case 'c':
667 case 'n':
668 case 'S':
669 case 'b':
670 case 'o':
671 case 'i':
672 case 'k':
673 case 'B':
674 case 't':
675 panic("Option -%c requires an argument!\n",
676 optopt);
677 default:
678 if (isprint(optopt))
679 whine("Unknown option character "
680 "`0x%X\'!\n", optopt);
681 die();
683 default:
684 break;
688 if (!interactive && argc < 5)
689 help();
690 if (interactive && argc < 2)
691 help();
692 if (!interactive && mode.device == NULL)
693 panic("No networking device given!\n");
694 if (!interactive && confname == NULL)
695 panic("No configuration file given!\n");
696 if (!interactive && device_mtu(mode.device) == 0)
697 panic("This is no networking device!\n");
698 if (!interactive && device_up_and_running(mode.device) == 0)
699 panic("Networking device not running!\n");
701 register_signal(SIGINT, signal_handler);
702 register_signal(SIGHUP, signal_handler);
703 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
705 header();
707 if (prio_high == true) {
708 set_proc_prio(get_default_proc_prio());
709 set_sched_status(get_default_sched_policy(),
710 get_default_sched_prio());
713 if (interactive)
714 main_loop_interactive(&mode, confname);
715 else
716 main_loop(&mode, confname);
718 if (mode.device)
719 xfree(mode.device);
720 if (confname)
721 xfree(confname);
723 return 0;