pcap_rw: simplify code by using raw
[netsniff-ng.git] / trafgen.c
blob12c2ab4da7ee78cc5a16b78be8fe8ef61563db94
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 #ifndef ICMP_FILTER
126 # define ICMP_FILTER 1
128 struct icmp_filter {
129 __u32 data;
131 #endif
133 static void signal_handler(int number)
135 switch (number) {
136 case SIGINT:
137 sigint = 1;
138 case SIGHUP:
139 default:
140 break;
144 static void timer_elapsed(int number)
146 itimer.it_interval.tv_sec = 0;
147 itimer.it_interval.tv_usec = interval;
149 itimer.it_value.tv_sec = 0;
150 itimer.it_value.tv_usec = interval;
152 pull_and_flush_tx_ring(sock);
153 setitimer(ITIMER_REAL, &itimer, NULL);
156 static void header(void)
158 printf("%s%s%s\n", colorize_start(bold), "trafgen " VERSION_STRING, colorize_end());
161 static void help(void)
163 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
164 puts("http://www.netsniff-ng.org\n\n"
165 "Usage: trafgen [options]\n"
166 "Options:\n"
167 " -o|-d|--out|--dev <netdev> Networking device i.e., eth0\n"
168 " -i|-c|--in|--conf <cfg-file/-> Packet configuration file/stdin\n"
169 " -p|--cpp Run packet config through C preprocessor\n"
170 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
171 " -R|--rfraw Inject raw 802.11 frames\n"
172 " -s|--smoke-test <ipv4-receiver> Probe if machine survived fuzz-tested packet\n"
173 " -n|--num <uint> Number of packets until exit (def: 0)\n"
174 " -r|--rand Randomize packet selection (def: round robin)\n"
175 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
176 " -t|--gap <uint> Interpacket gap in us (approx)\n"
177 " -S|--ring-size <size> Manually set mmap size (KB/MB/GB): e.g.\'10MB\'\n"
178 " -k|--kernel-pull <uint> Kernel batch interval in us (def: 10us)\n"
179 " -E|--seed <uint> Manually set srand(3) seed\n"
180 " -u|--user <userid> Drop privileges and change to userid\n"
181 " -g|--group <groupid> Drop privileges and change to groupid\n"
182 " -V|--verbose Be more verbose\n"
183 " -v|--version Show version\n"
184 " -e|--example Show built-in packet config example\n"
185 " -h|--help Guess what?!\n\n"
186 "Examples:\n"
187 " See trafgen.txf for configuration file examples.\n"
188 " trafgen --dev eth0 --conf trafgen.cfg\n"
189 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
190 " trafgen --dev eth0 --conf trafgen.cfg --smoke-test 10.0.0.1\n"
191 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
192 " trafgen --dev eth0 --conf trafgen.cfg --rand --gap 1000\n"
193 " trafgen --dev eth0 --conf trafgen.cfg --rand --num 1400000 -k1000\n"
194 " trafgen --dev eth0 --conf trafgen.cfg -u `id -u bob` -g `id -g bob`\n\n"
195 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
196 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
197 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
198 " Run packet only on CPU1-2: cpu(1:2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
199 "Note:\n"
200 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
201 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
202 " we assume the kernel crashed, thus we print the packet and quit.\n"
203 " In case you find a ping-of-death, please mention trafgen in your\n"
204 " commit message of the fix!\n\n"
205 " For introducing bit errors, delays with random variation and more,\n"
206 " make use of tc(8) with its difference disciplines (e.g. netem).\n\n"
207 " For generating different package distributions, you can use some\n"
208 " scripting to generate a trafgen config file with packet ratios as:\n\n"
209 " IMIX 64:7, 570:4, 1518:1\n"
210 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
211 " Cisco 64:7, 594:4, 1518:1\n"
212 " RPR Trimodal 64:60, 512:20, 1518:20\n"
213 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n\n"
214 "Please report bugs to <bugs@netsniff-ng.org>\n"
215 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
216 "Swiss federal institute of technology (ETH Zurich)\n"
217 "License: GNU GPL version 2.0\n"
218 "This is free software: you are free to change and redistribute it.\n"
219 "There is NO WARRANTY, to the extent permitted by law.\n");
220 die();
223 static void example(void)
225 const char *e =
226 "/* Note: dynamic elements make trafgen slower! */\n\n"
227 "#define ETH_P_IP 0x0800\n\n"
228 "#define SYN (1 << 1)\n"
229 "#define ECN (1 << 6)\n\n"
230 "{\n"
231 " /* MAC Destination */\n"
232 " fill(0xff, 6),\n"
233 " /* MAC Source */\n"
234 " 0x00, 0x02, 0xb3, drnd(3),\n"
235 " /* IPv4 Protocol */\n"
236 " c16(ETH_P_IP),\n"
237 " /* IPv4 Version, IHL, TOS */\n"
238 " 0b01000101, 0,\n"
239 " /* IPv4 Total Len */\n"
240 " c16(59),\n"
241 " /* IPv4 Ident */\n"
242 " drnd(2),\n"
243 " /* IPv4 Flags, Frag Off */\n"
244 " 0b01000000, 0,\n"
245 " /* IPv4 TTL */\n"
246 " 64,\n"
247 " /* Proto TCP */\n"
248 " 0x06,\n"
249 " /* IPv4 Checksum (IP header from, to) */\n"
250 " csumip(14, 33),\n"
251 " /* Source IP */\n"
252 " drnd(4),\n"
253 " /* Dest IP */\n"
254 " drnd(4),\n"
255 " /* TCP Source Port */\n"
256 " drnd(2),\n"
257 " /* TCP Dest Port */\n"
258 " c16(80),\n"
259 " /* TCP Sequence Number */\n"
260 " drnd(4),\n"
261 " /* TCP Ackn. Number */\n"
262 " c32(0),\n"
263 " /* TCP Header length + TCP SYN/ECN Flag */\n"
264 " c16((0x8 << 12) | SYN | ECN)\n"
265 " /* Window Size */\n"
266 " c16(16),\n"
267 " /* TCP Checksum (offset IP, offset TCP) */\n"
268 " csumtcp(14, 34),\n"
269 " /* TCP Options */\n"
270 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
271 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
272 " /* Data blob */\n"
273 " \"gotcha!\",\n"
274 "}";
275 puts(e);
276 die();
279 static void version(void)
281 printf("\ntrafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
282 puts("http://www.netsniff-ng.org\n\n"
283 "Please report bugs to <bugs@netsniff-ng.org>\n"
284 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
285 "Swiss federal institute of technology (ETH Zurich)\n"
286 "License: GNU GPL version 2.0\n"
287 "This is free software: you are free to change and redistribute it.\n"
288 "There is NO WARRANTY, to the extent permitted by law.\n");
289 die();
292 static void apply_counter(int counter_id)
294 int j, i = counter_id;
295 size_t counter_max = packet_dyn[i].clen;
297 for (j = 0; j < counter_max; ++j) {
298 uint8_t val;
299 struct counter *counter = &packet_dyn[i].cnt[j];
301 val = counter->val - counter->min;
303 switch (counter->type) {
304 case TYPE_INC:
305 val = (val + counter->inc) % (counter->max - counter->min + 1);
306 break;
307 case TYPE_DEC:
308 val = (val - counter->inc) % (counter->min - counter->max + 1);
309 break;
310 default:
311 bug();
314 counter->val = val + counter->min;
315 packets[i].payload[counter->off] = val;
319 static void apply_randomizer(int rand_id)
321 int j, i = rand_id;
322 size_t rand_max = packet_dyn[i].rlen;
324 for (j = 0; j < rand_max; ++j) {
325 uint8_t val = (uint8_t) rand();
326 struct randomizer *randomizer = &packet_dyn[i].rnd[j];
328 packets[i].payload[randomizer->off] = val;
332 /* Taken and modified from tcpdump, Copyright belongs to them! */
334 struct cksum_vec {
335 const u8 *ptr;
336 int len;
339 #define ADDCARRY(x) \
340 do { if ((x) > 65535) \
341 (x) -= 65535; \
342 } while (0)
344 #define REDUCE \
345 do { \
346 l_util.l = sum; \
347 sum = l_util.s[0] + l_util.s[1]; \
348 ADDCARRY(sum); \
349 } while (0)
351 static u16 __in_cksum(const struct cksum_vec *vec, int veclen)
353 register const u16 *w;
354 register int sum = 0, mlen = 0;
355 int byte_swapped = 0;
356 union {
357 u8 c[2];
358 u16 s;
359 } s_util;
360 union {
361 u16 s[2];
362 u32 l;
363 } l_util;
365 for (; veclen != 0; vec++, veclen--) {
366 if (vec->len == 0)
367 continue;
369 w = (const u16 *) (void *) vec->ptr;
371 if (mlen == -1) {
372 s_util.c[1] = *(const u8 *) w;
373 sum += s_util.s;
374 w = (const u16 *) (void *) ((const u8 *) w + 1);
375 mlen = vec->len - 1;
376 } else
377 mlen = vec->len;
379 if ((1 & (unsigned long) w) && (mlen > 0)) {
380 REDUCE;
381 sum <<= 8;
382 s_util.c[0] = *(const u8 *) w;
383 w = (const u16 *) (void *) ((const u8 *) w + 1);
384 mlen--;
385 byte_swapped = 1;
388 while ((mlen -= 32) >= 0) {
389 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
390 sum += w[4]; sum += w[5]; sum += w[6]; sum += w[7];
391 sum += w[8]; sum += w[9]; sum += w[10]; sum += w[11];
392 sum += w[12]; sum += w[13]; sum += w[14]; sum += w[15];
393 w += 16;
396 mlen += 32;
398 while ((mlen -= 8) >= 0) {
399 sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
400 w += 4;
403 mlen += 8;
405 if (mlen == 0 && byte_swapped == 0)
406 continue;
408 REDUCE;
410 while ((mlen -= 2) >= 0) {
411 sum += *w++;
414 if (byte_swapped) {
415 REDUCE;
416 sum <<= 8;
417 byte_swapped = 0;
419 if (mlen == -1) {
420 s_util.c[1] = *(const u8 *) w;
421 sum += s_util.s;
422 mlen = 0;
423 } else
424 mlen = -1;
425 } else if (mlen == -1)
426 s_util.c[0] = *(const u8 *) w;
429 if (mlen == -1) {
430 s_util.c[1] = 0;
431 sum += s_util.s;
434 REDUCE;
436 return (~sum & 0xffff);
439 static u16 p4_csum(const struct ip *ip, const u8 *data, u16 len,
440 u8 next_proto)
442 struct cksum_vec vec[2];
443 struct pseudo_hdr {
444 u32 src;
445 u32 dst;
446 u8 mbz;
447 u8 proto;
448 u16 len;
449 } ph;
451 memset(&ph, 0, sizeof(ph));
452 ph.len = htons(len);
453 ph.mbz = 0;
454 ph.proto = next_proto;
455 ph.src = ip->ip_src.s_addr;
456 ph.dst = ip->ip_dst.s_addr;
458 vec[0].ptr = (const u8 *) (void *) &ph;
459 vec[0].len = sizeof(ph);
461 vec[1].ptr = data;
462 vec[1].len = len;
464 return __in_cksum(vec, 2);
467 static void apply_csum16(int csum_id)
469 int j, i = csum_id;
470 size_t csum_max = packet_dyn[i].slen;
472 for (j = 0; j < csum_max; ++j) {
473 uint16_t sum = 0;
474 struct csum16 *csum = &packet_dyn[i].csum[j];
476 fmemset(&packets[i].payload[csum->off], 0, sizeof(sum));
478 switch (csum->which) {
479 case CSUM_IP:
480 if (csum->to >= packets[i].len)
481 csum->to = packets[i].len - 1;
482 sum = calc_csum(packets[i].payload + csum->from,
483 csum->to - csum->from + 1, 0);
484 break;
485 case CSUM_UDP:
486 sum = p4_csum((void *) packets[i].payload + csum->from,
487 packets[i].payload + csum->to,
488 (packets[i].len - csum->to),
489 IPPROTO_UDP);
490 break;
491 case CSUM_TCP:
492 sum = p4_csum((void *) packets[i].payload + csum->from,
493 packets[i].payload + csum->to,
494 (packets[i].len - csum->to),
495 IPPROTO_TCP);
496 break;
499 fmemcpy(&packets[i].payload[csum->off], &sum, sizeof(sum));
503 static struct cpu_stats *setup_shared_var(unsigned long cpus)
505 int fd;
506 char zbuff[cpus * sizeof(struct cpu_stats)], file[256];
507 struct cpu_stats *buff;
509 fmemset(zbuff, 0, sizeof(zbuff));
510 slprintf(file, sizeof(file), ".tmp_mmap.%u", (unsigned int) rand());
512 fd = creat(file, S_IRUSR | S_IWUSR);
513 bug_on(fd < 0);
514 close(fd);
516 fd = open_or_die_m(file, O_RDWR | O_CREAT | O_TRUNC,
517 S_IRUSR | S_IWUSR);
518 write_or_die(fd, zbuff, sizeof(zbuff));
520 buff = (void *) mmap(0, sizeof(zbuff), PROT_READ | PROT_WRITE,
521 MAP_SHARED, fd, 0);
522 if (buff == (void *) -1)
523 panic("Cannot setup shared variable!\n");
525 close(fd);
526 unlink(file);
528 memset(buff, 0, sizeof(zbuff));
530 return buff;
533 static void destroy_shared_var(void *buff, unsigned long cpus)
535 munmap(buff, cpus * sizeof(struct cpu_stats));
538 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
540 int i;
542 printf("{");
543 for (i = 0; i < len; ++i) {
544 if (i % 15 == 0)
545 printf("\n ");
546 printf("0x%02x, ", payload[i]);
548 printf("\n}\n");
549 fflush(stdout);
552 static inline unsigned short csum(unsigned short *buf, int nwords)
554 unsigned long sum;
556 for (sum = 0; nwords > 0; nwords--)
557 sum += *buf++;
558 sum = (sum >> 16) + (sum & 0xffff);
559 sum += (sum >> 16);
561 return ~sum;
564 static int xmit_smoke_setup(struct ctx *ctx)
566 int icmp_sock, ret, ttl = 64;
567 struct icmp_filter filter;
569 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
570 if (icmp_sock < 0)
571 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
573 filter.data = ~(1 << ICMP_ECHOREPLY);
575 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
576 if (ret < 0)
577 panic("Cannot install filter!\n");
579 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
580 if (ret < 0)
581 panic("Cannot set TTL!\n");
583 memset(&ctx->dest, 0, sizeof(ctx->dest));
584 ctx->dest.sin_family = AF_INET;
585 ctx->dest.sin_port = 0;
587 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
588 if (ret < 0)
589 panic("Cannot resolv address!\n");
591 return icmp_sock;
594 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
596 int ret, i, probes = 5;
597 short ident, cnt = 1;
598 uint8_t outpack[512], *data;
599 struct icmphdr *icmp;
600 struct iphdr *ip;
601 size_t len = sizeof(*icmp) + 56;
602 struct sockaddr_in from;
603 socklen_t from_len;
604 struct pollfd fds = {
605 .fd = icmp_sock,
606 .events = POLLIN,
609 while (probes-- > 0) {
610 ident = htons((short) rand());
612 memset(outpack, 0, sizeof(outpack));
613 icmp = (void *) outpack;
614 icmp->type = ICMP_ECHO;
615 icmp->code = 0;
616 icmp->checksum = 0;
617 icmp->un.echo.id = ident;
618 icmp->un.echo.sequence = htons(cnt++);
620 data = ((uint8_t *) outpack + sizeof(*icmp));
621 for (i = 0; i < 56; ++i)
622 data[i] = (uint8_t) rand();
624 icmp->checksum = csum((unsigned short *) outpack,
625 len / sizeof(unsigned short));
627 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
628 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
629 if (unlikely(ret != len))
630 panic("Cannot send out probe: %s!\n", strerror(errno));
632 ret = poll(&fds, 1, 500);
633 if (ret < 0)
634 panic("Poll failed!\n");
636 if (fds.revents & POLLIN) {
637 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
638 (struct sockaddr *) &from, &from_len);
639 if (unlikely(ret <= 0))
640 panic("Probe receive failed!\n");
641 if (unlikely(from_len != sizeof(ctx->dest)))
642 continue;
643 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
644 continue;
645 if (unlikely(ret < sizeof(*ip) + sizeof(*icmp)))
646 continue;
647 ip = (void *) outpack;
648 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > ret))
649 continue;
650 icmp = (void *) outpack + ip->ihl * 4;
651 if (unlikely(icmp->un.echo.id != ident))
652 continue;
654 return 0;
658 return -1;
661 static void xmit_slowpath_or_die(struct ctx *ctx, int cpu)
663 int ret, icmp_sock = -1;
664 unsigned long num = 1, i = 0;
665 struct timeval start, end, diff;
666 unsigned long long tx_bytes = 0, tx_packets = 0;
667 struct packet_dyn *pktd;
668 struct sockaddr_ll saddr = {
669 .sll_family = PF_PACKET,
670 .sll_halen = ETH_ALEN,
671 .sll_ifindex = device_ifindex(ctx->device),
674 if (ctx->num > 0)
675 num = ctx->num;
677 if (ctx->smoke_test)
678 icmp_sock = xmit_smoke_setup(ctx);
680 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
682 bug_on(gettimeofday(&start, NULL));
684 while (likely(sigint == 0) && likely(num > 0)) {
685 pktd = &packet_dyn[i];
686 if (pktd->clen + pktd->rlen + pktd->slen) {
687 apply_counter(i);
688 apply_randomizer(i);
689 apply_csum16(i);
691 retry:
692 ret = sendto(sock, packets[i].payload, packets[i].len, 0,
693 (struct sockaddr *) &saddr, sizeof(saddr));
694 if (unlikely(ret < 0)) {
695 if (errno == ENOBUFS) {
696 sched_yield();
697 goto retry;
700 panic("Sendto error: %s!\n", strerror(errno));
703 tx_bytes += packets[i].len;
704 tx_packets++;
706 if (ctx->smoke_test) {
707 ret = xmit_smoke_probe(icmp_sock, ctx);
708 if (unlikely(ret < 0)) {
709 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
710 printf(" Remote host seems to be unresponsive to ICMP pings!\n");
711 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
712 i, seed);
714 dump_trafgen_snippet(packets[i].payload, packets[i].len);
715 break;
719 if (!ctx->rand) {
720 i++;
721 if (i >= plen)
722 i = 0;
723 } else
724 i = rand() % plen;
726 if (ctx->num > 0)
727 num--;
729 if (ctx->gap > 0)
730 usleep(ctx->gap);
733 bug_on(gettimeofday(&end, NULL));
734 diff = tv_subtract(end, start);
736 if (ctx->smoke_test)
737 close(icmp_sock);
739 stats[cpu].tx_packets = tx_packets;
740 stats[cpu].tx_bytes = tx_bytes;
741 stats[cpu].tv_sec = diff.tv_sec;
742 stats[cpu].tv_usec = diff.tv_usec;
744 stats[cpu].state |= CPU_STATS_STATE_RES;
747 static void xmit_fastpath_or_die(struct ctx *ctx, int cpu)
749 int ifindex = device_ifindex(ctx->device);
750 uint8_t *out = NULL;
751 unsigned int it = 0;
752 unsigned long num = 1, i = 0, size;
753 struct ring tx_ring;
754 struct frame_map *hdr;
755 struct timeval start, end, diff;
756 struct packet_dyn *pktd;
757 unsigned long long tx_bytes = 0, tx_packets = 0;
759 fmemset(&tx_ring, 0, sizeof(tx_ring));
761 size = ring_size(ctx->device, ctx->reserve_size);
763 set_sock_prio(sock, 512);
764 set_packet_loss_discard(sock);
766 setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
767 create_tx_ring(sock, &tx_ring, ctx->verbose);
768 mmap_tx_ring(sock, &tx_ring);
769 alloc_tx_ring_frames(&tx_ring);
770 bind_tx_ring(sock, &tx_ring, ifindex);
772 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
774 if (ctx->kpull)
775 interval = ctx->kpull;
776 if (ctx->num > 0)
777 num = ctx->num;
779 itimer.it_interval.tv_sec = 0;
780 itimer.it_interval.tv_usec = interval;
782 itimer.it_value.tv_sec = 0;
783 itimer.it_value.tv_usec = interval;
785 setitimer(ITIMER_REAL, &itimer, NULL);
787 bug_on(gettimeofday(&start, NULL));
789 while (likely(sigint == 0) && likely(num > 0)) {
790 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base) && likely(num > 0)) {
791 hdr = tx_ring.frames[it].iov_base;
793 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
794 * sizeof(struct sockaddr_ll); */
795 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
797 hdr->tp_h.tp_snaplen = packets[i].len;
798 hdr->tp_h.tp_len = packets[i].len;
800 pktd = &packet_dyn[i];
801 if (pktd->clen + pktd->rlen + pktd->slen) {
802 apply_counter(i);
803 apply_randomizer(i);
804 apply_csum16(i);
807 fmemcpy(out, packets[i].payload, packets[i].len);
809 tx_bytes += packets[i].len;
810 tx_packets++;
812 if (!ctx->rand) {
813 i++;
814 if (i >= plen)
815 i = 0;
816 } else
817 i = rand() % plen;
819 kernel_may_pull_from_tx(&hdr->tp_h);
821 it++;
822 if (it >= tx_ring.layout.tp_frame_nr)
823 it = 0;
825 if (ctx->num > 0)
826 num--;
828 if (unlikely(sigint == 1))
829 break;
833 bug_on(gettimeofday(&end, NULL));
834 diff = tv_subtract(end, start);
836 destroy_tx_ring(sock, &tx_ring);
838 stats[cpu].tx_packets = tx_packets;
839 stats[cpu].tx_bytes = tx_bytes;
840 stats[cpu].tv_sec = diff.tv_sec;
841 stats[cpu].tv_usec = diff.tv_usec;
843 stats[cpu].state |= CPU_STATS_STATE_RES;
846 static inline void __set_state(int cpu, sig_atomic_t s)
848 stats[cpu].state = s;
851 static inline sig_atomic_t __get_state(int cpu)
853 return stats[cpu].state;
856 static unsigned long __wait_and_sum_others(struct ctx *ctx, int cpu)
858 int i;
859 unsigned long total;
861 for (i = 0, total = plen; i < ctx->cpus; i++) {
862 if (i == cpu)
863 continue;
865 while ((__get_state(i) & CPU_STATS_STATE_CFG) == 0 &&
866 sigint == 0)
867 sched_yield();
869 total += stats[i].cf_packets;
872 return total;
875 static void __correct_global_delta(struct ctx *ctx, int cpu, unsigned long orig)
877 int i, cpu_sel;
878 unsigned long total;
879 long long delta_correction = 0;
881 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
882 if (i == cpu)
883 continue;
885 while ((__get_state(i) & CPU_STATS_STATE_CHK) == 0 &&
886 sigint == 0)
887 sched_yield();
889 total += stats[i].cd_packets;
892 if (total > orig)
893 delta_correction = -1 * ((long long) total - orig);
894 if (total < orig)
895 delta_correction = +1 * ((long long) orig - total);
897 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
898 if (stats[i].cd_packets > 0) {
899 if ((long long) stats[i].cd_packets +
900 delta_correction > 0) {
901 cpu_sel = i;
902 break;
907 if (cpu == cpu_sel)
908 ctx->num += delta_correction;
911 static void __set_state_cf(int cpu, unsigned long p, unsigned long b,
912 sig_atomic_t s)
914 stats[cpu].cf_packets = p;
915 stats[cpu].cf_bytes = b;
916 stats[cpu].state = s;
919 static void __set_state_cd(int cpu, unsigned long p, sig_atomic_t s)
921 stats[cpu].cd_packets = p;
922 stats[cpu].state = s;
925 static int xmit_packet_precheck(struct ctx *ctx, int cpu)
927 int i;
928 unsigned long plen_total, orig = ctx->num;
929 size_t mtu, total_len = 0;
931 bug_on(plen != dlen);
933 for (i = 0; i < plen; ++i)
934 total_len += packets[i].len;
936 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
937 plen_total = __wait_and_sum_others(ctx, cpu);
939 if (orig > 0) {
940 ctx->num = (unsigned long) nearbyint((1.0 * plen / plen_total) * orig);
942 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
943 CPU_STATS_STATE_CFG);
944 __correct_global_delta(ctx, cpu, orig);
947 if (plen == 0) {
948 __set_state(cpu, CPU_STATS_STATE_RES);
949 return -1;
952 for (mtu = device_mtu(ctx->device), i = 0; i < plen; ++i) {
953 if (packets[i].len > mtu + 14)
954 panic("Device MTU < than packet%d's size!\n", i);
955 if (packets[i].len <= 14)
956 panic("Packet%d's size too short!\n", i);
959 return 0;
962 static void main_loop(struct ctx *ctx, char *confname, bool slow,
963 int cpu, bool invoke_cpp)
965 compile_packets(confname, ctx->verbose, cpu, invoke_cpp);
966 if (xmit_packet_precheck(ctx, cpu) < 0)
967 return;
969 if (cpu == 0) {
970 int i;
971 size_t total_len = 0, total_pkts = 0;
973 for (i = 0; i < ctx->cpus; ++i) {
974 total_len += stats[i].cf_bytes;
975 total_pkts += stats[i].cf_packets;
978 printf("%6zu packets to schedule\n", total_pkts);
979 printf("%6zu bytes in total\n", total_len);
980 printf("Running! Hang up with ^C!\n\n");
981 fflush(stdout);
984 sock = pf_socket();
986 if (slow)
987 xmit_slowpath_or_die(ctx, cpu);
988 else
989 xmit_fastpath_or_die(ctx, cpu);
991 close(sock);
993 cleanup_packets();
996 static unsigned int generate_srand_seed(void)
998 int fd;
999 unsigned int seed;
1001 fd = open("/dev/urandom", O_RDONLY);
1002 if (fd < 0)
1003 return time(0);
1005 read_or_die(fd, &seed, sizeof(seed));
1007 close(fd);
1008 return seed;
1011 int main(int argc, char **argv)
1013 bool slow = false, invoke_cpp = false, reseed = true;
1014 int c, opt_index, i, j, vals[4] = {0}, irq;
1015 char *confname = NULL, *ptr;
1016 unsigned long cpus_tmp;
1017 unsigned long long tx_packets, tx_bytes;
1018 struct ctx ctx;
1020 fmemset(&ctx, 0, sizeof(ctx));
1021 ctx.cpus = get_number_cpus_online();
1022 ctx.uid = getuid();
1023 ctx.gid = getgid();
1025 while ((c = getopt_long(argc, argv, short_options, long_options,
1026 &opt_index)) != EOF) {
1027 switch (c) {
1028 case 'h':
1029 help();
1030 break;
1031 case 'v':
1032 version();
1033 break;
1034 case 'e':
1035 example();
1036 break;
1037 case 'p':
1038 invoke_cpp = true;
1039 break;
1040 case 'V':
1041 ctx.verbose = true;
1042 break;
1043 case 'P':
1044 cpus_tmp = strtoul(optarg, NULL, 0);
1045 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
1046 ctx.cpus = cpus_tmp;
1047 break;
1048 case 'd':
1049 case 'o':
1050 ctx.device = xstrndup(optarg, IFNAMSIZ);
1051 break;
1052 case 'r':
1053 ctx.rand = true;
1054 break;
1055 case 's':
1056 slow = true;
1057 ctx.cpus = 1;
1058 ctx.smoke_test = true;
1059 ctx.rhost = xstrdup(optarg);
1060 break;
1061 case 'R':
1062 ctx.rfraw = true;
1063 break;
1064 case 'J':
1065 ctx.jumbo_support = true;
1066 break;
1067 case 'c':
1068 case 'i':
1069 confname = xstrdup(optarg);
1070 if (!strncmp("-", confname, strlen("-")))
1071 ctx.cpus = 1;
1072 break;
1073 case 'u':
1074 ctx.uid = strtoul(optarg, NULL, 0);
1075 ctx.enforce = true;
1076 break;
1077 case 'g':
1078 ctx.gid = strtoul(optarg, NULL, 0);
1079 ctx.enforce = true;
1080 break;
1081 case 'k':
1082 ctx.kpull = strtoul(optarg, NULL, 0);
1083 break;
1084 case 'E':
1085 seed = strtoul(optarg, NULL, 0);
1086 reseed = false;
1087 break;
1088 case 'n':
1089 ctx.num = strtoul(optarg, NULL, 0);
1090 break;
1091 case 't':
1092 slow = true;
1093 ctx.gap = strtoul(optarg, NULL, 0);
1094 if (ctx.gap > 0)
1095 /* Fall back to single core to not
1096 * mess up correct timing. We are slow
1097 * anyway!
1099 ctx.cpus = 1;
1100 break;
1101 case 'S':
1102 ptr = optarg;
1103 ctx.reserve_size = 0;
1105 for (j = i = strlen(optarg); i > 0; --i) {
1106 if (!isdigit(optarg[j - i]))
1107 break;
1108 ptr++;
1111 if (!strncmp(ptr, "KB", strlen("KB")))
1112 ctx.reserve_size = 1 << 10;
1113 else if (!strncmp(ptr, "MB", strlen("MB")))
1114 ctx.reserve_size = 1 << 20;
1115 else if (!strncmp(ptr, "GB", strlen("GB")))
1116 ctx.reserve_size = 1 << 30;
1117 else
1118 panic("Syntax error in ring size param!\n");
1119 *ptr = 0;
1121 ctx.reserve_size *= strtol(optarg, NULL, 0);
1122 break;
1123 case '?':
1124 switch (optopt) {
1125 case 'd':
1126 case 'c':
1127 case 'n':
1128 case 'S':
1129 case 's':
1130 case 'P':
1131 case 'o':
1132 case 'E':
1133 case 'i':
1134 case 'k':
1135 case 'u':
1136 case 'g':
1137 case 't':
1138 panic("Option -%c requires an argument!\n",
1139 optopt);
1140 default:
1141 if (isprint(optopt))
1142 whine("Unknown option character "
1143 "`0x%X\'!\n", optopt);
1144 die();
1146 default:
1147 break;
1151 if (argc < 5)
1152 help();
1153 if (ctx.device == NULL)
1154 panic("No networking device given!\n");
1155 if (confname == NULL)
1156 panic("No configuration file given!\n");
1157 if (device_mtu(ctx.device) == 0)
1158 panic("This is no networking device!\n");
1159 if (!ctx.rfraw && device_up_and_running(ctx.device) == 0)
1160 panic("Networking device not running!\n");
1162 register_signal(SIGINT, signal_handler);
1163 register_signal(SIGHUP, signal_handler);
1164 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1166 header();
1168 set_system_socket_memory(vals, array_size(vals));
1169 xlockme();
1171 if (ctx.rfraw) {
1172 ctx.device_trans = xstrdup(ctx.device);
1173 xfree(ctx.device);
1175 enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
1176 sleep(0);
1179 irq = device_irq_number(ctx.device);
1180 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1182 if (ctx.num > 0 && ctx.num <= ctx.cpus)
1183 ctx.cpus = 1;
1185 stats = setup_shared_var(ctx.cpus);
1187 for (i = 0; i < ctx.cpus; i++) {
1188 pid_t pid = fork();
1190 switch (pid) {
1191 case 0:
1192 if (reseed)
1193 seed = generate_srand_seed();
1194 srand(seed);
1196 cpu_affinity(i);
1197 main_loop(&ctx, confname, slow, i, invoke_cpp);
1199 goto thread_out;
1200 case -1:
1201 panic("Cannot fork processes!\n");
1205 for (i = 0; i < ctx.cpus; i++) {
1206 int status;
1208 wait(&status);
1209 if (WEXITSTATUS(status) == EXIT_FAILURE)
1210 die();
1213 if (ctx.rfraw)
1214 leave_rfmon_mac80211(ctx.device_trans, ctx.device);
1216 reset_system_socket_memory(vals, array_size(vals));
1218 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1219 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1220 sched_yield();
1222 tx_packets += stats[i].tx_packets;
1223 tx_bytes += stats[i].tx_bytes;
1226 fflush(stdout);
1227 printf("\n");
1228 printf("\r%12llu packets outgoing\n", tx_packets);
1229 printf("\r%12llu bytes outgoing\n", tx_bytes);
1230 for (i = 0; i < ctx.cpus; i++) {
1231 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1232 stats[i].tv_sec, stats[i].tv_usec, i,
1233 stats[i].tx_packets);
1236 thread_out:
1237 xunlockme();
1238 destroy_shared_var(stats, ctx.cpus);
1240 free(ctx.device);
1241 free(ctx.device_trans);
1242 free(ctx.rhost);
1243 free(confname);
1245 return 0;