netsniff-ng, trafgen: drop privileges if wished
[netsniff-ng.git] / src / trafgen.c
blobdba6abb758b6b1d86e402adc0674efaf7b0bb99d
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/fsuid.h>
32 #include <sys/stat.h>
33 #include <sys/time.h>
34 #include <sys/wait.h>
35 #include <sys/mman.h>
36 #include <net/ethernet.h>
37 #include <netinet/in.h>
38 #include <netinet/ip.h>
39 #include <linux/icmp.h>
40 #include <arpa/inet.h>
41 #include <signal.h>
42 #include <stdint.h>
43 #include <stdlib.h>
44 #include <fcntl.h>
45 #include <time.h>
46 #include <poll.h>
47 #include <netdb.h>
48 #include <math.h>
49 #include <unistd.h>
51 #include "xmalloc.h"
52 #include "die.h"
53 #include "mac80211.h"
54 #include "xutils.h"
55 #include "xio.h"
56 #include "built_in.h"
57 #include "trafgen_conf.h"
58 #include "tprintf.h"
59 #include "ring_tx.h"
60 #include "csum.h"
62 struct ctx {
63 bool rand, rfraw, jumbo_support, verbose, smoke_test;
64 unsigned long kpull, num, gap, reserve_size, cpus;
65 struct sockaddr_in dest;
66 char *device, *device_trans, *rhost;
69 struct cpu_stats {
70 unsigned long tv_sec, tv_usec;
71 unsigned long long tx_packets, tx_bytes;
72 unsigned long long cf_packets, cf_bytes;
73 unsigned long long cd_packets;
74 sig_atomic_t state;
77 sig_atomic_t sigint = 0;
79 struct packet *packets = NULL;
80 size_t plen = 0;
82 struct packet_dyn *packet_dyn = NULL;
83 size_t dlen = 0;
85 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRsP:eE:pu:g:";
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 {"cpus", required_argument, NULL, 'P'},
94 {"ring-size", required_argument, NULL, 'S'},
95 {"kernel-pull", required_argument, NULL, 'k'},
96 {"smoke-test", required_argument, NULL, 's'},
97 {"seed", required_argument, NULL, 'E'},
98 {"user", required_argument, NULL, 'u'},
99 {"group", required_argument, NULL, 'g'},
100 {"jumbo-support", no_argument, NULL, 'J'},
101 {"cpp", no_argument, NULL, 'p'},
102 {"rfraw", no_argument, NULL, 'R'},
103 {"rand", no_argument, NULL, 'r'},
104 {"verbose", no_argument, NULL, 'V'},
105 {"version", no_argument, NULL, 'v'},
106 {"example", no_argument, NULL, 'e'},
107 {"help", no_argument, NULL, 'h'},
108 {NULL, 0, NULL, 0}
111 static int sock;
113 static struct itimerval itimer;
115 static unsigned long interval = TX_KERNEL_PULL_INT;
117 static struct cpu_stats *stats;
119 unsigned int seed;
121 #define CPU_STATS_STATE_CFG 1
122 #define CPU_STATS_STATE_CHK 2
123 #define CPU_STATS_STATE_RES 4
125 #define set_system_socket_memory(vals) \
126 do { \
127 if ((vals[0] = get_system_socket_mem(sock_rmem_max)) < SMEM_SUG_MAX) \
128 set_system_socket_mem(sock_rmem_max, SMEM_SUG_MAX); \
129 if ((vals[1] = get_system_socket_mem(sock_rmem_def)) < SMEM_SUG_DEF) \
130 set_system_socket_mem(sock_rmem_def, SMEM_SUG_DEF); \
131 if ((vals[2] = get_system_socket_mem(sock_wmem_max)) < SMEM_SUG_MAX) \
132 set_system_socket_mem(sock_wmem_max, SMEM_SUG_MAX); \
133 if ((vals[3] = get_system_socket_mem(sock_wmem_def)) < SMEM_SUG_DEF) \
134 set_system_socket_mem(sock_wmem_def, SMEM_SUG_DEF); \
135 } while (0)
137 #define reset_system_socket_memory(vals) \
138 do { \
139 set_system_socket_mem(sock_rmem_max, vals[0]); \
140 set_system_socket_mem(sock_rmem_def, vals[1]); \
141 set_system_socket_mem(sock_wmem_max, vals[2]); \
142 set_system_socket_mem(sock_wmem_def, vals[3]); \
143 } while (0)
145 #ifndef ICMP_FILTER
146 # define ICMP_FILTER 1
148 struct icmp_filter {
149 __u32 data;
151 #endif
153 static void signal_handler(int number)
155 switch (number) {
156 case SIGINT:
157 sigint = 1;
158 case SIGHUP:
159 default:
160 break;
164 static void timer_elapsed(int number)
166 itimer.it_interval.tv_sec = 0;
167 itimer.it_interval.tv_usec = interval;
169 itimer.it_value.tv_sec = 0;
170 itimer.it_value.tv_usec = interval;
172 pull_and_flush_tx_ring(sock);
173 setitimer(ITIMER_REAL, &itimer, NULL);
176 static void header(void)
178 printf("%s%s%s\n", colorize_start(bold), "trafgen " VERSION_STRING, colorize_end());
181 static void help(void)
183 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
184 puts("http://www.netsniff-ng.org\n\n"
185 "Usage: trafgen [options]\n"
186 "Options:\n"
187 " -o|-d|--out|--dev <netdev> Networking Device i.e., eth0\n"
188 " -i|-c|--in|--conf <cfg-file/-> Packet configuration file/stdin\n"
189 " -p|--cpp Run packet config through preprocessor\n"
190 " -J|--jumbo-support Support 64KB Super Jumbo Frames (def: 2048B)\n"
191 " -R|--rfraw Inject raw 802.11 frames\n"
192 " -s|--smoke-test <ipv4-receiver> Test if machine survived packet\n"
193 " -n|--num <uint> Number of packets until exit (def: 0)\n"
194 " -r|--rand Randomize packet selection (def: round robin)\n"
195 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
196 " -t|--gap <uint> Interpacket gap in us (approx)\n"
197 " -S|--ring-size <size> Manually set mmap size (KB/MB/GB): e.g.\'10MB\'\n"
198 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
199 " -E|--seed <uint> Manually set srand(3) seed\n"
200 " -u|--user <userid> Drop privileges and change to userid\n"
201 " -g|--group <groupid> Drop privileges and change to groupid\n"
202 " -V|--verbose Be more verbose\n"
203 " -v|--version Show version\n"
204 " -e|--example Show built-in packet config example\n"
205 " -h|--help Guess what?!\n\n"
206 "Examples:\n"
207 " See trafgen.txf for configuration file examples.\n"
208 " trafgen --dev eth0 --conf trafgen.cfg\n"
209 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
210 " trafgen --dev eth0 --conf trafgen.cfg --smoke-test 10.0.0.1\n"
211 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
212 " trafgen --dev eth0 --conf trafgen.cfg --rand --gap 1000\n"
213 " trafgen --dev eth0 --conf trafgen.cfg --rand --num 1400000 -k1000\n"
214 " trafgen --dev eth0 --conf trafgen.cfg -u `id -u bob` -g `id -g bob`\n\n"
215 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
216 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
217 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
218 " Run packet only on CPU1-2: cpu(1:2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
219 "Note:\n"
220 " Smoke test example: machine A, 10.0.0.2 (trafgen) is directly\n"
221 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
222 " we assume the kernel crashed, thus we print the packet and quit.\n"
223 " In case you find a ping-of-death, please mention trafgen in your\n"
224 " commit message of the fix!\n\n"
225 " This tool is targeted for network developers! You should\n"
226 " be aware of what you are doing and what these options above\n"
227 " mean! Only use this tool in an isolated LAN that you own!\n\n"
228 "Please report bugs to <bugs@netsniff-ng.org>\n"
229 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
230 "Swiss federal institute of technology (ETH Zurich)\n"
231 "License: GNU GPL version 2.0\n"
232 "This is free software: you are free to change and redistribute it.\n"
233 "There is NO WARRANTY, to the extent permitted by law.\n");
234 die();
237 static void example(void)
239 const char *e =
240 "/* Note: dynamic elements make trafgen slower! */\n\n"
241 "#define ETH_P_IP 0x0800\n\n"
242 "#define SYN (1 << 1)\n"
243 "#define ECN (1 << 6)\n\n"
244 "{\n"
245 " /* MAC Destination */\n"
246 " fill(0xff, 6),\n"
247 " /* MAC Source */\n"
248 " 0x00, 0x02, 0xb3, drnd(3),\n"
249 " /* IPv4 Protocol */\n"
250 " c16(ETH_P_IP),\n"
251 " /* IPv4 Version, IHL, TOS */\n"
252 " 0b01000101, 0,\n"
253 " /* IPv4 Total Len */\n"
254 " c16(59),\n"
255 " /* IPv4 Ident */\n"
256 " drnd(2),\n"
257 " /* IPv4 Flags, Frag Off */\n"
258 " 0b01000000, 0,\n"
259 " /* IPv4 TTL */\n"
260 " 64,\n"
261 " /* Proto TCP */\n"
262 " 0x06,\n"
263 " /* IPv4 Checksum (IP header from, to) */\n"
264 " csumip(14, 33),\n"
265 " /* Source IP */\n"
266 " drnd(4),\n"
267 " /* Dest IP */\n"
268 " drnd(4),\n"
269 " /* TCP Source Port */\n"
270 " drnd(2),\n"
271 " /* TCP Dest Port */\n"
272 " c16(80),\n"
273 " /* TCP Sequence Number */\n"
274 " drnd(4),\n"
275 " /* TCP Ackn. Number */\n"
276 " c32(0),\n"
277 " /* TCP Header length + TCP SYN/ECN Flag */\n"
278 " c16((0x8 << 12) | SYN | ECN)\n"
279 " /* Window Size */\n"
280 " c16(16),\n"
281 " /* TCP Checksum (offset IP, offset TCP) */\n"
282 " csumtcp(14, 34),\n"
283 " /* TCP Options */\n"
284 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
285 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
286 " /* Data blob */\n"
287 " \"gotcha!\",\n"
288 "}";
289 puts(e);
290 die();
293 static void version(void)
295 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
296 puts("http://www.netsniff-ng.org\n\n"
297 "Please report bugs to <bugs@netsniff-ng.org>\n"
298 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
299 "Swiss federal institute of technology (ETH Zurich)\n"
300 "License: GNU GPL version 2.0\n"
301 "This is free software: you are free to change and redistribute it.\n"
302 "There is NO WARRANTY, to the extent permitted by law.\n");
303 die();
306 static void apply_counter(int counter_id)
308 int j, i = counter_id;
309 size_t counter_max = packet_dyn[i].clen;
311 for (j = 0; j < counter_max; ++j) {
312 uint8_t val;
313 struct counter *counter = &packet_dyn[i].cnt[j];
315 val = counter->val - counter->min;
317 switch (counter->type) {
318 case TYPE_INC:
319 val = (val + counter->inc) % (counter->max - counter->min + 1);
320 break;
321 case TYPE_DEC:
322 val = (val - counter->inc) % (counter->min - counter->max + 1);
323 break;
324 default:
325 bug();
328 counter->val = val + counter->min;
329 packets[i].payload[counter->off] = val;
333 static void apply_randomizer(int rand_id)
335 int j, i = rand_id;
336 size_t rand_max = packet_dyn[i].rlen;
338 for (j = 0; j < rand_max; ++j) {
339 uint8_t val = (uint8_t) rand();
340 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
342 packets[i].payload[randomizer->off] = val;
346 /* Taken and modified from tcpdump, Copyright belongs to them! */
348 struct cksum_vec {
349 const u8 *ptr;
350 int len;
353 #define ADDCARRY(x) \
354 do { if ((x) > 65535) \
355 (x) -= 65535; \
356 } while (0)
358 #define REDUCE \
359 do { \
360 l_util.l = sum; \
361 sum = l_util.s[0] + l_util.s[1]; \
362 ADDCARRY(sum); \
363 } while (0)
365 static u16 __in_cksum(const struct cksum_vec *vec, int veclen)
367 register const u16 *w;
368 register int sum = 0, mlen = 0;
369 int byte_swapped = 0;
370 union {
371 u8 c[2];
372 u16 s;
373 } s_util;
374 union {
375 u16 s[2];
376 u32 l;
377 } l_util;
379 for (; veclen != 0; vec++, veclen--) {
380 if (vec->len == 0)
381 continue;
383 w = (const u16 *) (void *) vec->ptr;
385 if (mlen == -1) {
386 s_util.c[1] = *(const u8 *) w;
387 sum += s_util.s;
388 w = (const u16 *) (void *) ((const u8 *) w + 1);
389 mlen = vec->len - 1;
390 } else
391 mlen = vec->len;
393 if ((1 & (unsigned long) w) && (mlen > 0)) {
394 REDUCE;
395 sum <<= 8;
396 s_util.c[0] = *(const u8 *) w;
397 w = (const u16 *) (void *) ((const u8 *) w + 1);
398 mlen--;
399 byte_swapped = 1;
402 while ((mlen -= 32) >= 0) {
403 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
404 sum += w[4]; sum += w[5]; sum += w[6]; sum += w[7];
405 sum += w[8]; sum += w[9]; sum += w[10]; sum += w[11];
406 sum += w[12]; sum += w[13]; sum += w[14]; sum += w[15];
407 w += 16;
410 mlen += 32;
412 while ((mlen -= 8) >= 0) {
413 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
414 w += 4;
417 mlen += 8;
419 if (mlen == 0 && byte_swapped == 0)
420 continue;
422 REDUCE;
424 while ((mlen -= 2) >= 0) {
425 sum += *w++;
428 if (byte_swapped) {
429 REDUCE;
430 sum <<= 8;
431 byte_swapped = 0;
433 if (mlen == -1) {
434 s_util.c[1] = *(const u8 *) w;
435 sum += s_util.s;
436 mlen = 0;
437 } else
438 mlen = -1;
439 } else if (mlen == -1)
440 s_util.c[0] = *(const u8 *) w;
443 if (mlen == -1) {
444 s_util.c[1] = 0;
445 sum += s_util.s;
448 REDUCE;
450 return (~sum & 0xffff);
453 static u16 p4_csum(const struct ip *ip, const u8 *data, u16 len,
454 u8 next_proto)
456 struct cksum_vec vec[2];
457 struct pseudo_hdr {
458 u32 src;
459 u32 dst;
460 u8 mbz;
461 u8 proto;
462 u16 len;
463 } ph;
465 memset(&ph, 0, sizeof(ph));
466 ph.len = htons(len);
467 ph.mbz = 0;
468 ph.proto = next_proto;
469 ph.src = ip->ip_src.s_addr;
470 ph.dst = ip->ip_dst.s_addr;
472 vec[0].ptr = (const u8 *) (void *) &ph;
473 vec[0].len = sizeof(ph);
475 vec[1].ptr = data;
476 vec[1].len = len;
478 return __in_cksum(vec, 2);
481 static void apply_csum16(int csum_id)
483 int j, i = csum_id;
484 size_t csum_max = packet_dyn[i].slen;
486 for (j = 0; j < csum_max; ++j) {
487 uint16_t sum = 0;
488 struct csum16 *csum = &packet_dyn[i].csum[j];
490 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
492 switch (csum->which) {
493 case CSUM_IP:
494 if (csum->to >= packets[i].len)
495 csum->to = packets[i].len - 1;
496 sum = calc_csum(packets[i].payload + csum->from,
497 csum->to - csum->from + 1, 0);
498 break;
499 case CSUM_UDP:
500 sum = p4_csum((void *) packets[i].payload + csum->from,
501 packets[i].payload + csum->to,
502 (packets[i].len - csum->to),
503 IPPROTO_UDP);
504 break;
505 case CSUM_TCP:
506 sum = p4_csum((void *) packets[i].payload + csum->from,
507 packets[i].payload + csum->to,
508 (packets[i].len - csum->to),
509 IPPROTO_TCP);
510 break;
513 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
517 static struct cpu_stats *setup_shared_var(unsigned long cpus)
519 int fd;
520 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
521 struct cpu_stats *buff;
523 fmemset(zbuff, 0, sizeof(zbuff));
524 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
526 fd = creat(file, S_IRUSR | S_IWUSR);
527 bug_on(fd < 0);
528 close(fd);
530 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
531 S_IRUSR | S_IWUSR);
532 write_or_die(fd, zbuff, sizeof(zbuff));
534 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
535 MAP_SHARED, fd, 0);
536 if (buff == (void *) -1)
537 panic("Cannot setup shared variable!\n");
539 close(fd);
540 unlink(file);
542 memset(buff, 0, sizeof(zbuff));
544 return buff;
547 static void destroy_shared_var(void *buff, unsigned long cpus)
549 munmap(buff, cpus * sizeof(struct cpu_stats));
552 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
554 int i;
556 printf("{");
557 for (i = 0; i < len; ++i) {
558 if (i % 15 == 0)
559 printf("\n ");
560 printf("0x%02x, ", payload[i]);
562 printf("\n}\n");
563 fflush(stdout);
566 static inline unsigned short csum(unsigned short *buf, int nwords)
568 unsigned long sum;
570 for (sum = 0; nwords > 0; nwords--)
571 sum += *buf++;
572 sum = (sum >> 16) + (sum & 0xffff);
573 sum += (sum >> 16);
575 return ~sum;
578 static int xmit_smoke_setup(struct ctx *ctx)
580 int icmp_sock, ret, ttl = 64;
581 struct icmp_filter filter;
583 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
584 if (icmp_sock < 0)
585 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
587 filter.data = ~(1 << ICMP_ECHOREPLY);
589 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
590 if (ret < 0)
591 panic("Cannot install filter!\n");
593 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
594 if (ret < 0)
595 panic("Cannot set TTL!\n");
597 memset(&ctx->dest, 0, sizeof(ctx->dest));
598 ctx->dest.sin_family = AF_INET;
599 ctx->dest.sin_port = 0;
601 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
602 if (ret < 0)
603 panic("Cannot resolv address!\n");
605 return icmp_sock;
608 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
610 int ret, i, probes = 5;
611 short ident, cnt = 1;
612 uint8_t outpack[512], *data;
613 struct icmphdr *icmp;
614 struct iphdr *ip;
615 size_t len = sizeof(*icmp) + 56;
616 struct sockaddr_in from;
617 socklen_t from_len;
618 struct pollfd fds = {
619 .fd = icmp_sock,
620 .events = POLLIN,
623 while (probes-- > 0) {
624 ident = htons((short) rand());
626 memset(outpack, 0, sizeof(outpack));
627 icmp = (void *) outpack;
628 icmp->type = ICMP_ECHO;
629 icmp->code = 0;
630 icmp->checksum = 0;
631 icmp->un.echo.id = ident;
632 icmp->un.echo.sequence = htons(cnt++);
634 data = ((uint8_t *) outpack + sizeof(*icmp));
635 for (i = 0; i < 56; ++i)
636 data[i] = (uint8_t) rand();
638 icmp->checksum = csum((unsigned short *) outpack,
639 len / sizeof(unsigned short));
641 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
642 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
643 if (unlikely(ret != len))
644 panic("Cannot send out probe: %s!\n", strerror(errno));
646 ret = poll(&fds, 1, 500);
647 if (ret < 0)
648 panic("Poll failed!\n");
650 if (fds.revents & POLLIN) {
651 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
652 (struct sockaddr *) &from, &from_len);
653 if (unlikely(ret <= 0))
654 panic("Probe receive failed!\n");
655 if (unlikely(from_len != sizeof(ctx->dest)))
656 continue;
657 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
658 continue;
659 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
660 continue;
661 ip = (void *) outpack;
662 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
663 continue;
664 icmp = (void *) outpack + ip->ihl * 4;
665 if (unlikely(icmp->un.echo.id != ident))
666 continue;
668 return 0;
672 return -1;
675 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu)
677 int ret, icmp_sock = -1;
678 unsigned long num = 1, i = 0;
679 struct timeval start, end, diff;
680 unsigned long long tx_bytes = 0, tx_packets = 0;
681 struct packet_dyn *pktd;
682 struct sockaddr_ll saddr = {
683 .sll_family = PF_PACKET,
684 .sll_halen = ETH_ALEN,
685 .sll_ifindex = device_ifindex(ctx->device),
688 if (ctx->num > 0)
689 num = ctx->num;
691 if (ctx->smoke_test)
692 icmp_sock = xmit_smoke_setup(ctx);
694 bug_on(gettimeofday(&start, NULL));
696 while (likely(sigint == 0) && likely(num > 0)) {
697 pktd = &packet_dyn[i];
698 if (pktd->clen + pktd->rlen + pktd->slen) {
699 apply_counter(i);
700 apply_randomizer(i);
701 apply_csum16(i);
703 retry:
704 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
705 (struct sockaddr *) &saddr, sizeof(saddr));
706 if (unlikely(ret < 0)) {
707 if (errno == ENOBUFS) {
708 sched_yield();
709 goto retry;
712 panic("Sendto error: %s!\n", strerror(errno));
715 tx_bytes += packets[i].len;
716 tx_packets++;
718 if (ctx->smoke_test) {
719 ret = xmit_smoke_probe(icmp_sock, ctx);
720 if (unlikely(ret < 0)) {
721 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
722 printf(" Remote host seems to be unresponsive to ICMP pings!\n");
723 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
724 i, seed);
726 dump_trafgen_snippet(packets[i].payload, packets[i].len);
727 break;
731 if (!ctx->rand) {
732 i++;
733 if (i >= plen)
734 i = 0;
735 } else
736 i = rand() % plen;
738 if (ctx->num > 0)
739 num--;
741 if (ctx->gap > 0)
742 usleep(ctx->gap);
745 bug_on(gettimeofday(&end, NULL));
746 diff = tv_subtract(end, start);
748 if (ctx->smoke_test)
749 close(icmp_sock);
751 stats[cpu].tx_packets = tx_packets;
752 stats[cpu].tx_bytes = tx_bytes;
753 stats[cpu].tv_sec = diff.tv_sec;
754 stats[cpu].tv_usec = diff.tv_usec;
756 stats[cpu].state |= CPU_STATS_STATE_RES;
759 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu)
761 int ifindex = device_ifindex(ctx->device);
762 uint8_t *out = NULL;
763 unsigned int it = 0;
764 unsigned long num = 1, i = 0, size;
765 struct ring tx_ring;
766 struct frame_map *hdr;
767 struct timeval start, end, diff;
768 struct packet_dyn *pktd;
769 unsigned long long tx_bytes = 0, tx_packets = 0;
771 fmemset(&tx_ring, 0, sizeof(tx_ring));
773 size = ring_size(ctx->device, ctx->reserve_size);
775 set_sock_prio(sock, 512);
776 set_packet_loss_discard(sock);
778 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
779 create_tx_ring(sock, &tx_ring, ctx->verbose);
780 mmap_tx_ring(sock, &tx_ring);
781 alloc_tx_ring_frames(&tx_ring);
782 bind_tx_ring(sock, &tx_ring, ifindex);
784 if (ctx->kpull)
785 interval = ctx->kpull;
786 if (ctx->num > 0)
787 num = ctx->num;
789 itimer.it_interval.tv_sec = 0;
790 itimer.it_interval.tv_usec = interval;
792 itimer.it_value.tv_sec = 0;
793 itimer.it_value.tv_usec = interval;
795 setitimer(ITIMER_REAL, &itimer, NULL);
797 bug_on(gettimeofday(&start, NULL));
799 while (likely(sigint == 0) && likely(num > 0)) {
800 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
801 hdr = tx_ring.frames[it].iov_base;
803 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
804 * sizeof(struct sockaddr_ll); */
805 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
807 hdr->tp_h.tp_snaplen = packets[i].len;
808 hdr->tp_h.tp_len = packets[i].len;
810 pktd = &packet_dyn[i];
811 if (pktd->clen + pktd->rlen + pktd->slen) {
812 apply_counter(i);
813 apply_randomizer(i);
814 apply_csum16(i);
817 fmemcpy(out, packets[i].payload, packets[i].len);
819 tx_bytes += packets[i].len;
820 tx_packets++;
822 if (!ctx->rand) {
823 i++;
824 if (i >= plen)
825 i = 0;
826 } else
827 i = rand() % plen;
829 kernel_may_pull_from_tx(&hdr->tp_h);
831 it++;
832 if (it >= tx_ring.layout.tp_frame_nr)
833 it = 0;
835 if (ctx->num > 0)
836 num--;
838 if (unlikely(sigint == 1))
839 break;
843 bug_on(gettimeofday(&end, NULL));
844 diff = tv_subtract(end, start);
846 destroy_tx_ring(sock, &tx_ring);
848 stats[cpu].tx_packets = tx_packets;
849 stats[cpu].tx_bytes = tx_bytes;
850 stats[cpu].tv_sec = diff.tv_sec;
851 stats[cpu].tv_usec = diff.tv_usec;
853 stats[cpu].state |= CPU_STATS_STATE_RES;
856 static inline void __set_state(int cpu, sig_atomic_t s)
858 stats[cpu].state = s;
861 static inline sig_atomic_t __get_state(int cpu)
863 return stats[cpu].state;
866 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
868 int i;
869 unsigned long total;
871 for (i = 0, total = plen; i < ctx->cpus; i++) {
872 if (i == cpu)
873 continue;
875 while ((__get_state(i) & CPU_STATS_STATE_CFG) == 0 &&
876 sigint == 0)
877 sched_yield();
879 total += stats[i].cf_packets;
882 return total;
885 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
887 int i, cpu_sel;
888 unsigned long total;
889 long long delta_correction = 0;
891 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
892 if (i == cpu)
893 continue;
895 while ((__get_state(i) & CPU_STATS_STATE_CHK) == 0 &&
896 sigint == 0)
897 sched_yield();
899 total += stats[i].cd_packets;
902 if (total > orig)
903 delta_correction = -1 * ((long long) total - orig);
904 if (total < orig)
905 delta_correction = +1 * ((long long) orig - total);
907 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
908 if (stats[i].cd_packets > 0) {
909 if ((long long) stats[i].cd_packets +
910 delta_correction > 0) {
911 cpu_sel = i;
912 break;
917 if (cpu == cpu_sel)
918 ctx->num += delta_correction;
921 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
922 sig_atomic_t s)
924 stats[cpu].cf_packets = p;
925 stats[cpu].cf_bytes = b;
926 stats[cpu].state = s;
929 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
931 stats[cpu].cd_packets = p;
932 stats[cpu].state = s;
935 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
937 int i;
938 unsigned long plen_total, orig = ctx->num;
939 size_t mtu, total_len = 0;
941 bug_on(plen != dlen);
943 for (i = 0; i < plen; ++i)
944 total_len += packets[i].len;
946 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
947 plen_total = __wait_and_sum_others(ctx, cpu);
949 if (orig > 0) {
950 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
952 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
953 CPU_STATS_STATE_CFG);
954 __correct_global_delta(ctx, cpu, orig);
957 if (plen == 0) {
958 __set_state(cpu, CPU_STATS_STATE_RES);
959 return -1;
962 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
963 if (packets[i].len > mtu + 14)
964 panic("Device MTU < than packet%d's size!\n", i);
965 if (packets[i].len <= 14)
966 panic("Packet%d's size too short!\n", i);
969 return 0;
972 static void main_loop(struct ctx *ctx, char *confname, bool slow,
973 int cpu, bool invoke_cpp)
975 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
976 if (xmit_packet_precheck(ctx, cpu) < 0)
977 return;
979 if (cpu == 0) {
980 int i;
981 size_t total_len = 0, total_pkts = 0;
983 for (i = 0; i < ctx->cpus; ++i) {
984 total_len += stats[i].cf_bytes;
985 total_pkts += stats[i].cf_packets;
988 printf("%6zu packets to schedule\n", total_pkts);
989 printf("%6zu bytes in total\n", total_len);
990 printf("Running! Hang up with ^C!\n\n");
991 fflush(stdout);
994 sock = pf_socket();
996 if (slow)
997 xmit_slowpath_or_die(ctx, cpu);
998 else
999 xmit_fastpath_or_die(ctx, cpu);
1001 close(sock);
1003 cleanup_packets();
1006 static unsigned int generate_srand_seed(void)
1008 int fd;
1009 unsigned int seed;
1011 fd = open("/dev/random", O_RDONLY);
1012 if (fd < 0)
1013 return time(0);
1015 read_or_die(fd, &seed, sizeof(seed));
1017 close(fd);
1018 return seed;
1021 int main(int argc, char **argv)
1023 bool slow = false, invoke_cpp = false;
1024 int c, opt_index, i, j, vals[4] = {0}, irq;
1025 char *confname = NULL, *ptr;
1026 unsigned long cpus_tmp;
1027 unsigned long long tx_packets, tx_bytes;
1028 struct ctx ctx;
1029 uid_t uid = getuid();
1030 gid_t gid = getgid();
1032 fmemset(&ctx, 0, sizeof(ctx));
1033 ctx.cpus = get_number_cpus_online();
1035 seed = generate_srand_seed();
1037 while ((c = getopt_long(argc, argv, short_options, long_options,
1038 &opt_index)) != EOF) {
1039 switch (c) {
1040 case 'h':
1041 help();
1042 break;
1043 case 'v':
1044 version();
1045 break;
1046 case 'e':
1047 example();
1048 break;
1049 case 'p':
1050 invoke_cpp = true;
1051 break;
1052 case 'V':
1053 ctx.verbose = true;
1054 break;
1055 case 'P':
1056 cpus_tmp = strtoul(optarg, NULL, 0);
1057 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
1058 ctx.cpus = cpus_tmp;
1059 break;
1060 case 'd':
1061 case 'o':
1062 ctx.device = xstrndup(optarg, IFNAMSIZ);
1063 break;
1064 case 'r':
1065 ctx.rand = true;
1066 break;
1067 case 's':
1068 slow = true;
1069 ctx.cpus = 1;
1070 ctx.smoke_test = true;
1071 ctx.rhost = xstrdup(optarg);
1072 break;
1073 case 'R':
1074 ctx.rfraw = true;
1075 break;
1076 case 'J':
1077 ctx.jumbo_support = true;
1078 break;
1079 case 'c':
1080 case 'i':
1081 confname = xstrdup(optarg);
1082 break;
1083 case 'u':
1084 uid = strtoul(optarg, NULL, 0);
1085 break;
1086 case 'g':
1087 gid = strtoul(optarg, NULL, 0);
1088 break;
1089 case 'k':
1090 ctx.kpull = strtoul(optarg, NULL, 0);
1091 break;
1092 case 'E':
1093 seed = strtoul(optarg, NULL, 0);
1094 break;
1095 case 'n':
1096 ctx.num = strtoul(optarg, NULL, 0);
1097 break;
1098 case 't':
1099 slow = true;
1100 ctx.gap = strtoul(optarg, NULL, 0);
1101 if (ctx.gap > 0)
1102 /* Fall back to single core to not
1103 * mess up correct timing. We are slow
1104 * anyway!
1106 ctx.cpus = 1;
1107 break;
1108 case 'S':
1109 ptr = optarg;
1110 ctx.reserve_size = 0;
1112 for (j = i = strlen(optarg); i > 0; --i) {
1113 if (!isdigit(optarg[j - i]))
1114 break;
1115 ptr++;
1118 if (!strncmp(ptr, "KB", strlen("KB")))
1119 ctx.reserve_size = 1 << 10;
1120 else if (!strncmp(ptr, "MB", strlen("MB")))
1121 ctx.reserve_size = 1 << 20;
1122 else if (!strncmp(ptr, "GB", strlen("GB")))
1123 ctx.reserve_size = 1 << 30;
1124 else
1125 panic("Syntax error in ring size param!\n");
1126 *ptr = 0;
1128 ctx.reserve_size *= strtol(optarg, NULL, 0);
1129 break;
1130 case '?':
1131 switch (optopt) {
1132 case 'd':
1133 case 'c':
1134 case 'n':
1135 case 'S':
1136 case 's':
1137 case 'P':
1138 case 'o':
1139 case 'E':
1140 case 'i':
1141 case 'k':
1142 case 'u':
1143 case 'g':
1144 case 't':
1145 panic("Option -%c requires an argument!\n",
1146 optopt);
1147 default:
1148 if (isprint(optopt))
1149 whine("Unknown option character "
1150 "`0x%X\'!\n", optopt);
1151 die();
1153 default:
1154 break;
1158 if (setgid(gid) != 0)
1159 panic("Unable to drop group privileges: %s!\n", strerror(errno));
1160 if (setuid(uid) != 0)
1161 panic("Unable to drop user privileges: %s!\n", strerror(errno));
1163 if (argc < 5)
1164 help();
1165 if (ctx.device == NULL)
1166 panic("No networking device given!\n");
1167 if (confname == NULL)
1168 panic("No configuration file given!\n");
1169 if (device_mtu(ctx.device) == 0)
1170 panic("This is no networking device!\n");
1171 if (!ctx.rfraw && device_up_and_running(ctx.device) == 0)
1172 panic("Networking device not running!\n");
1174 register_signal(SIGINT, signal_handler);
1175 register_signal(SIGHUP, signal_handler);
1176 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1178 header();
1180 srand(seed);
1182 set_system_socket_memory(vals);
1184 if (ctx.rfraw) {
1185 ctx.device_trans = xstrdup(ctx.device);
1186 xfree(ctx.device);
1188 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1189 sleep(0);
1192 irq = device_irq_number(ctx.device);
1193 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1195 if (ctx.num > 0 && ctx.num <= ctx.cpus)
1196 ctx.cpus = 1;
1198 stats = setup_shared_var(ctx.cpus);
1200 for (i = 0; i < ctx.cpus; i++) {
1201 pid_t pid = fork();
1203 switch (pid) {
1204 case 0:
1205 cpu_affinity(i);
1206 main_loop(&ctx, confname, slow, i, invoke_cpp);
1208 goto thread_out;
1209 case -1:
1210 panic("Cannot fork processes!\n");
1214 for (i = 0; i < ctx.cpus; i++) {
1215 int status;
1217 wait(&status);
1218 if (WEXITSTATUS(status) == EXIT_FAILURE)
1219 die();
1222 if (ctx.rfraw)
1223 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1225 reset_system_socket_memory(vals);
1227 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1228 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1229 sched_yield();
1231 tx_packets += stats[i].tx_packets;
1232 tx_bytes += stats[i].tx_bytes;
1235 fflush(stdout);
1236 printf("\n");
1237 printf("\r%12llu packets outgoing\n", tx_packets);
1238 printf("\r%12llu bytes outgoing\n", tx_bytes);
1239 for (i = 0; i < ctx.cpus; i++) {
1240 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1241 stats[i].tv_sec, stats[i].tv_usec, i,
1242 stats[i].tx_packets);
1245 thread_out:
1246 destroy_shared_var(stats, ctx.cpus);
1248 free(ctx.device);
1249 free(ctx.device_trans);
1250 free(ctx.rhost);
1251 free(confname);
1253 return 0;