netsniff-ng: refactor the code a bit
[netsniff-ng.git] / src / trafgen.c
blob6b445ef3f800aa90ac21d801fa8586745f0d99fc
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * By Daniel Borkmann <daniel@netsniff-ng.org>
4 * Copyright 2011 - 2013 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 "built_in.h"
46 #include "trafgen_conf.h"
47 #include "tprintf.h"
48 #include "ring_tx.h"
50 struct ctx {
51 char *device, *device_trans;
52 int cpu, rand, rfraw, jumbo_support, verbose;
53 unsigned long kpull, num, gap, reserve_size;
54 unsigned long tx_bytes, tx_packets;
57 sig_atomic_t sigint = 0;
59 struct packet *packets = NULL;
60 size_t plen = 0;
62 struct packet_dyn *packet_dyn = NULL;
63 size_t dlen = 0;
65 static const char *short_options = "d:c:n:t:vJhS:HQb:B:rk:i:o:VRA";
66 static const struct option long_options[] = {
67 {"dev", required_argument, NULL, 'd'},
68 {"out", required_argument, NULL, 'o'},
69 {"in", required_argument, NULL, 'i'},
70 {"conf", required_argument, NULL, 'c'},
71 {"num", required_argument, NULL, 'n'},
72 {"gap", required_argument, NULL, 't'},
73 {"ring-size", required_argument, NULL, 'S'},
74 {"bind-cpu", required_argument, NULL, 'b'},
75 {"unbind-cpu", required_argument, NULL, 'B'},
76 {"kernel-pull", required_argument, NULL, 'k'},
77 {"jumbo-support", no_argument, NULL, 'J'},
78 {"rfraw", no_argument, NULL, 'R'},
79 {"rand", no_argument, NULL, 'r'},
80 {"prio-high", no_argument, NULL, 'H'},
81 {"notouch-irq", no_argument, NULL, 'Q'},
82 {"verbose", no_argument, NULL, 'V'},
83 {"no-sock-mem", no_argument, NULL, 'A'},
84 {"version", no_argument, NULL, 'v'},
85 {"help", no_argument, NULL, 'h'},
86 {NULL, 0, NULL, 0}
89 static int sock;
91 static struct itimerval itimer;
93 static unsigned long interval = TX_KERNEL_PULL_INT;
95 #define set_system_socket_memory(vals) \
96 do { \
97 if ((vals[0] = get_system_socket_mem(sock_rmem_max)) < SMEM_SUG_MAX) \
98 set_system_socket_mem(sock_rmem_max, SMEM_SUG_MAX); \
99 if ((vals[1] = get_system_socket_mem(sock_rmem_def)) < SMEM_SUG_DEF) \
100 set_system_socket_mem(sock_rmem_def, SMEM_SUG_DEF); \
101 if ((vals[2] = get_system_socket_mem(sock_wmem_max)) < SMEM_SUG_MAX) \
102 set_system_socket_mem(sock_wmem_max, SMEM_SUG_MAX); \
103 if ((vals[3] = get_system_socket_mem(sock_wmem_def)) < SMEM_SUG_DEF) \
104 set_system_socket_mem(sock_wmem_def, SMEM_SUG_DEF); \
105 } while (0)
107 #define reset_system_socket_memory(vals) \
108 do { \
109 set_system_socket_mem(sock_rmem_max, vals[0]); \
110 set_system_socket_mem(sock_rmem_def, vals[1]); \
111 set_system_socket_mem(sock_wmem_max, vals[2]); \
112 set_system_socket_mem(sock_wmem_def, vals[3]); \
113 } while (0)
115 static void signal_handler(int number)
117 switch (number) {
118 case SIGINT:
119 sigint = 1;
120 case SIGHUP:
121 default:
122 break;
126 static void timer_elapsed(int number)
128 itimer.it_interval.tv_sec = 0;
129 itimer.it_interval.tv_usec = interval;
131 itimer.it_value.tv_sec = 0;
132 itimer.it_value.tv_usec = interval;
134 pull_and_flush_tx_ring(sock);
135 setitimer(ITIMER_REAL, &itimer, NULL);
138 static void header(void)
140 printf("%s%s%s\n", colorize_start(bold), "trafgen " VERSION_STRING, colorize_end());
143 static void help(void)
145 printf("\ntrafgen %s, zero-copy network packet generator\n", VERSION_STRING);
146 puts("http://www.netsniff-ng.org\n\n"
147 "Usage: trafgen [options]\n"
148 "Options:\n"
149 /* " -o|-d|--out|--dev <netdev|pcap> Networking Device i.e., eth0 or pcap\n" */
150 " -o|-d|--out|--dev <netdev> Networking Device i.e., eth0\n"
151 " -i|-c|--in|--conf <cfg-file> Packet configuration file\n"
152 " -J|--jumbo-support Support for 64KB Super Jumbo Frames\n"
153 " Default TX slot: 2048Byte\n"
154 " -R|--rfraw Inject raw 802.11 frames\n"
155 " -n|--num <uint> Number of packets until exit\n"
156 " `-- 0 Loop until interrupt (default)\n"
157 " `- n Send n packets and done\n"
158 " -r|--rand Randomize packet selection process\n"
159 " Instead of a round robin selection\n"
160 " -t|--gap <uint> Interpacket gap in us (approx)\n"
161 " -A|--no-sock-mem Don't tune core socket memory\n"
162 " -S|--ring-size <size> Manually set ring size to <size>:\n"
163 " mmap space in KB/MB/GB, e.g. \'10MB\'\n"
164 " -k|--kernel-pull <uint> Kernel pull from user interval in us\n"
165 " Default is 10us where the TX_RING\n"
166 " is populated with payload from uspace\n"
167 " -b|--bind-cpu <cpu> Bind to specific CPU (or CPU-range)\n"
168 " -B|--unbind-cpu <cpu> Forbid to use specific CPU (or CPU-range)\n"
169 " -H|--prio-high Make this high priority process\n"
170 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
171 " -V|--verbose Be more verbose\n"
172 " -v|--version Show version\n"
173 " -h|--help Guess what?!\n\n"
174 "Examples:\n"
175 " See trafgen.txf for configuration file examples.\n"
176 " trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0\n"
177 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf --bind-cpu 0 -A -V\n"
178 " trafgen --out eth0 --in trafgen.txf --bind-cpu 0\n"
179 /* " trafgen --out test.pcap --in trafgen.txf --bind-cpu 0\n" */
180 " trafgen --dev eth0 --conf trafgen.txf --rand --gap 1000\n"
181 " trafgen --dev eth0 --conf trafgen.txf --rand --num 1400000 -k1000\n"
182 " trafgen --dev eth0 --conf trafgen.txf --bind-cpu 0 --num 10 --rand\n\n"
183 "Note:\n"
184 " This tool is targeted for network developers! You should\n"
185 " be aware of what you are doing and what these options above\n"
186 " mean! Only use this tool in an isolated LAN that you own!\n\n"
187 "Please report bugs to <bugs@netsniff-ng.org>\n"
188 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
189 "Swiss federal institute of technology (ETH Zurich)\n"
190 "License: GNU GPL version 2.0\n"
191 "This is free software: you are free to change and redistribute it.\n"
192 "There is NO WARRANTY, to the extent permitted by law.\n");
193 die();
196 static void version(void)
198 printf("\ntrafgen %s, zero-copy network packet generator\n", VERSION_STRING);
199 puts("http://www.netsniff-ng.org\n\n"
200 "Please report bugs to <bugs@netsniff-ng.org>\n"
201 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
202 "Swiss federal institute of technology (ETH Zurich)\n"
203 "License: GNU GPL version 2.0\n"
204 "This is free software: you are free to change and redistribute it.\n"
205 "There is NO WARRANTY, to the extent permitted by law.\n");
206 die();
209 static inline void apply_counter(int counter_id)
211 int j;
212 size_t counter_max = packet_dyn[counter_id].clen;
214 for (j = 0; j < counter_max; ++j) {
215 uint8_t val;
216 struct counter *counter;
218 counter = &packet_dyn[counter_id].cnt[j];
219 val = counter->val - counter->min;
221 switch (counter->type) {
222 case TYPE_INC:
223 val = (val + counter->inc) % (counter->max - counter->min + 1);
224 break;
225 case TYPE_DEC:
226 val = (val - counter->inc) % (counter->min - counter->max + 1);
227 break;
228 default:
229 bug();
232 counter->val = val + counter->min;
233 packets[counter_id].payload[counter->off] = val;
237 static inline void apply_randomizer(int rand_id)
239 int j;
240 size_t rand_max = packet_dyn[rand_id].rlen;
242 for (j = 0; j < rand_max; ++j) {
243 uint8_t val;
244 struct randomizer *randomizer;
246 val = (uint8_t) rand();
248 randomizer = &packet_dyn[rand_id].rnd[j];
249 randomizer->val = val;
251 packets[rand_id].payload[randomizer->off] = val;
255 static void xmit_precheck(const struct ctx *ctx)
257 int i;
258 size_t mtu;
260 if (!ctx)
261 panic("Panic, invalid args for TX trigger!\n");
262 if (plen == 0 || plen != dlen)
263 panic("Panic, invalid args for TX trigger!\n");
264 if (!ctx->rfraw && !device_up_and_running(ctx->device))
265 panic("Device not up and running!\n");
266 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
267 if (packets[i].len > mtu + 14)
268 panic("Device MTU < than your packet size!\n");
269 if (packets[i].len <= 14)
270 panic("Device packet size too short!\n");
274 static void xmit_slowpath_or_die(struct ctx *ctx)
276 int ret;
277 unsigned long num = 1, i = 0;
278 struct timeval start, end, diff;
279 struct sockaddr_ll saddr = {
280 .sll_family = PF_PACKET,
281 .sll_halen = ETH_ALEN,
284 xmit_precheck(ctx);
286 sock = pf_socket();
288 if (ctx->rfraw) {
289 ctx->device_trans = xstrdup(ctx->device);
290 xfree(ctx->device);
292 enter_rfmon_mac80211(ctx->device_trans, &ctx->device);
295 if (ctx->num > 0)
296 num = ctx->num;
298 if (ctx->verbose) {
299 if (ctx->rand)
300 printf("Note: randomizes output makes trafgen slower!\n");
301 printf("MD: TX sendto %s %luus", ctx->rand ? "RND" : "RR", ctx->gap);
302 if (ctx->rfraw)
303 printf(" 802.11 raw via %s", ctx->device);
304 printf("\n\n");
306 printf("Running! Hang up with ^C!\n\n");
307 fflush(stdout);
309 saddr.sll_ifindex = device_ifindex(ctx->device);
311 bug_on(gettimeofday(&start, NULL));
313 while (likely(sigint == 0) && likely(num > 0)) {
314 apply_counter(i);
315 apply_randomizer(i);
317 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
318 (struct sockaddr *) &saddr, sizeof(saddr));
319 if (ret < 0)
320 whine("sendto error!\n");
322 ctx->tx_bytes += packets[i].len;
323 ctx->tx_packets++;
325 if (!ctx->rand) {
326 i++;
327 atomic_cmp_swp(&i, plen, 0);
328 } else {
329 i = rand() % plen;
332 if (ctx->num > 0)
333 num--;
335 if (ctx->gap > 0)
336 usleep(ctx->gap);
339 bug_on(gettimeofday(&end, NULL));
340 diff = tv_subtract(end, start);
342 if (ctx->rfraw)
343 leave_rfmon_mac80211(ctx->device_trans, ctx->device);
345 fflush(stdout);
346 printf("\n");
347 printf("\r%12lu frames outgoing\n", ctx->tx_packets);
348 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
349 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
351 close(sock);
354 static void xmit_fastpath_or_die(struct ctx *ctx)
356 int irq, ifindex;
357 uint8_t *out = NULL;
358 unsigned int it = 0;
359 unsigned long num = 1, i = 0, size;
360 struct ring tx_ring;
361 struct frame_map *hdr;
362 struct timeval start, end, diff;
364 xmit_precheck(ctx);
366 sock = pf_socket();
368 if (ctx->rfraw) {
369 ctx->device_trans = xstrdup(ctx->device);
370 xfree(ctx->device);
372 enter_rfmon_mac80211(ctx->device_trans, &ctx->device);
375 fmemset(&tx_ring, 0, sizeof(tx_ring));
377 ifindex = device_ifindex(ctx->device);
378 size = ring_size(ctx->device, ctx->reserve_size);
380 set_sock_prio(sock, 512);
381 set_packet_loss_discard(sock);
383 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
384 create_tx_ring(sock, &tx_ring, ctx->verbose);
385 mmap_tx_ring(sock, &tx_ring);
386 alloc_tx_ring_frames(&tx_ring);
387 bind_tx_ring(sock, &tx_ring, ifindex);
389 if (ctx->cpu >= 0 && ifindex > 0) {
390 irq = device_irq_number(ctx->device);
391 device_bind_irq_to_cpu(ctx->cpu, irq);
393 if (ctx->verbose)
394 printf("IRQ: %s:%d > CPU%d\n",
395 ctx->device, irq, ctx->cpu);
398 if (ctx->kpull)
399 interval = ctx->kpull;
400 if (ctx->num > 0)
401 num = ctx->num;
403 if (ctx->verbose) {
404 if (ctx->rand)
405 printf("Note: randomizes output makes trafgen slower!\n");
406 printf("MD: TX fastpath %s %luus", ctx->rand ? "RND" : "RR", interval);
407 if (ctx->rfraw)
408 printf(" 802.11 raw via %s", ctx->device);
409 printf("\n\n");
411 printf("Running! Hang up with ^C!\n\n");
412 fflush(stdout);
414 itimer.it_interval.tv_sec = 0;
415 itimer.it_interval.tv_usec = interval;
417 itimer.it_value.tv_sec = 0;
418 itimer.it_value.tv_usec = interval;
420 setitimer(ITIMER_REAL, &itimer, NULL);
422 bug_on(gettimeofday(&start, NULL));
424 while (likely(sigint == 0) && likely(num > 0)) {
425 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) &&
426 likely(num > 0)) {
427 hdr = tx_ring.frames[it].iov_base;
429 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
430 * sizeof(struct sockaddr_ll); */
431 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
433 hdr->tp_h.tp_snaplen = packets[i].len;
434 hdr->tp_h.tp_len = packets[i].len;
436 apply_counter(i);
437 apply_randomizer(i);
439 fmemcpy(out, packets[i].payload, packets[i].len);
441 ctx->tx_bytes += packets[i].len;
442 ctx->tx_packets++;
444 if (!ctx->rand) {
445 i++;
446 atomic_cmp_swp(&i, plen, 0);
447 } else {
448 i = rand() % plen;
451 kernel_may_pull_from_tx(&hdr->tp_h);
452 next_slot(&it, &tx_ring);
454 if (ctx->num > 0)
455 num--;
457 if (unlikely(sigint == 1))
458 break;
462 bug_on(gettimeofday(&end, NULL));
463 diff = tv_subtract(end, start);
465 destroy_tx_ring(sock, &tx_ring);
467 if (ctx->rfraw)
468 leave_rfmon_mac80211(ctx->device_trans, ctx->device);
470 fflush(stdout);
471 printf("\n");
472 printf("\r%12lu frames outgoing\n", ctx->tx_packets);
473 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
474 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
476 close(sock);
479 static void main_loop(struct ctx *ctx, char *confname, bool slow)
481 compile_packets(confname, ctx->verbose);
483 if (slow)
484 xmit_slowpath_or_die(ctx);
485 else
486 xmit_fastpath_or_die(ctx);
488 cleanup_packets();
491 int main(int argc, char **argv)
493 int c, opt_index, i, j, vals[4] = {0};
494 char *confname = NULL, *ptr;
495 bool prio_high = false, setsockmem = true, slow = false;
496 struct ctx ctx;
498 srand(time(NULL));
500 fmemset(&ctx, 0, sizeof(ctx));
501 ctx.cpu = -1;
503 while ((c = getopt_long(argc, argv, short_options, long_options,
504 &opt_index)) != EOF) {
505 switch (c) {
506 case 'h':
507 help();
508 break;
509 case 'v':
510 version();
511 break;
512 case 'V':
513 ctx.verbose = 1;
514 break;
515 case 'd':
516 case 'o':
517 ctx.device = xstrndup(optarg, IFNAMSIZ);
518 break;
519 case 'r':
520 ctx.rand = 1;
521 break;
522 case 'R':
523 ctx.rfraw = 1;
524 break;
525 case 'J':
526 ctx.jumbo_support = 1;
527 break;
528 case 'c':
529 case 'i':
530 confname = xstrdup(optarg);
531 break;
532 case 'k':
533 ctx.kpull = atol(optarg);
534 break;
535 case 'n':
536 ctx.num = atol(optarg);
537 break;
538 case 't':
539 slow = true;
540 ctx.gap = atol(optarg);
541 break;
542 case 'A':
543 setsockmem = false;
544 break;
545 case 'S':
546 ptr = optarg;
547 ctx.reserve_size = 0;
549 for (j = i = strlen(optarg); i > 0; --i) {
550 if (!isdigit(optarg[j - i]))
551 break;
552 ptr++;
555 if (!strncmp(ptr, "KB", strlen("KB")))
556 ctx.reserve_size = 1 << 10;
557 else if (!strncmp(ptr, "MB", strlen("MB")))
558 ctx.reserve_size = 1 << 20;
559 else if (!strncmp(ptr, "GB", strlen("GB")))
560 ctx.reserve_size = 1 << 30;
561 else
562 panic("Syntax error in ring size param!\n");
563 *ptr = 0;
565 ctx.reserve_size *= strtol(optarg, NULL, 0);
566 break;
567 case 'b':
568 set_cpu_affinity(optarg, 0);
569 /* Take the first CPU for rebinding the IRQ */
570 if (ctx.cpu != -2)
571 ctx.cpu = strtol(optarg, NULL, 0);
572 break;
573 case 'B':
574 set_cpu_affinity(optarg, 1);
575 break;
576 case 'H':
577 prio_high = true;
578 break;
579 case 'Q':
580 ctx.cpu = -2;
581 break;
582 case '?':
583 switch (optopt) {
584 case 'd':
585 case 'c':
586 case 'n':
587 case 'S':
588 case 'b':
589 case 'o':
590 case 'i':
591 case 'k':
592 case 'B':
593 case 't':
594 panic("Option -%c requires an argument!\n",
595 optopt);
596 default:
597 if (isprint(optopt))
598 whine("Unknown option character "
599 "`0x%X\'!\n", optopt);
600 die();
602 default:
603 break;
607 if (argc < 5)
608 help();
609 if (ctx.device == NULL)
610 panic("No networking device given!\n");
611 if (confname == NULL)
612 panic("No configuration file given!\n");
613 if (device_mtu(ctx.device) == 0)
614 panic("This is no networking device!\n");
615 if (!ctx.rfraw && device_up_and_running(ctx.device) == 0)
616 panic("Networking device not running!\n");
618 register_signal(SIGINT, signal_handler);
619 register_signal(SIGHUP, signal_handler);
620 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
622 header();
624 if (prio_high) {
625 set_proc_prio(get_default_proc_prio());
626 set_sched_status(get_default_sched_policy(), get_default_sched_prio());
629 if (setsockmem)
630 set_system_socket_memory(vals);
632 main_loop(&ctx, confname, slow);
634 if (setsockmem)
635 reset_system_socket_memory(vals);
637 free(ctx.device);
638 free(ctx.device_trans);
639 free(confname);
641 return 0;