src: remove trailing newline
[netsniff-ng.git] / src / trafgen.c
blob7a30bb0bac3f0c5e205f49ee7fd2d17e51d9b994
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'.
24 #include <stdio.h>
25 #include <string.h>
26 #include <getopt.h>
27 #include <ctype.h>
28 #include <stdbool.h>
29 #include <sys/socket.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/time.h>
33 #include <signal.h>
34 #include <stdint.h>
35 #include <stdlib.h>
36 #include <fcntl.h>
37 #include <time.h>
38 #include <net/ethernet.h>
40 #include "xmalloc.h"
41 #include "die.h"
42 #include "mac80211.h"
43 #include "xutils.h"
44 #include "xio.h"
45 #include "trafgen_conf.h"
46 #include "tprintf.h"
47 #include "mtrand.h"
48 #include "ring_tx.h"
50 struct stats {
51 unsigned long tx_bytes;
52 unsigned long tx_packets;
55 struct mode {
56 #define CPU_UNKNOWN -1
57 #define CPU_NOTOUCH -2
58 struct stats stats;
59 char *device;
60 char *device_trans;
61 int cpu;
62 int rand;
63 int rfraw;
64 unsigned long kpull;
65 /* 0 for automatic, > 0 for manual */
66 unsigned int reserve_size;
67 int jumbo_support;
68 int verbose;
69 unsigned long num;
70 unsigned long gap;
73 static int sock;
74 static struct itimerval itimer;
75 static unsigned long interval = TX_KERNEL_PULL_INT;
77 sig_atomic_t sigint = 0;
79 struct packet *packets = NULL;
80 unsigned int packets_len = 0;
82 struct packet_dynamics *packet_dyns = NULL;
83 unsigned int packet_dyn_len = 0;
85 static const char *short_options = "d:c:n:t:vJhS:HQb:B:rk:i:o:VRA";
86 static const struct option long_options[] = {
87 {"dev", required_argument, NULL, 'd'},
88 {"out", required_argument, NULL, 'o'},
89 {"in", required_argument, NULL, 'i'},
90 {"conf", required_argument, NULL, 'c'},
91 {"num", required_argument, NULL, 'n'},
92 {"gap", required_argument, NULL, 't'},
93 {"ring-size", required_argument, NULL, 'S'},
94 {"bind-cpu", required_argument, NULL, 'b'},
95 {"unbind-cpu", required_argument, NULL, 'B'},
96 {"kernel-pull", required_argument, NULL, 'k'},
97 {"jumbo-support", no_argument, NULL, 'J'},
98 {"rfraw", no_argument, NULL, 'R'},
99 {"rand", no_argument, NULL, 'r'},
100 {"prio-high", no_argument, NULL, 'H'},
101 {"notouch-irq", no_argument, NULL, 'Q'},
102 {"verbose", no_argument, NULL, 'V'},
103 {"no-sock-mem", no_argument, NULL, 'A'},
104 {"version", no_argument, NULL, 'v'},
105 {"help", no_argument, NULL, 'h'},
106 {NULL, 0, NULL, 0}
109 static void signal_handler(int number)
111 switch (number) {
112 case SIGINT:
113 sigint = 1;
114 break;
115 case SIGHUP:
116 default:
117 break;
121 static void timer_elapsed(int number)
123 itimer.it_interval.tv_sec = 0;
124 itimer.it_interval.tv_usec = interval;
125 itimer.it_value.tv_sec = 0;
126 itimer.it_value.tv_usec = interval;
128 pull_and_flush_tx_ring(sock);
129 setitimer(ITIMER_REAL, &itimer, NULL);
132 static void header(void)
134 printf("%s%s%s\n", colorize_start(bold), "trafgen "
135 VERSION_STRING, colorize_end());
138 static void help(void)
140 printf("\n%s %s, zero-copy network packet generator\n",
141 PROGNAME_STRING, VERSION_STRING);
142 puts("http://www.netsniff-ng.org\n\n"
143 "Usage: trafgen [options]\n"
144 "Options:\n"
145 /* " -o|-d|--out|--dev <netdev|pcap> Networking Device i.e., eth0 or pcap\n" */
146 " -o|-d|--out|--dev <netdev> Networking Device i.e., eth0\n"
147 " -i|-c|--in|--conf <cfg-file> Packet configuration file\n"
148 " -J|--jumbo-support Support for 64KB Super Jumbo Frames\n"
149 " Default TX slot: 2048Byte\n"
150 " -R|--rfraw Inject raw 802.11 frames\n"
151 " -n|--num <uint> Number of packets until exit\n"
152 " `-- 0 Loop until interrupt (default)\n"
153 " `- n Send n packets and done\n"
154 " -r|--rand Randomize packet selection process\n"
155 " Instead of a round robin selection\n"
156 " -t|--gap <uint> Interpacket gap in us (approx)\n"
157 " -A|--no-sock-mem Don't tune core socket memory\n"
158 " -S|--ring-size <size> Manually set ring size to <size>:\n"
159 " mmap space in KB/MB/GB, e.g. \'10MB\'\n"
160 " -k|--kernel-pull <uint> Kernel pull from user interval in us\n"
161 " Default is 10us where the TX_RING\n"
162 " is populated with payload from uspace\n"
163 " -b|--bind-cpu <cpu> Bind to specific CPU (or CPU-range)\n"
164 " -B|--unbind-cpu <cpu> Forbid to use specific CPU (or CPU-range)\n"
165 " -H|--prio-high Make this high priority process\n"
166 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
167 " -v|--version Show version\n"
168 " -h|--help Guess what?!\n\n"
169 "Examples:\n"
170 " See trafgen.txf for configuration file examples.\n"
171 " trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0\n"
172 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf --bind-cpu 0 -A\n"
173 " trafgen --out eth0 --in trafgen.txf --bind-cpu 0\n"
174 /* " trafgen --out test.pcap --in trafgen.txf --bind-cpu 0\n" */
175 " trafgen --dev eth0 --conf trafgen.txf --rand --gap 1000\n"
176 " trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0 --num 10 --rand\n\n"
177 "Note:\n"
178 " This tool is targeted for network developers! You should\n"
179 " be aware of what you are doing and what these options above\n"
180 " mean! Only use this tool in an isolated LAN that you own!\n\n"
181 "Please report bugs to <bugs@netsniff-ng.org>\n"
182 "Copyright (C) 2011-2012 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
183 "Swiss federal institute of technology (ETH Zurich)\n"
184 "License: GNU GPL version 2.0\n"
185 "This is free software: you are free to change and redistribute it.\n"
186 "There is NO WARRANTY, to the extent permitted by law.\n");
187 die();
190 static void version(void)
192 printf("\n%s %s, zero-copy network packet generator\n",
193 PROGNAME_STRING, VERSION_STRING);
194 puts("http://www.netsniff-ng.org\n\n"
195 "Please report bugs to <bugs@netsniff-ng.org>\n"
196 "Copyright (C) 2011-2012 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
197 "Swiss federal institute of technology (ETH Zurich)\n"
198 "License: GNU GPL version 2.0\n"
199 "This is free software: you are free to change and redistribute it.\n"
200 "There is NO WARRANTY, to the extent permitted by law.\n");
201 die();
204 static inline void apply_counter(int i)
206 int j;
208 for (j = 0; j < packet_dyns[i].counter_len; ++j) {
209 uint8_t val;
210 struct counter *counter = &packet_dyns[i].counter[j];
212 val = counter->val;
213 val -= counter->min;
215 if (counter->type == TYPE_INC)
216 val = (val + counter->inc) %
217 (counter->max - counter->min + 1);
218 else
219 val = (val - counter->inc) %
220 (counter->min - counter->max + 1);
222 val += counter->min;
223 counter->val = val;
225 packets[i].payload[counter->off] = val;
229 static inline void apply_randomizer(int i)
231 int j;
233 for (j = 0; j < packet_dyns[i].randomizer_len; ++j) {
234 uint8_t val = (uint8_t) mt_rand_int32();
235 struct randomizer *randomizer = &packet_dyns[i].randomizer[j];
237 randomizer->val = val;
238 packets[i].payload[randomizer->off] = val;
242 static void tx_precheck(struct mode *mode)
244 int i, mtu;
246 if (!mode)
247 panic("Panic over invalid args for TX trigger!\n");
248 if (packets_len == 0 || packets_len != packet_dyn_len)
249 panic("Panic over invalid args for TX trigger!\n");
250 if (!mode->rfraw && !device_up_and_running(mode->device))
251 panic("Device not up and running!\n");
253 mtu = device_mtu(mode->device);
255 for (i = 0; i < packets_len; ++i) {
256 if (packets[i].len > mtu + 14)
257 panic("Device MTU < than your packet size!\n");
258 if (packets[i].len <= 14)
259 panic("Device packet size too short!\n");
263 static void tx_slowpath_or_die(struct mode *mode)
265 int ifindex, ret;
266 unsigned int i;
267 struct sockaddr_ll s_addr;
268 unsigned long num = 1;
269 struct timeval start, end, diff;
271 tx_precheck(mode);
273 sock = pf_socket();
275 if (mode->rfraw) {
276 mode->device_trans = xstrdup(mode->device);
277 xfree(mode->device);
279 enter_rfmon_mac80211(mode->device_trans, &mode->device);
282 ifindex = device_ifindex(mode->device);
284 if (mode->num > 0)
285 num = mode->num;
286 if (mode->rand)
287 printf("Note: randomizes output makes trafgen slower!\n");
289 printf("MD: TX slowpath %s %luus", mode->rand ? "RND" : "RR", mode->gap);
290 if (mode->rfraw)
291 printf(" 802.11 raw via %s", mode->device);
292 printf("\n\n");
293 printf("Running! Hang up with ^C!\n\n");
295 fmemset(&s_addr, 0, sizeof(s_addr));
296 s_addr.sll_family = PF_PACKET;
297 s_addr.sll_halen = ETH_ALEN;
298 s_addr.sll_ifindex = ifindex;
300 i = 0;
302 gettimeofday(&start, NULL);
304 while (likely(sigint == 0) && likely(num > 0)) {
305 apply_counter(i);
306 apply_randomizer(i);
308 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
309 (struct sockaddr *) &s_addr, sizeof(s_addr));
310 if (ret < 0)
311 whine("sendto error!\n");
313 mode->stats.tx_bytes += packets[i].len;
314 mode->stats.tx_packets++;
316 if (mode->rand) {
317 i = mt_rand_int32() % packets_len;
318 } else {
319 i++;
320 atomic_cmp_swp(&i, packets_len, 0);
323 if (mode->num > 0)
324 num--;
326 usleep(mode->gap);
329 gettimeofday(&end, NULL);
330 diff = tv_subtract(end, start);
332 if (mode->rfraw)
333 leave_rfmon_mac80211(mode->device_trans, mode->device);
335 close(sock);
337 fflush(stdout);
338 printf("\n");
339 printf("\r%12lu frames outgoing\n", mode->stats.tx_packets);
340 printf("\r%12lu bytes outgoing\n", mode->stats.tx_bytes);
341 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
344 static void tx_fastpath_or_die(struct mode *mode)
346 int irq, ifindex;
347 unsigned int i, size, it = 0;
348 unsigned long num = 1;
349 uint8_t *out = NULL;
350 struct ring tx_ring;
351 struct frame_map *hdr;
352 struct timeval start, end, diff;
354 tx_precheck(mode);
356 sock = pf_socket();
358 fmemset(&tx_ring, 0, sizeof(tx_ring));
360 if (mode->rfraw) {
361 mode->device_trans = xstrdup(mode->device);
362 xfree(mode->device);
364 enter_rfmon_mac80211(mode->device_trans, &mode->device);
367 ifindex = device_ifindex(mode->device);
368 size = ring_size(mode->device, mode->reserve_size);
370 set_packet_loss_discard(sock);
371 setup_tx_ring_layout(sock, &tx_ring, size, mode->jumbo_support);
372 create_tx_ring(sock, &tx_ring);
373 mmap_tx_ring(sock, &tx_ring);
374 alloc_tx_ring_frames(&tx_ring);
375 bind_tx_ring(sock, &tx_ring, ifindex);
377 if (mode->cpu >= 0 && ifindex > 0) {
378 irq = device_irq_number(mode->device);
379 device_bind_irq_to_cpu(mode->cpu, irq);
380 printf("IRQ: %s:%d > CPU%d\n", mode->device, irq,
381 mode->cpu);
384 if (mode->kpull)
385 interval = mode->kpull;
386 if (mode->num > 0)
387 num = mode->num;
388 if (mode->rand)
389 printf("Note: randomizes output makes trafgen slower!\n");
391 printf("MD: TX fastpath %s %luus", mode->rand ? "RND" : "RR", interval);
392 if (mode->rfraw)
393 printf(" 802.11 raw via %s", mode->device);
394 printf("\n\n");
395 printf("Running! Hang up with ^C!\n\n");
397 itimer.it_interval.tv_sec = 0;
398 itimer.it_interval.tv_usec = interval;
399 itimer.it_value.tv_sec = 0;
400 itimer.it_value.tv_usec = interval;
401 setitimer(ITIMER_REAL, &itimer, NULL);
403 i = 0;
405 gettimeofday(&start, NULL);
407 while (likely(sigint == 0) && likely(num > 0)) {
408 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) &&
409 likely(num > 0)) {
410 hdr = tx_ring.frames[it].iov_base;
412 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
413 * sizeof(struct sockaddr_ll); */
414 out = ((uint8_t *) hdr) + TPACKET_HDRLEN -
415 sizeof(struct sockaddr_ll);
417 hdr->tp_h.tp_snaplen = packets[i].len;
418 hdr->tp_h.tp_len = packets[i].len;
420 apply_counter(i);
421 apply_randomizer(i);
423 fmemcpy(out, packets[i].payload, packets[i].len);
425 mode->stats.tx_bytes += packets[i].len;
426 mode->stats.tx_packets++;
428 if (mode->rand) {
429 i = mt_rand_int32() % packets_len;
430 } else {
431 i++;
432 atomic_cmp_swp(&i, packets_len, 0);
435 kernel_may_pull_from_tx(&hdr->tp_h);
436 next_slot_prewr(&it, &tx_ring);
438 if (mode->num > 0)
439 num--;
440 if (unlikely(sigint == 1))
441 break;
445 gettimeofday(&end, NULL);
446 diff = tv_subtract(end, start);
448 destroy_tx_ring(sock, &tx_ring);
450 if (mode->rfraw)
451 leave_rfmon_mac80211(mode->device_trans, mode->device);
453 close(sock);
455 fflush(stdout);
456 printf("\n");
457 printf("\r%12lu frames outgoing\n", mode->stats.tx_packets);
458 printf("\r%12lu bytes outgoing\n", mode->stats.tx_bytes);
459 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
462 static void main_loop(struct mode *mode, char *confname)
464 compile_packets(confname, mode->verbose);
466 if (mode->gap > 0)
467 tx_slowpath_or_die(mode);
468 else
469 tx_fastpath_or_die(mode);
471 cleanup_packets();
474 int main(int argc, char **argv)
476 int c, opt_index, i, j;
477 int vals[4] = {0};
478 char *confname = NULL, *ptr;
479 bool prio_high = false;
480 bool setsockmem = true;
481 struct mode mode;
483 check_for_root_maybe_die();
485 fmemset(&mode, 0, sizeof(mode));
486 mode.cpu = CPU_UNKNOWN;
487 mode.gap = 0;
488 mode.num = 0;
490 while ((c = getopt_long(argc, argv, short_options, long_options,
491 &opt_index)) != EOF) {
492 switch (c) {
493 case 'h':
494 help();
495 break;
496 case 'v':
497 version();
498 break;
499 case 'V':
500 mode.verbose = 1;
501 break;
502 case 'd':
503 case 'o':
504 mode.device = xstrndup(optarg, IFNAMSIZ);
505 break;
506 case 'r':
507 mode.rand = 1;
508 break;
509 case 'R':
510 mode.rfraw = 1;
511 break;
512 case 'J':
513 mode.jumbo_support = 1;
514 break;
515 case 'c':
516 case 'i':
517 confname = xstrdup(optarg);
518 break;
519 case 'k':
520 mode.kpull = atol(optarg);
521 break;
522 case 'n':
523 mode.num = atol(optarg);
524 break;
525 case 't':
526 mode.gap = atol(optarg);
527 break;
528 case 'A':
529 setsockmem = false;
530 break;
531 case 'S':
532 ptr = optarg;
533 mode.reserve_size = 0;
535 for (j = i = strlen(optarg); i > 0; --i) {
536 if (!isdigit(optarg[j - i]))
537 break;
538 ptr++;
541 if (!strncmp(ptr, "KB", strlen("KB")))
542 mode.reserve_size = 1 << 10;
543 else if (!strncmp(ptr, "MB", strlen("MB")))
544 mode.reserve_size = 1 << 20;
545 else if (!strncmp(ptr, "GB", strlen("GB")))
546 mode.reserve_size = 1 << 30;
547 else
548 panic("Syntax error in ring size param!\n");
549 *ptr = 0;
551 mode.reserve_size *= atoi(optarg);
552 break;
553 case 'b':
554 set_cpu_affinity(optarg, 0);
555 /* Take the first CPU for rebinding the IRQ */
556 if (mode.cpu != CPU_NOTOUCH)
557 mode.cpu = atoi(optarg);
558 break;
559 case 'B':
560 set_cpu_affinity(optarg, 1);
561 break;
562 case 'H':
563 prio_high = true;
564 break;
565 case 'Q':
566 mode.cpu = CPU_NOTOUCH;
567 break;
568 case '?':
569 switch (optopt) {
570 case 'd':
571 case 'c':
572 case 'n':
573 case 'S':
574 case 'b':
575 case 'o':
576 case 'i':
577 case 'k':
578 case 'B':
579 case 't':
580 panic("Option -%c requires an argument!\n",
581 optopt);
582 default:
583 if (isprint(optopt))
584 whine("Unknown option character "
585 "`0x%X\'!\n", optopt);
586 die();
588 default:
589 break;
593 if (argc < 5)
594 help();
595 if (mode.device == NULL)
596 panic("No networking device given!\n");
597 if (confname == NULL)
598 panic("No configuration file given!\n");
599 if (device_mtu(mode.device) == 0)
600 panic("This is no networking device!\n");
601 if (!mode.rfraw && device_up_and_running(mode.device) == 0)
602 panic("Networking device not running!\n");
604 register_signal(SIGINT, signal_handler);
605 register_signal(SIGHUP, signal_handler);
606 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
608 header();
610 if (prio_high == true) {
611 set_proc_prio(get_default_proc_prio());
612 set_sched_status(get_default_sched_policy(),
613 get_default_sched_prio());
616 if (setsockmem == true) {
617 if ((vals[0] = get_system_socket_mem(sock_rmem_max)) < SMEM_SUG_MAX)
618 set_system_socket_mem(sock_rmem_max, SMEM_SUG_MAX);
619 if ((vals[1] = get_system_socket_mem(sock_rmem_def)) < SMEM_SUG_DEF)
620 set_system_socket_mem(sock_rmem_def, SMEM_SUG_DEF);
621 if ((vals[2] = get_system_socket_mem(sock_wmem_max)) < SMEM_SUG_MAX)
622 set_system_socket_mem(sock_wmem_max, SMEM_SUG_MAX);
623 if ((vals[3] = get_system_socket_mem(sock_wmem_def)) < SMEM_SUG_DEF)
624 set_system_socket_mem(sock_wmem_def, SMEM_SUG_DEF);
627 main_loop(&mode, confname);
629 if (setsockmem == true) {
630 set_system_socket_mem(sock_rmem_max, vals[0]);
631 set_system_socket_mem(sock_rmem_def, vals[1]);
632 set_system_socket_mem(sock_wmem_max, vals[2]);
633 set_system_socket_mem(sock_wmem_def, vals[3]);
636 free(mode.device);
637 free(mode.device_trans);
638 free(confname);
640 return 0;