xio: add comment to function
[netsniff-ng.git] / trafgen.c
blob2d3a399851f41c26b674a0958545e58012c77a93
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, enforce;
64 unsigned long kpull, num, gap, reserve_size, cpus;
65 uid_t uid; gid_t gid; char *device, *device_trans, *rhost;
66 struct sockaddr_in dest;
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 C 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> Probe if machine survived fuzz-tested 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/fuzz 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 " For introducing bit errors, delays with random variation and more,\n"
226 " make use of tc(8) with its difference disciplines (e.g. netem).\n\n"
227 " For generating different package distributions, you can use some\n"
228 " scripting to generate a trafgen config file with packet ratios as:\n\n"
229 " IMIX 64:7, 570:4, 1518:1\n"
230 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
231 " Cisco 64:7, 594:4, 1518:1\n"
232 " RPR Trimodal 64:60, 512:20, 1518:20\n"
233 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
234 "Please report bugs to <bugs@netsniff-ng.org>\n"
235 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
236 "Swiss federal institute of technology (ETH Zurich)\n"
237 "License: GNU GPL version 2.0\n"
238 "This is free software: you are free to change and redistribute it.\n"
239 "There is NO WARRANTY, to the extent permitted by law.\n");
240 die();
243 static void example(void)
245 const char *e =
246 "/* Note: dynamic elements make trafgen slower! */\n\n"
247 "#define ETH_P_IP 0x0800\n\n"
248 "#define SYN (1 << 1)\n"
249 "#define ECN (1 << 6)\n\n"
250 "{\n"
251 " /* MAC Destination */\n"
252 " fill(0xff, 6),\n"
253 " /* MAC Source */\n"
254 " 0x00, 0x02, 0xb3, drnd(3),\n"
255 " /* IPv4 Protocol */\n"
256 " c16(ETH_P_IP),\n"
257 " /* IPv4 Version, IHL, TOS */\n"
258 " 0b01000101, 0,\n"
259 " /* IPv4 Total Len */\n"
260 " c16(59),\n"
261 " /* IPv4 Ident */\n"
262 " drnd(2),\n"
263 " /* IPv4 Flags, Frag Off */\n"
264 " 0b01000000, 0,\n"
265 " /* IPv4 TTL */\n"
266 " 64,\n"
267 " /* Proto TCP */\n"
268 " 0x06,\n"
269 " /* IPv4 Checksum (IP header from, to) */\n"
270 " csumip(14, 33),\n"
271 " /* Source IP */\n"
272 " drnd(4),\n"
273 " /* Dest IP */\n"
274 " drnd(4),\n"
275 " /* TCP Source Port */\n"
276 " drnd(2),\n"
277 " /* TCP Dest Port */\n"
278 " c16(80),\n"
279 " /* TCP Sequence Number */\n"
280 " drnd(4),\n"
281 " /* TCP Ackn. Number */\n"
282 " c32(0),\n"
283 " /* TCP Header length + TCP SYN/ECN Flag */\n"
284 " c16((0x8 << 12) | SYN | ECN)\n"
285 " /* Window Size */\n"
286 " c16(16),\n"
287 " /* TCP Checksum (offset IP, offset TCP) */\n"
288 " csumtcp(14, 34),\n"
289 " /* TCP Options */\n"
290 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
291 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
292 " /* Data blob */\n"
293 " \"gotcha!\",\n"
294 "}";
295 puts(e);
296 die();
299 static void version(void)
301 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
302 puts("http://www.netsniff-ng.org\n\n"
303 "Please report bugs to <bugs@netsniff-ng.org>\n"
304 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
305 "Swiss federal institute of technology (ETH Zurich)\n"
306 "License: GNU GPL version 2.0\n"
307 "This is free software: you are free to change and redistribute it.\n"
308 "There is NO WARRANTY, to the extent permitted by law.\n");
309 die();
312 static void apply_counter(int counter_id)
314 int j, i = counter_id;
315 size_t counter_max = packet_dyn[i].clen;
317 for (j = 0; j < counter_max; ++j) {
318 uint8_t val;
319 struct counter *counter = &packet_dyn[i].cnt[j];
321 val = counter->val - counter->min;
323 switch (counter->type) {
324 case TYPE_INC:
325 val = (val + counter->inc) % (counter->max - counter->min + 1);
326 break;
327 case TYPE_DEC:
328 val = (val - counter->inc) % (counter->min - counter->max + 1);
329 break;
330 default:
331 bug();
334 counter->val = val + counter->min;
335 packets[i].payload[counter->off] = val;
339 static void apply_randomizer(int rand_id)
341 int j, i = rand_id;
342 size_t rand_max = packet_dyn[i].rlen;
344 for (j = 0; j < rand_max; ++j) {
345 uint8_t val = (uint8_t) rand();
346 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
348 packets[i].payload[randomizer->off] = val;
352 /* Taken and modified from tcpdump, Copyright belongs to them! */
354 struct cksum_vec {
355 const u8 *ptr;
356 int len;
359 #define ADDCARRY(x) \
360 do { if ((x) > 65535) \
361 (x) -= 65535; \
362 } while (0)
364 #define REDUCE \
365 do { \
366 l_util.l = sum; \
367 sum = l_util.s[0] + l_util.s[1]; \
368 ADDCARRY(sum); \
369 } while (0)
371 static u16 __in_cksum(const struct cksum_vec *vec, int veclen)
373 register const u16 *w;
374 register int sum = 0, mlen = 0;
375 int byte_swapped = 0;
376 union {
377 u8 c[2];
378 u16 s;
379 } s_util;
380 union {
381 u16 s[2];
382 u32 l;
383 } l_util;
385 for (; veclen != 0; vec++, veclen--) {
386 if (vec->len == 0)
387 continue;
389 w = (const u16 *) (void *) vec->ptr;
391 if (mlen == -1) {
392 s_util.c[1] = *(const u8 *) w;
393 sum += s_util.s;
394 w = (const u16 *) (void *) ((const u8 *) w + 1);
395 mlen = vec->len - 1;
396 } else
397 mlen = vec->len;
399 if ((1 & (unsigned long) w) && (mlen > 0)) {
400 REDUCE;
401 sum <<= 8;
402 s_util.c[0] = *(const u8 *) w;
403 w = (const u16 *) (void *) ((const u8 *) w + 1);
404 mlen--;
405 byte_swapped = 1;
408 while ((mlen -= 32) >= 0) {
409 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
410 sum += w[4]; sum += w[5]; sum += w[6]; sum += w[7];
411 sum += w[8]; sum += w[9]; sum += w[10]; sum += w[11];
412 sum += w[12]; sum += w[13]; sum += w[14]; sum += w[15];
413 w += 16;
416 mlen += 32;
418 while ((mlen -= 8) >= 0) {
419 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
420 w += 4;
423 mlen += 8;
425 if (mlen == 0 && byte_swapped == 0)
426 continue;
428 REDUCE;
430 while ((mlen -= 2) >= 0) {
431 sum += *w++;
434 if (byte_swapped) {
435 REDUCE;
436 sum <<= 8;
437 byte_swapped = 0;
439 if (mlen == -1) {
440 s_util.c[1] = *(const u8 *) w;
441 sum += s_util.s;
442 mlen = 0;
443 } else
444 mlen = -1;
445 } else if (mlen == -1)
446 s_util.c[0] = *(const u8 *) w;
449 if (mlen == -1) {
450 s_util.c[1] = 0;
451 sum += s_util.s;
454 REDUCE;
456 return (~sum & 0xffff);
459 static u16 p4_csum(const struct ip *ip, const u8 *data, u16 len,
460 u8 next_proto)
462 struct cksum_vec vec[2];
463 struct pseudo_hdr {
464 u32 src;
465 u32 dst;
466 u8 mbz;
467 u8 proto;
468 u16 len;
469 } ph;
471 memset(&ph, 0, sizeof(ph));
472 ph.len = htons(len);
473 ph.mbz = 0;
474 ph.proto = next_proto;
475 ph.src = ip->ip_src.s_addr;
476 ph.dst = ip->ip_dst.s_addr;
478 vec[0].ptr = (const u8 *) (void *) &ph;
479 vec[0].len = sizeof(ph);
481 vec[1].ptr = data;
482 vec[1].len = len;
484 return __in_cksum(vec, 2);
487 static void apply_csum16(int csum_id)
489 int j, i = csum_id;
490 size_t csum_max = packet_dyn[i].slen;
492 for (j = 0; j < csum_max; ++j) {
493 uint16_t sum = 0;
494 struct csum16 *csum = &packet_dyn[i].csum[j];
496 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
498 switch (csum->which) {
499 case CSUM_IP:
500 if (csum->to >= packets[i].len)
501 csum->to = packets[i].len - 1;
502 sum = calc_csum(packets[i].payload + csum->from,
503 csum->to - csum->from + 1, 0);
504 break;
505 case CSUM_UDP:
506 sum = p4_csum((void *) packets[i].payload + csum->from,
507 packets[i].payload + csum->to,
508 (packets[i].len - csum->to),
509 IPPROTO_UDP);
510 break;
511 case CSUM_TCP:
512 sum = p4_csum((void *) packets[i].payload + csum->from,
513 packets[i].payload + csum->to,
514 (packets[i].len - csum->to),
515 IPPROTO_TCP);
516 break;
519 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
523 static struct cpu_stats *setup_shared_var(unsigned long cpus)
525 int fd;
526 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
527 struct cpu_stats *buff;
529 fmemset(zbuff, 0, sizeof(zbuff));
530 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
532 fd = creat(file, S_IRUSR | S_IWUSR);
533 bug_on(fd < 0);
534 close(fd);
536 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
537 S_IRUSR | S_IWUSR);
538 write_or_die(fd, zbuff, sizeof(zbuff));
540 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
541 MAP_SHARED, fd, 0);
542 if (buff == (void *) -1)
543 panic("Cannot setup shared variable!\n");
545 close(fd);
546 unlink(file);
548 memset(buff, 0, sizeof(zbuff));
550 return buff;
553 static void destroy_shared_var(void *buff, unsigned long cpus)
555 munmap(buff, cpus * sizeof(struct cpu_stats));
558 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
560 int i;
562 printf("{");
563 for (i = 0; i < len; ++i) {
564 if (i % 15 == 0)
565 printf("\n ");
566 printf("0x%02x, ", payload[i]);
568 printf("\n}\n");
569 fflush(stdout);
572 static inline unsigned short csum(unsigned short *buf, int nwords)
574 unsigned long sum;
576 for (sum = 0; nwords > 0; nwords--)
577 sum += *buf++;
578 sum = (sum >> 16) + (sum & 0xffff);
579 sum += (sum >> 16);
581 return ~sum;
584 static int xmit_smoke_setup(struct ctx *ctx)
586 int icmp_sock, ret, ttl = 64;
587 struct icmp_filter filter;
589 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
590 if (icmp_sock < 0)
591 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
593 filter.data = ~(1 << ICMP_ECHOREPLY);
595 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
596 if (ret < 0)
597 panic("Cannot install filter!\n");
599 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
600 if (ret < 0)
601 panic("Cannot set TTL!\n");
603 memset(&ctx->dest, 0, sizeof(ctx->dest));
604 ctx->dest.sin_family = AF_INET;
605 ctx->dest.sin_port = 0;
607 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
608 if (ret < 0)
609 panic("Cannot resolv address!\n");
611 return icmp_sock;
614 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
616 int ret, i, probes = 5;
617 short ident, cnt = 1;
618 uint8_t outpack[512], *data;
619 struct icmphdr *icmp;
620 struct iphdr *ip;
621 size_t len = sizeof(*icmp) + 56;
622 struct sockaddr_in from;
623 socklen_t from_len;
624 struct pollfd fds = {
625 .fd = icmp_sock,
626 .events = POLLIN,
629 while (probes-- > 0) {
630 ident = htons((short) rand());
632 memset(outpack, 0, sizeof(outpack));
633 icmp = (void *) outpack;
634 icmp->type = ICMP_ECHO;
635 icmp->code = 0;
636 icmp->checksum = 0;
637 icmp->un.echo.id = ident;
638 icmp->un.echo.sequence = htons(cnt++);
640 data = ((uint8_t *) outpack + sizeof(*icmp));
641 for (i = 0; i < 56; ++i)
642 data[i] = (uint8_t) rand();
644 icmp->checksum = csum((unsigned short *) outpack,
645 len / sizeof(unsigned short));
647 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
648 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
649 if (unlikely(ret != len))
650 panic("Cannot send out probe: %s!\n", strerror(errno));
652 ret = poll(&fds, 1, 500);
653 if (ret < 0)
654 panic("Poll failed!\n");
656 if (fds.revents & POLLIN) {
657 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
658 (struct sockaddr *) &from, &from_len);
659 if (unlikely(ret <= 0))
660 panic("Probe receive failed!\n");
661 if (unlikely(from_len != sizeof(ctx->dest)))
662 continue;
663 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
664 continue;
665 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
666 continue;
667 ip = (void *) outpack;
668 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
669 continue;
670 icmp = (void *) outpack + ip->ihl * 4;
671 if (unlikely(icmp->un.echo.id != ident))
672 continue;
674 return 0;
678 return -1;
681 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu)
683 int ret, icmp_sock = -1;
684 unsigned long num = 1, i = 0;
685 struct timeval start, end, diff;
686 unsigned long long tx_bytes = 0, tx_packets = 0;
687 struct packet_dyn *pktd;
688 struct sockaddr_ll saddr = {
689 .sll_family = PF_PACKET,
690 .sll_halen = ETH_ALEN,
691 .sll_ifindex = device_ifindex(ctx->device),
694 if (ctx->num > 0)
695 num = ctx->num;
697 if (ctx->smoke_test)
698 icmp_sock = xmit_smoke_setup(ctx);
700 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
702 bug_on(gettimeofday(&start, NULL));
704 while (likely(sigint == 0) && likely(num > 0)) {
705 pktd = &packet_dyn[i];
706 if (pktd->clen + pktd->rlen + pktd->slen) {
707 apply_counter(i);
708 apply_randomizer(i);
709 apply_csum16(i);
711 retry:
712 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
713 (struct sockaddr *) &saddr, sizeof(saddr));
714 if (unlikely(ret < 0)) {
715 if (errno == ENOBUFS) {
716 sched_yield();
717 goto retry;
720 panic("Sendto error: %s!\n", strerror(errno));
723 tx_bytes += packets[i].len;
724 tx_packets++;
726 if (ctx->smoke_test) {
727 ret = xmit_smoke_probe(icmp_sock, ctx);
728 if (unlikely(ret < 0)) {
729 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
730 printf(" Remote host seems to be unresponsive to ICMP pings!\n");
731 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
732 i, seed);
734 dump_trafgen_snippet(packets[i].payload, packets[i].len);
735 break;
739 if (!ctx->rand) {
740 i++;
741 if (i >= plen)
742 i = 0;
743 } else
744 i = rand() % plen;
746 if (ctx->num > 0)
747 num--;
749 if (ctx->gap > 0)
750 usleep(ctx->gap);
753 bug_on(gettimeofday(&end, NULL));
754 diff = tv_subtract(end, start);
756 if (ctx->smoke_test)
757 close(icmp_sock);
759 stats[cpu].tx_packets = tx_packets;
760 stats[cpu].tx_bytes = tx_bytes;
761 stats[cpu].tv_sec = diff.tv_sec;
762 stats[cpu].tv_usec = diff.tv_usec;
764 stats[cpu].state |= CPU_STATS_STATE_RES;
767 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu)
769 int ifindex = device_ifindex(ctx->device);
770 uint8_t *out = NULL;
771 unsigned int it = 0;
772 unsigned long num = 1, i = 0, size;
773 struct ring tx_ring;
774 struct frame_map *hdr;
775 struct timeval start, end, diff;
776 struct packet_dyn *pktd;
777 unsigned long long tx_bytes = 0, tx_packets = 0;
779 fmemset(&tx_ring, 0, sizeof(tx_ring));
781 size = ring_size(ctx->device, ctx->reserve_size);
783 set_sock_prio(sock, 512);
784 set_packet_loss_discard(sock);
786 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
787 create_tx_ring(sock, &tx_ring, ctx->verbose);
788 mmap_tx_ring(sock, &tx_ring);
789 alloc_tx_ring_frames(&tx_ring);
790 bind_tx_ring(sock, &tx_ring, ifindex);
792 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
794 if (ctx->kpull)
795 interval = ctx->kpull;
796 if (ctx->num > 0)
797 num = ctx->num;
799 itimer.it_interval.tv_sec = 0;
800 itimer.it_interval.tv_usec = interval;
802 itimer.it_value.tv_sec = 0;
803 itimer.it_value.tv_usec = interval;
805 setitimer(ITIMER_REAL, &itimer, NULL);
807 bug_on(gettimeofday(&start, NULL));
809 while (likely(sigint == 0) && likely(num > 0)) {
810 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
811 hdr = tx_ring.frames[it].iov_base;
813 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
814 * sizeof(struct sockaddr_ll); */
815 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
817 hdr->tp_h.tp_snaplen = packets[i].len;
818 hdr->tp_h.tp_len = packets[i].len;
820 pktd = &packet_dyn[i];
821 if (pktd->clen + pktd->rlen + pktd->slen) {
822 apply_counter(i);
823 apply_randomizer(i);
824 apply_csum16(i);
827 fmemcpy(out, packets[i].payload, packets[i].len);
829 tx_bytes += packets[i].len;
830 tx_packets++;
832 if (!ctx->rand) {
833 i++;
834 if (i >= plen)
835 i = 0;
836 } else
837 i = rand() % plen;
839 kernel_may_pull_from_tx(&hdr->tp_h);
841 it++;
842 if (it >= tx_ring.layout.tp_frame_nr)
843 it = 0;
845 if (ctx->num > 0)
846 num--;
848 if (unlikely(sigint == 1))
849 break;
853 bug_on(gettimeofday(&end, NULL));
854 diff = tv_subtract(end, start);
856 destroy_tx_ring(sock, &tx_ring);
858 stats[cpu].tx_packets = tx_packets;
859 stats[cpu].tx_bytes = tx_bytes;
860 stats[cpu].tv_sec = diff.tv_sec;
861 stats[cpu].tv_usec = diff.tv_usec;
863 stats[cpu].state |= CPU_STATS_STATE_RES;
866 static inline void __set_state(int cpu, sig_atomic_t s)
868 stats[cpu].state = s;
871 static inline sig_atomic_t __get_state(int cpu)
873 return stats[cpu].state;
876 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
878 int i;
879 unsigned long total;
881 for (i = 0, total = plen; i < ctx->cpus; i++) {
882 if (i == cpu)
883 continue;
885 while ((__get_state(i) & CPU_STATS_STATE_CFG) == 0 &&
886 sigint == 0)
887 sched_yield();
889 total += stats[i].cf_packets;
892 return total;
895 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
897 int i, cpu_sel;
898 unsigned long total;
899 long long delta_correction = 0;
901 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
902 if (i == cpu)
903 continue;
905 while ((__get_state(i) & CPU_STATS_STATE_CHK) == 0 &&
906 sigint == 0)
907 sched_yield();
909 total += stats[i].cd_packets;
912 if (total > orig)
913 delta_correction = -1 * ((long long) total - orig);
914 if (total < orig)
915 delta_correction = +1 * ((long long) orig - total);
917 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
918 if (stats[i].cd_packets > 0) {
919 if ((long long) stats[i].cd_packets +
920 delta_correction > 0) {
921 cpu_sel = i;
922 break;
927 if (cpu == cpu_sel)
928 ctx->num += delta_correction;
931 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
932 sig_atomic_t s)
934 stats[cpu].cf_packets = p;
935 stats[cpu].cf_bytes = b;
936 stats[cpu].state = s;
939 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
941 stats[cpu].cd_packets = p;
942 stats[cpu].state = s;
945 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
947 int i;
948 unsigned long plen_total, orig = ctx->num;
949 size_t mtu, total_len = 0;
951 bug_on(plen != dlen);
953 for (i = 0; i < plen; ++i)
954 total_len += packets[i].len;
956 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
957 plen_total = __wait_and_sum_others(ctx, cpu);
959 if (orig > 0) {
960 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
962 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
963 CPU_STATS_STATE_CFG);
964 __correct_global_delta(ctx, cpu, orig);
967 if (plen == 0) {
968 __set_state(cpu, CPU_STATS_STATE_RES);
969 return -1;
972 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
973 if (packets[i].len > mtu + 14)
974 panic("Device MTU < than packet%d's size!\n", i);
975 if (packets[i].len <= 14)
976 panic("Packet%d's size too short!\n", i);
979 return 0;
982 static void main_loop(struct ctx *ctx, char *confname, bool slow,
983 int cpu, bool invoke_cpp)
985 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
986 if (xmit_packet_precheck(ctx, cpu) < 0)
987 return;
989 if (cpu == 0) {
990 int i;
991 size_t total_len = 0, total_pkts = 0;
993 for (i = 0; i < ctx->cpus; ++i) {
994 total_len += stats[i].cf_bytes;
995 total_pkts += stats[i].cf_packets;
998 printf("%6zu packets to schedule\n", total_pkts);
999 printf("%6zu bytes in total\n", total_len);
1000 printf("Running! Hang up with ^C!\n\n");
1001 fflush(stdout);
1004 sock = pf_socket();
1006 if (slow)
1007 xmit_slowpath_or_die(ctx, cpu);
1008 else
1009 xmit_fastpath_or_die(ctx, cpu);
1011 close(sock);
1013 cleanup_packets();
1016 static unsigned int generate_srand_seed(void)
1018 int fd;
1019 unsigned int seed;
1021 fd = open("/dev/random", O_RDONLY);
1022 if (fd < 0)
1023 return time(0);
1025 read_or_die(fd, &seed, sizeof(seed));
1027 close(fd);
1028 return seed;
1031 int main(int argc, char **argv)
1033 bool slow = false, invoke_cpp = false, reseed = true;
1034 int c, opt_index, i, j, vals[4] = {0}, irq;
1035 char *confname = NULL, *ptr;
1036 unsigned long cpus_tmp;
1037 unsigned long long tx_packets, tx_bytes;
1038 struct ctx ctx;
1040 fmemset(&ctx, 0, sizeof(ctx));
1041 ctx.cpus = get_number_cpus_online();
1042 ctx.uid = getuid();
1043 ctx.gid = getgid();
1045 while ((c = getopt_long(argc, argv, short_options, long_options,
1046 &opt_index)) != EOF) {
1047 switch (c) {
1048 case 'h':
1049 help();
1050 break;
1051 case 'v':
1052 version();
1053 break;
1054 case 'e':
1055 example();
1056 break;
1057 case 'p':
1058 invoke_cpp = true;
1059 break;
1060 case 'V':
1061 ctx.verbose = true;
1062 break;
1063 case 'P':
1064 cpus_tmp = strtoul(optarg, NULL, 0);
1065 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
1066 ctx.cpus = cpus_tmp;
1067 break;
1068 case 'd':
1069 case 'o':
1070 ctx.device = xstrndup(optarg, IFNAMSIZ);
1071 break;
1072 case 'r':
1073 ctx.rand = true;
1074 break;
1075 case 's':
1076 slow = true;
1077 ctx.cpus = 1;
1078 ctx.smoke_test = true;
1079 ctx.rhost = xstrdup(optarg);
1080 break;
1081 case 'R':
1082 ctx.rfraw = true;
1083 break;
1084 case 'J':
1085 ctx.jumbo_support = true;
1086 break;
1087 case 'c':
1088 case 'i':
1089 confname = xstrdup(optarg);
1090 if (!strncmp("-", confname, strlen("-")))
1091 ctx.cpus = 1;
1092 break;
1093 case 'u':
1094 ctx.uid = strtoul(optarg, NULL, 0);
1095 ctx.enforce = true;
1096 break;
1097 case 'g':
1098 ctx.gid = strtoul(optarg, NULL, 0);
1099 ctx.enforce = true;
1100 break;
1101 case 'k':
1102 ctx.kpull = strtoul(optarg, NULL, 0);
1103 break;
1104 case 'E':
1105 seed = strtoul(optarg, NULL, 0);
1106 reseed = false;
1107 break;
1108 case 'n':
1109 ctx.num = strtoul(optarg, NULL, 0);
1110 break;
1111 case 't':
1112 slow = true;
1113 ctx.gap = strtoul(optarg, NULL, 0);
1114 if (ctx.gap > 0)
1115 /* Fall back to single core to not
1116 * mess up correct timing. We are slow
1117 * anyway!
1119 ctx.cpus = 1;
1120 break;
1121 case 'S':
1122 ptr = optarg;
1123 ctx.reserve_size = 0;
1125 for (j = i = strlen(optarg); i > 0; --i) {
1126 if (!isdigit(optarg[j - i]))
1127 break;
1128 ptr++;
1131 if (!strncmp(ptr, "KB", strlen("KB")))
1132 ctx.reserve_size = 1 << 10;
1133 else if (!strncmp(ptr, "MB", strlen("MB")))
1134 ctx.reserve_size = 1 << 20;
1135 else if (!strncmp(ptr, "GB", strlen("GB")))
1136 ctx.reserve_size = 1 << 30;
1137 else
1138 panic("Syntax error in ring size param!\n");
1139 *ptr = 0;
1141 ctx.reserve_size *= strtol(optarg, NULL, 0);
1142 break;
1143 case '?':
1144 switch (optopt) {
1145 case 'd':
1146 case 'c':
1147 case 'n':
1148 case 'S':
1149 case 's':
1150 case 'P':
1151 case 'o':
1152 case 'E':
1153 case 'i':
1154 case 'k':
1155 case 'u':
1156 case 'g':
1157 case 't':
1158 panic("Option -%c requires an argument!\n",
1159 optopt);
1160 default:
1161 if (isprint(optopt))
1162 whine("Unknown option character "
1163 "`0x%X\'!\n", optopt);
1164 die();
1166 default:
1167 break;
1171 if (argc < 5)
1172 help();
1173 if (ctx.device == NULL)
1174 panic("No networking device given!\n");
1175 if (confname == NULL)
1176 panic("No configuration file given!\n");
1177 if (device_mtu(ctx.device) == 0)
1178 panic("This is no networking device!\n");
1179 if (!ctx.rfraw && device_up_and_running(ctx.device) == 0)
1180 panic("Networking device not running!\n");
1182 register_signal(SIGINT, signal_handler);
1183 register_signal(SIGHUP, signal_handler);
1184 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1186 header();
1188 set_system_socket_memory(vals);
1189 xlockme();
1191 if (ctx.rfraw) {
1192 ctx.device_trans = xstrdup(ctx.device);
1193 xfree(ctx.device);
1195 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1196 sleep(0);
1199 irq = device_irq_number(ctx.device);
1200 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1202 if (ctx.num > 0 && ctx.num <= ctx.cpus)
1203 ctx.cpus = 1;
1205 stats = setup_shared_var(ctx.cpus);
1207 for (i = 0; i < ctx.cpus; i++) {
1208 pid_t pid = fork();
1210 switch (pid) {
1211 case 0:
1212 if (reseed)
1213 seed = generate_srand_seed();
1214 srand(seed);
1216 cpu_affinity(i);
1217 main_loop(&ctx, confname, slow, i, invoke_cpp);
1219 goto thread_out;
1220 case -1:
1221 panic("Cannot fork processes!\n");
1225 for (i = 0; i < ctx.cpus; i++) {
1226 int status;
1228 wait(&status);
1229 if (WEXITSTATUS(status) == EXIT_FAILURE)
1230 die();
1233 if (ctx.rfraw)
1234 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1236 reset_system_socket_memory(vals);
1238 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1239 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1240 sched_yield();
1242 tx_packets += stats[i].tx_packets;
1243 tx_bytes += stats[i].tx_bytes;
1246 fflush(stdout);
1247 printf("\n");
1248 printf("\r%12llu packets outgoing\n", tx_packets);
1249 printf("\r%12llu bytes outgoing\n", tx_bytes);
1250 for (i = 0; i < ctx.cpus; i++) {
1251 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1252 stats[i].tv_sec, stats[i].tv_usec, i,
1253 stats[i].tx_packets);
1256 thread_out:
1257 xunlockme();
1258 destroy_shared_var(stats, ctx.cpus);
1260 free(ctx.device);
1261 free(ctx.device_trans);
1262 free(ctx.rhost);
1263 free(confname);
1265 return 0;