trafgen: allow to set packet rate in kpps and Mpps
[netsniff-ng-new.git] / trafgen.c
blob0f52cfe72dab2a3e7f478b2f5b0fe05d2273e080
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2011 - 2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,
4 * Swiss federal institute of technology (ETH Zurich)
5 * Subject to the GPL, version 2.
6 */
8 #define _GNU_SOURCE
10 #include <stdio.h>
11 #include <string.h>
12 #include <getopt.h>
13 #include <ctype.h>
14 #include <stdbool.h>
15 #include <sched.h>
16 #include <sys/socket.h>
17 #include <sys/types.h>
18 #include <sys/fsuid.h>
19 #include <sys/prctl.h>
20 #include <sys/stat.h>
21 #include <sys/wait.h>
22 #include <sys/mman.h>
23 #include <net/ethernet.h>
24 #include <netinet/in.h>
25 #include <netinet/ip.h>
26 #include <linux/icmp.h>
27 #include <linux/if.h>
28 #include <arpa/inet.h>
29 #include <signal.h>
30 #include <stdint.h>
31 #include <stdlib.h>
32 #include <fcntl.h>
33 #include <time.h>
34 #include <poll.h>
35 #include <netdb.h>
36 #include <math.h>
37 #include <unistd.h>
39 #include "xmalloc.h"
40 #include "die.h"
41 #include "str.h"
42 #include "sig.h"
43 #include "sock.h"
44 #include "cpus.h"
45 #include "lockme.h"
46 #include "privs.h"
47 #include "proc.h"
48 #include "ioops.h"
49 #include "irq.h"
50 #include "config.h"
51 #include "built_in.h"
52 #include "trafgen_conf.h"
53 #include "tprintf.h"
54 #include "timer.h"
55 #include "ring_tx.h"
56 #include "csum.h"
57 #include "trafgen_proto.h"
58 #include "pcap_io.h"
59 #include "trafgen_dev.h"
61 enum shaper_type {
62 SHAPER_NONE,
63 SHAPER_DELAY,
64 SHAPER_PKTS,
65 SHAPER_BYTES,
66 SHAPER_TSTAMP,
69 struct shaper {
70 enum shaper_type type;
71 unsigned long long sent;
72 unsigned long long rate;
73 struct timeval tstamp;
74 struct timespec delay;
75 struct timeval start;
76 struct timeval end;
79 struct ctx {
80 bool rand, rfraw, jumbo_support, verbose, smoke_test, enforce, qdisc_path;
81 size_t reserve_size;
82 struct dev_io *dev_out;
83 struct dev_io *dev_in;
84 unsigned long num;
85 unsigned int cpus;
86 uid_t uid; gid_t gid;
87 char *device, *rhost;
88 struct sockaddr_in dest;
89 struct shaper sh;
90 char *packet_str;
91 char *pcap_in;
94 struct cpu_stats {
95 unsigned long tv_sec, tv_usec;
96 unsigned long long tx_packets, tx_bytes;
97 unsigned long long cf_packets, cf_bytes;
98 unsigned long long cd_packets;
99 sig_atomic_t state;
102 static sig_atomic_t sigint = 0;
104 struct packet *packets = NULL;
105 size_t plen = 0;
107 struct packet_dyn *packet_dyn = NULL;
108 size_t dlen = 0;
110 static const char *short_options = "d:c:n:t:vJhS:rk:i:o:VRs:P:eE:pu:g:CHQqD:b:";
111 static const struct option long_options[] = {
112 {"dev", required_argument, NULL, 'd'},
113 {"out", required_argument, NULL, 'o'},
114 {"in", required_argument, NULL, 'i'},
115 {"conf", required_argument, NULL, 'c'},
116 {"num", required_argument, NULL, 'n'},
117 {"gap", required_argument, NULL, 't'},
118 {"rate", required_argument, NULL, 'b'},
119 {"cpus", required_argument, NULL, 'P'},
120 {"ring-size", required_argument, NULL, 'S'},
121 {"kernel-pull", required_argument, NULL, 'k'},
122 {"smoke-test", required_argument, NULL, 's'},
123 {"seed", required_argument, NULL, 'E'},
124 {"user", required_argument, NULL, 'u'},
125 {"group", required_argument, NULL, 'g'},
126 {"prio-high", no_argument, NULL, 'H'},
127 {"notouch-irq", no_argument, NULL, 'Q'},
128 {"no-sock-mem", no_argument, NULL, 'A'},
129 {"qdisc-path", no_argument, NULL, 'q'},
130 {"jumbo-support", no_argument, NULL, 'J'},
131 {"no-cpu-stats", no_argument, NULL, 'C'},
132 {"cpp", no_argument, NULL, 'p'},
133 {"define", required_argument, NULL, 'D'},
134 {"rfraw", no_argument, NULL, 'R'},
135 {"rand", no_argument, NULL, 'r'},
136 {"verbose", no_argument, NULL, 'V'},
137 {"version", no_argument, NULL, 'v'},
138 {"example", no_argument, NULL, 'e'},
139 {"help", no_argument, NULL, 'h'},
140 {NULL, 0, NULL, 0}
143 static const char *copyright =
144 "Please report bugs at https://github.com/netsniff-ng/netsniff-ng/issues\n"
145 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
146 "Swiss federal institute of technology (ETH Zurich)\n"
147 "License: GNU GPL version 2.0\n"
148 "This is free software: you are free to change and redistribute it.\n"
149 "There is NO WARRANTY, to the extent permitted by law.";
151 static struct cpu_stats *stats;
152 static unsigned int seed;
154 #define CPU_STATS_STATE_CFG 1
155 #define CPU_STATS_STATE_CHK 2
156 #define CPU_STATS_STATE_RES 4
158 #ifndef ICMP_FILTER
159 # define ICMP_FILTER 1
161 struct icmp_filter {
162 __u32 data;
164 #endif
166 #define SMOKE_N_PROBES 100
168 #define PKT_MIN_LEN 14
170 static void signal_handler(int number)
172 switch (number) {
173 case SIGINT:
174 case SIGQUIT:
175 case SIGTERM:
176 sigint = 1;
177 case SIGHUP:
178 default:
179 break;
183 static void __noreturn help(void)
185 printf("trafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING);
186 puts("http://www.netsniff-ng.org\n\n"
187 "Usage: trafgen [options] [packet]\n"
188 "Options:\n"
189 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
190 " -o|-d|--out|--dev <netdev|.cfg|.pcap> Networking device or configuration file i.e., eth0\n"
191 " -p|--cpp Run packet config through C preprocessor\n"
192 " -D|--define Add macro/define for C preprocessor\n"
193 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
194 " -R|--rfraw Inject raw 802.11 frames\n"
195 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
196 " -n|--num <uint> Number of packets until exit (def: 0)\n"
197 " -r|--rand Randomize packet selection (def: round robin)\n"
198 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
199 " -t|--gap <time> Set approx. interpacket gap (s/ms/us/ns, def: us)\n"
200 " -b|--rate <rate> Send traffic at specified rate (pps/kpps/Mpps/B/kB/MB/GB/kbit/Mbit/Gbit/KiB/MiB/GiB)\n"
201 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
202 " -E|--seed <uint> Manually set srand(3) seed\n"
203 " -u|--user <userid> Drop privileges and change to userid\n"
204 " -g|--group <groupid> Drop privileges and change to groupid\n"
205 " -H|--prio-high Make this high priority process\n"
206 " -A|--no-sock-mem Don't tune core socket memory\n"
207 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
208 " -q|--qdisc-path Enable qdisc kernel path (default off since 3.14)\n"
209 " -V|--verbose Be more verbose\n"
210 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
211 " -v|--version Show version and exit\n"
212 " -e|--example Show built-in packet config example\n"
213 " -h|--help Guess what?!\n\n"
214 "Examples:\n"
215 " trafgen --dev eth0 --conf trafgen.cfg\n"
216 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
217 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
218 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
219 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000us\n"
220 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
221 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n"
222 " trafgen --dev eth0 '{ fill(0xff, 6), 0x00, 0x02, 0xb3, rnd(3), c16(0x0800), fill(0xca, 64) }'\n\n"
223 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
224 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
225 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
226 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
227 "Generate config files from existing pcap using netsniff-ng:\n"
228 " netsniff-ng --in dump.pcap --out dump.cfg\n\n"
229 "Note:\n"
230 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
231 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
232 " we assume the kernel crashed, thus we print the packet and quit.\n"
233 " In case you find a ping-of-death, please mention trafgen in your\n"
234 " commit message of the fix!\n\n"
235 " For introducing bit errors, delays with random variation and more,\n"
236 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
237 " For generating different package distributions, you can use scripting\n"
238 " to generate a trafgen config file with packet ratios as:\n\n"
239 " IMIX 64:7, 570:4, 1518:1\n"
240 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
241 " Cisco 64:7, 594:4, 1518:1\n"
242 " RPR Trimodal 64:60, 512:20, 1518:20\n"
243 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n");
244 puts(copyright);
245 die();
248 static void __noreturn example(void)
250 const char *e =
251 "/* Note: dynamic elements make trafgen slower! */\n"
252 "#include <stddef.h>\n\n"
253 "{\n"
254 " /* MAC Destination */\n"
255 " fill(0xff, ETH_ALEN),\n"
256 " /* MAC Source */\n"
257 " 0x00, 0x02, 0xb3, drnd(3),\n"
258 " /* IPv4 Protocol */\n"
259 " c16(ETH_P_IP),\n"
260 " /* IPv4 Version, IHL, TOS */\n"
261 " 0b01000101, 0,\n"
262 " /* IPv4 Total Len */\n"
263 " c16(59),\n"
264 " /* IPv4 Ident */\n"
265 " drnd(2),\n"
266 " /* IPv4 Flags, Frag Off */\n"
267 " 0b01000000, 0,\n"
268 " /* IPv4 TTL */\n"
269 " 64,\n"
270 " /* Proto TCP */\n"
271 " 0x06,\n"
272 " /* IPv4 Checksum (IP header from, to) */\n"
273 " csumip(14, 33),\n"
274 " /* Source IP */\n"
275 " drnd(4),\n"
276 " /* Dest IP */\n"
277 " drnd(4),\n"
278 " /* TCP Source Port */\n"
279 " drnd(2),\n"
280 " /* TCP Dest Port */\n"
281 " c16(80),\n"
282 " /* TCP Sequence Number */\n"
283 " drnd(4),\n"
284 " /* TCP Ackn. Number */\n"
285 " c32(0),\n"
286 " /* TCP Header length + TCP SYN/ECN Flag */\n"
287 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
288 " /* Window Size */\n"
289 " c16(16),\n"
290 " /* TCP Checksum (offset IP, offset TCP) */\n"
291 " csumtcp(14, 34),\n"
292 " /* TCP Options */\n"
293 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
294 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
295 " /* Data blob */\n"
296 " \"gotcha!\",\n"
297 "}";
298 puts(e);
299 die();
302 static void __noreturn version(void)
304 printf("trafgen %s, Git id: %s\n", VERSION_LONG, GITVERSION);
305 puts("multithreaded zero-copy network packet generator\n"
306 "http://www.netsniff-ng.org\n");
307 puts(copyright);
308 die();
311 static void apply_counter(int id)
313 size_t j, counter_max = packet_dyn[id].clen;
315 for (j = 0; j < counter_max; ++j) {
316 uint8_t val;
317 struct counter *counter = &packet_dyn[id].cnt[j];
319 val = counter->val - counter->min;
320 val = (val + counter->inc) % (counter->max - counter->min + 1);
322 counter->val = val + counter->min;
323 packets[id].payload[counter->off] = counter->val;
327 static void apply_randomizer(int id)
329 size_t j, rand_max = packet_dyn[id].rlen;
331 for (j = 0; j < rand_max; ++j) {
332 uint8_t val = (uint8_t) rand();
333 struct randomizer *randomizer = &packet_dyn[id].rnd[j];
335 packets[id].payload[randomizer->off] = val;
339 static void apply_csum16(int id)
341 size_t j, csum_max = packet_dyn[id].slen;
343 for (j = 0; j < csum_max; ++j) {
344 uint16_t sum = 0;
345 struct csum16 *csum = &packet_dyn[id].csum[j];
347 memset(&packets[id].payload[csum->off], 0, sizeof(sum));
348 if (unlikely((size_t) csum->to >= packets[id].len))
349 csum->to = packets[id].len - 1;
351 switch (csum->which) {
352 case CSUM_IP:
353 sum = calc_csum(packets[id].payload + csum->from,
354 csum->to - csum->from + 1);
355 break;
356 case CSUM_UDP:
357 sum = p4_csum((void *) packets[id].payload + csum->from,
358 packets[id].payload + csum->to,
359 (packets[id].len - csum->to),
360 IPPROTO_UDP);
361 break;
362 case CSUM_TCP:
363 sum = p4_csum((void *) packets[id].payload + csum->from,
364 packets[id].payload + csum->to,
365 (packets[id].len - csum->to),
366 IPPROTO_TCP);
367 break;
368 case CSUM_UDP6:
369 sum = p6_csum((void *) packets[id].payload + csum->from,
370 packets[id].payload + csum->to,
371 (packets[id].len - csum->to),
372 IPPROTO_UDP);
373 break;
374 case CSUM_TCP6:
375 sum = p6_csum((void *) packets[id].payload + csum->from,
376 packets[id].payload + csum->to,
377 (packets[id].len - csum->to),
378 IPPROTO_TCP);
379 break;
380 case CSUM_ICMP6:
381 sum = p6_csum((void *) packets[id].payload + csum->from,
382 packets[id].payload + csum->to,
383 (packets[id].len - csum->to),
384 IPPROTO_ICMPV6);
385 break;
386 default:
387 bug();
388 break;
391 memcpy(&packets[id].payload[csum->off], &sum, sizeof(sum));
395 static void preprocess_packets(void)
397 size_t i;
399 for (i = 0; i < plen; i++) {
400 struct packet_dyn *pktd = &packet_dyn[i];
402 if (packet_dyn_has_only_csums(pktd)) {
403 apply_csum16(i);
404 pktd->slen = 0;
405 xfree(pktd->csum);
410 static struct cpu_stats *setup_shared_var(unsigned int cpus)
412 int fd;
413 size_t len = cpus * sizeof(struct cpu_stats);
414 char *zbuff, file[256];
415 struct cpu_stats *buff;
417 slprintf(file, sizeof(file), ".tmp_mmap.XXXXXX");
418 fd = mkostemp_or_die(file, O_RDWR | O_CREAT | O_TRUNC);
419 zbuff = xzmalloc(len);
420 write_or_die(fd, zbuff, len);
421 xfree(zbuff);
423 buff = mmap(NULL, len, PROT_READ | PROT_WRITE,
424 MAP_SHARED, fd, 0);
425 if (buff == MAP_FAILED)
426 panic("Cannot setup shared variable!\n");
428 close(fd);
429 unlink(file);
431 memset(buff, 0, len);
432 return buff;
435 static void destroy_shared_var(void *buff, unsigned int cpus)
437 munmap(buff, cpus * sizeof(struct cpu_stats));
440 static void dump_trafgen_snippet(uint8_t *payload, size_t len)
442 size_t i;
444 printf("{");
445 for (i = 0; i < len; ++i) {
446 if (i % 15 == 0)
447 printf("\n ");
448 printf("0x%02x, ", payload[i]);
450 printf("\n}\n");
451 fflush(stdout);
454 static int xmit_smoke_setup(struct ctx *ctx)
456 int icmp_sock, ret, ttl = 64;
457 struct icmp_filter filter;
459 icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
460 if (icmp_sock < 0)
461 panic("Cannot get a ICMP socket: %s!\n", strerror(errno));
463 filter.data = ~(1 << ICMP_ECHOREPLY);
465 ret = setsockopt(icmp_sock, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
466 if (ret < 0)
467 panic("Cannot install filter!\n");
469 ret = setsockopt(icmp_sock, SOL_IP, IP_TTL, &ttl, sizeof(ttl));
470 if (ret < 0)
471 panic("Cannot set TTL!\n");
473 memset(&ctx->dest, 0, sizeof(ctx->dest));
474 ctx->dest.sin_family = AF_INET;
475 ctx->dest.sin_port = 0;
477 ret = inet_aton(ctx->rhost, &ctx->dest.sin_addr);
478 if (ret < 0)
479 panic("Cannot resolve address!\n");
481 return icmp_sock;
484 static int xmit_smoke_probe(int icmp_sock, struct ctx *ctx)
486 int ret;
487 unsigned int i, j;
488 short ident, cnt = 1, idstore[SMOKE_N_PROBES];
489 uint8_t outpack[512], *data;
490 struct icmphdr *icmp;
491 struct iphdr *ip;
492 size_t len = sizeof(*icmp) + 56;
493 struct sockaddr_in from;
494 socklen_t from_len;
495 struct pollfd fds = {
496 .fd = icmp_sock,
497 .events = POLLIN,
500 memset(idstore, 0, sizeof(idstore));
501 for (j = 0; j < SMOKE_N_PROBES; j++) {
502 while ((ident = htons((short) rand())) == 0)
503 sleep(0);
504 idstore[j] = ident;
506 memset(outpack, 0, sizeof(outpack));
507 icmp = (void *) outpack;
508 icmp->type = ICMP_ECHO;
509 icmp->un.echo.id = ident;
510 icmp->un.echo.sequence = htons(cnt++);
512 data = ((uint8_t *) outpack + sizeof(*icmp));
513 for (i = 0; i < 56; ++i)
514 data[i] = (uint8_t) rand();
516 icmp->checksum = csum((unsigned short *) outpack,
517 len / sizeof(unsigned short));
519 ret = sendto(icmp_sock, outpack, len, MSG_DONTWAIT,
520 (struct sockaddr *) &ctx->dest, sizeof(ctx->dest));
521 if (unlikely(ret != (int) len))
522 panic("Cannot send out probe: %s!\n", strerror(errno));
524 ret = poll(&fds, 1, 50);
525 if (ret < 0)
526 panic("Poll failed!\n");
528 if (fds.revents & POLLIN) {
529 ret = recvfrom(icmp_sock, outpack, sizeof(outpack), 0,
530 (struct sockaddr *) &from, &from_len);
531 if (unlikely(ret <= 0))
532 panic("Probe receive failed!\n");
533 if (unlikely(from_len != sizeof(ctx->dest)))
534 continue;
535 if (unlikely(memcmp(&from, &ctx->dest, sizeof(ctx->dest))))
536 continue;
537 if (unlikely((size_t) ret < sizeof(*ip) + sizeof(*icmp)))
538 continue;
539 ip = (void *) outpack;
540 if (unlikely(ip->ihl * 4 + sizeof(*icmp) > (size_t) ret))
541 continue;
542 icmp = (void *) outpack + ip->ihl * 4;
543 for (i = 0; i < array_size(idstore); ++i) {
544 if (unlikely(icmp->un.echo.id != idstore[i]))
545 continue;
546 return 0;
551 return -1;
554 static bool shaper_is_set(struct shaper *sh)
556 return sh->type != SHAPER_NONE;
559 static void shaper_init(struct shaper *sh)
561 if (sh->type == SHAPER_NONE || sh->type == SHAPER_DELAY)
562 return;
564 memset(&sh->delay, 0, sizeof(struct timespec));
565 bug_on(gettimeofday(&sh->start, NULL));
566 sh->sent = 0;
569 static void shaper_set_delay(struct shaper *sh, time_t sec, long int ns)
571 sh->type = SHAPER_DELAY;
572 sh->delay.tv_sec = sec;
573 sh->delay.tv_nsec = ns;
576 static void shaper_set_rate(struct shaper *sh, unsigned long long rate,
577 enum shaper_type type)
579 memset(sh, 0, sizeof(struct shaper));
580 sh->rate = rate;
581 sh->type = type;
584 static void shaper_set_tstamp(struct shaper *sh, struct timespec *ts)
586 TIMESPEC_TO_TIMEVAL(&sh->tstamp, ts);
589 static void shaper_delay(struct shaper *sh, struct packet *pkt)
591 if (sh->type == SHAPER_BYTES || sh->type == SHAPER_PKTS) {
592 unsigned long pkt_len = pkt->len;
594 sh->sent += sh->type == SHAPER_BYTES ? pkt_len : 1;
596 if (sh->sent >= sh->rate && sh->rate > 0) {
597 struct timeval delay_us;
598 struct timeval time_sent;
599 struct timeval time_1s = { .tv_sec = 1 };
601 bug_on(gettimeofday(&sh->end, NULL));
602 timersub(&sh->end, &sh->start, &time_sent);
604 if (timercmp(&time_1s, &time_sent, > )) {
605 timersub(&time_1s, &time_sent, &delay_us);
606 TIMEVAL_TO_TIMESPEC(&delay_us, &sh->delay);
609 } else if (sh->type == SHAPER_TSTAMP) {
610 struct timeval tstamp;
611 struct timeval pkt_diff;
612 struct timeval diff;
614 bug_on(gettimeofday(&sh->end, NULL));
615 TIMESPEC_TO_TIMEVAL(&tstamp, &pkt->tstamp);
616 timersub(&sh->end, &sh->start, &diff);
617 timersub(&tstamp, &sh->tstamp, &pkt_diff);
619 if (timercmp(&diff, &pkt_diff, <)) {
620 struct timeval delay;
622 timersub(&pkt_diff, &diff, &delay);
623 TIMEVAL_TO_TIMESPEC(&delay, &sh->delay);
626 memcpy(&sh->tstamp, &tstamp, sizeof(sh->tstamp));
629 if ((sh->delay.tv_sec | sh->delay.tv_nsec) > 0) {
630 nanosleep(&sh->delay, NULL);
632 shaper_init(sh);
636 static inline void packet_apply_dyn_elements(int idx)
638 if (packet_dyn_has_elems(&packet_dyn[idx])) {
639 apply_counter(idx);
640 apply_randomizer(idx);
641 apply_csum16(idx);
644 if (packet_dyn_has_fields(&packet_dyn[idx])) {
645 uint32_t i;
647 for (i = 0; i < packet_dyn[idx].flen; i++)
648 proto_field_dyn_apply(packet_dyn[idx].fields[i]);
650 proto_packet_update(idx);
654 static void xmit_slowpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
656 int ret, icmp_sock = -1;
657 unsigned long num = 1, i = 0;
658 struct timeval start, end, diff;
659 unsigned long long tx_bytes = 0, tx_packets = 0;
661 if (ctx->num > 0)
662 num = ctx->num;
663 if (ctx->num == 0 && orig_num > 0)
664 num = 0;
666 if (ctx->smoke_test)
667 icmp_sock = xmit_smoke_setup(ctx);
669 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
671 bug_on(gettimeofday(&start, NULL));
673 if (shaper_is_set(&ctx->sh))
674 shaper_init(&ctx->sh);
676 while (likely(sigint == 0 && num > 0 && plen > 0)) {
677 packet_apply_dyn_elements(i);
678 retry:
679 ret = dev_io_write(ctx->dev_out, &packets[i]);
680 if (unlikely(ret < 0)) {
681 if (errno == ENOBUFS) {
682 sched_yield();
683 goto retry;
685 if (ctx->smoke_test)
686 panic("Sendto error: %s!\n", strerror(errno));
689 tx_bytes += packets[i].len;
690 tx_packets++;
692 if (ctx->smoke_test) {
693 ret = xmit_smoke_probe(icmp_sock, ctx);
694 if (unlikely(ret < 0)) {
695 printf("%sSmoke test alert:%s\n", colorize_start(bold), colorize_end());
696 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
697 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
698 i, seed);
700 dump_trafgen_snippet(packets[i].payload, packets[i].len);
701 break;
705 if (!ctx->rand) {
706 i++;
707 if (i >= plen)
708 i = 0;
709 } else
710 i = rand() % plen;
712 if (ctx->num > 0)
713 num--;
715 if (shaper_is_set(&ctx->sh))
716 shaper_delay(&ctx->sh, &packets[i]);
719 bug_on(gettimeofday(&end, NULL));
720 timersub(&end, &start, &diff);
722 if (ctx->smoke_test)
723 close(icmp_sock);
725 stats[cpu].tx_packets = tx_packets;
726 stats[cpu].tx_bytes = tx_bytes;
727 stats[cpu].tv_sec = diff.tv_sec;
728 stats[cpu].tv_usec = diff.tv_usec;
730 stats[cpu].state |= CPU_STATS_STATE_RES;
733 static void xmit_fastpath_or_die(struct ctx *ctx, unsigned int cpu, unsigned long orig_num)
735 int ifindex = dev_io_ifindex_get(ctx->dev_out);
736 uint8_t *out = NULL;
737 unsigned int it = 0, retry = 100;
738 unsigned long num = 1, i = 0;
739 size_t size = ring_size(dev_io_name_get(ctx->dev_out), ctx->reserve_size);
740 struct ring tx_ring;
741 struct frame_map *hdr;
742 struct timeval start, end, diff;
743 unsigned long long tx_bytes = 0, tx_packets = 0;
744 int sock = dev_io_fd_get(ctx->dev_out);
746 set_sock_prio(sock, 512);
748 ring_tx_setup(&tx_ring, sock, size, ifindex, ctx->jumbo_support, ctx->verbose);
750 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
752 if (ctx->num > 0)
753 num = ctx->num;
754 if (ctx->num == 0 && orig_num > 0)
755 num = 0;
757 bug_on(gettimeofday(&start, NULL));
759 while (likely(sigint == 0 && num > 0 && plen > 0)) {
760 if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
761 int ret = pull_and_flush_tx_ring(sock);
762 if (unlikely(ret < 0)) {
763 /* We could hit EBADF if the socket has been closed before
764 * the timer was triggered.
766 if (errno != EBADF && errno != ENOBUFS)
767 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
770 continue;
773 hdr = tx_ring.frames[it].iov_base;
774 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
776 hdr->tp_h.tp_snaplen = packets[i].len;
777 hdr->tp_h.tp_len = packets[i].len;
779 packet_apply_dyn_elements(i);
781 memcpy(out, packets[i].payload, packets[i].len);
783 tx_bytes += packets[i].len;
784 tx_packets++;
786 if (!ctx->rand) {
787 i++;
788 if (i >= plen)
789 i = 0;
790 } else
791 i = rand() % plen;
793 kernel_may_pull_from_tx(&hdr->tp_h);
795 it++;
796 if (it >= tx_ring.layout.tp_frame_nr)
797 it = 0;
799 if (ctx->num > 0)
800 num--;
803 bug_on(gettimeofday(&end, NULL));
804 timersub(&end, &start, &diff);
806 while (pull_and_flush_tx_ring_wait(sock) < 0 && errno == ENOBUFS && retry-- > 0)
807 usleep(10000);
808 destroy_tx_ring(sock, &tx_ring);
810 stats[cpu].tx_packets = tx_packets;
811 stats[cpu].tx_bytes = tx_bytes;
812 stats[cpu].tv_sec = diff.tv_sec;
813 stats[cpu].tv_usec = diff.tv_usec;
815 stats[cpu].state |= CPU_STATS_STATE_RES;
818 static inline void __set_state(unsigned int cpu, sig_atomic_t s)
820 stats[cpu].state = s;
823 static inline sig_atomic_t __get_state(unsigned int cpu)
825 return stats[cpu].state;
828 static unsigned long __wait_and_sum_others(struct ctx *ctx, unsigned int cpu)
830 unsigned int i;
831 unsigned long total;
833 for (i = 0, total = plen; i < ctx->cpus; i++) {
834 if (i == cpu)
835 continue;
837 while ((__get_state(i) &
838 (CPU_STATS_STATE_CFG |
839 CPU_STATS_STATE_RES)) == 0 &&
840 sigint == 0)
841 sched_yield();
843 total += stats[i].cf_packets;
846 return total;
849 static void __correct_global_delta(struct ctx *ctx, unsigned int cpu, unsigned long orig)
851 unsigned int i;
852 unsigned long total;
853 int cpu_sel;
854 long long delta_correction = 0;
856 for (i = 0, total = ctx->num; i < ctx->cpus; i++) {
857 if (i == cpu)
858 continue;
860 while ((__get_state(i) &
861 (CPU_STATS_STATE_CHK |
862 CPU_STATS_STATE_RES)) == 0 &&
863 sigint == 0)
864 sched_yield();
866 total += stats[i].cd_packets;
869 if (total > orig)
870 delta_correction = -1 * ((long long) total - orig);
871 if (total < orig)
872 delta_correction = +1 * ((long long) orig - total);
874 for (cpu_sel = -1, i = 0; i < ctx->cpus; i++) {
875 if (stats[i].cd_packets > 0) {
876 if ((long long) stats[i].cd_packets +
877 delta_correction >= 0) {
878 cpu_sel = i;
879 break;
884 if ((int) cpu == cpu_sel)
885 ctx->num += delta_correction;
888 static void __set_state_cf(unsigned int cpu, unsigned long p, unsigned long b,
889 sig_atomic_t s)
891 stats[cpu].cf_packets = p;
892 stats[cpu].cf_bytes = b;
893 stats[cpu].state = s;
896 static void __set_state_cd(unsigned int cpu, unsigned long p, sig_atomic_t s)
898 stats[cpu].cd_packets = p;
899 stats[cpu].state = s;
902 static void xmit_packet_precheck(struct ctx *ctx, unsigned int cpu)
904 unsigned long plen_total, orig = ctx->num;
905 size_t total_len = 0;
906 unsigned int i;
908 bug_on(plen != dlen);
910 for (i = 0; i < plen; ++i)
911 total_len += packets[i].len;
913 __set_state_cf(cpu, plen, total_len, CPU_STATS_STATE_CFG);
914 plen_total = __wait_and_sum_others(ctx, cpu);
916 if (orig > 0) {
917 ctx->num = (unsigned long) round((1.0 * plen / plen_total) * orig);
919 __set_state_cd(cpu, ctx->num, CPU_STATS_STATE_CHK |
920 CPU_STATS_STATE_CFG);
921 __correct_global_delta(ctx, cpu, orig);
924 if (plen == 0) {
925 __set_state(cpu, CPU_STATS_STATE_RES);
926 return;
930 static void pcap_load_packets(struct dev_io *dev)
932 while (dev_io_read(dev))
933 /* nothing to do */;
936 static void main_loop(struct ctx *ctx, char *confname, bool slow,
937 unsigned int cpu, bool invoke_cpp, char **cpp_argv,
938 unsigned long orig_num)
940 if (ctx->dev_in && dev_io_is_pcap(ctx->dev_in)) {
941 pcap_load_packets(ctx->dev_in);
942 shaper_set_tstamp(&ctx->sh, &packets[0].tstamp);
943 ctx->num = plen;
944 } else {
945 if (ctx->packet_str)
946 compile_packets_str(ctx->packet_str, ctx->verbose, cpu);
947 else
948 compile_packets(confname, ctx->verbose, cpu, invoke_cpp, cpp_argv);
950 preprocess_packets();
953 xmit_packet_precheck(ctx, cpu);
955 if (cpu == 0) {
956 unsigned int i;
957 size_t total_len = 0, total_pkts = 0;
959 for (i = 0; i < ctx->cpus; ++i) {
960 total_len += stats[i].cf_bytes;
961 total_pkts += stats[i].cf_packets;
964 printf("%6zu packets to schedule\n", total_pkts);
965 printf("%6zu bytes in total\n", total_len);
966 printf("Running! Hang up with ^C!\n\n");
967 fflush(stdout);
970 dev_io_open(ctx->dev_out);
971 if (dev_io_is_netdev(ctx->dev_out) && ctx->qdisc_path == false)
972 set_sock_qdisc_bypass(dev_io_fd_get(ctx->dev_out), ctx->verbose);
974 if (slow)
975 xmit_slowpath_or_die(ctx, cpu, orig_num);
976 else
977 xmit_fastpath_or_die(ctx, cpu, orig_num);
979 dev_io_close(ctx->dev_out);
980 if (ctx->dev_in)
981 dev_io_close(ctx->dev_in);
983 cleanup_packets();
986 static unsigned int generate_srand_seed(void)
988 int fd;
989 unsigned int _seed;
991 fd = open("/dev/urandom", O_RDONLY);
992 if (fd < 0)
993 return time(NULL);
995 read_or_die(fd, &_seed, sizeof(_seed));
997 close(fd);
998 return _seed;
1001 static void on_panic_del_rfmon(void *arg)
1003 dev_io_close(arg);
1006 int main(int argc, char **argv)
1008 bool slow = false, invoke_cpp = false, reseed = true, cpustats = true;
1009 bool prio_high = false, set_irq_aff = true, set_sock_mem = true;
1010 int c, vals[4] = {0}, irq;
1011 uint64_t gap = 0;
1012 unsigned int i;
1013 char *confname = NULL, *ptr;
1014 unsigned long cpus_tmp, orig_num = 0;
1015 unsigned long long tx_packets, tx_bytes;
1016 struct ctx ctx;
1017 int min_opts = 5;
1018 char **cpp_argv = NULL;
1019 size_t cpp_argc = 0;
1020 unsigned long long rate;
1021 enum shaper_type shape_type;
1022 struct timespec delay;
1024 memset(&ctx, 0, sizeof(ctx));
1025 ctx.cpus = get_number_cpus_online();
1026 ctx.uid = getuid();
1027 ctx.gid = getgid();
1028 ctx.qdisc_path = false;
1030 /* Keep an initial small default size to reduce cache-misses. */
1031 ctx.reserve_size = 512 * (1 << 10);
1033 while ((c = getopt_long(argc, argv, short_options, long_options,
1034 NULL)) != EOF) {
1035 switch (c) {
1036 case 'h':
1037 help();
1038 break;
1039 case 'v':
1040 version();
1041 break;
1042 case 'C':
1043 cpustats = false;
1044 break;
1045 case 'e':
1046 example();
1047 break;
1048 case 'p':
1049 invoke_cpp = true;
1050 break;
1051 case 'D':
1052 cpp_argv = argv_insert(cpp_argv, &cpp_argc, "-D");
1053 cpp_argv = argv_insert(cpp_argv, &cpp_argc, optarg);
1054 break;
1055 case 'V':
1056 ctx.verbose = true;
1057 break;
1058 case 'P':
1059 cpus_tmp = strtoul(optarg, NULL, 0);
1060 if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
1061 ctx.cpus = cpus_tmp;
1062 break;
1063 case 'd':
1064 case 'o':
1065 ctx.device = xstrdup(optarg);
1066 break;
1067 case 'H':
1068 prio_high = true;
1069 break;
1070 case 'A':
1071 set_sock_mem = false;
1072 break;
1073 case 'Q':
1074 set_irq_aff = false;
1075 break;
1076 case 'q':
1077 ctx.qdisc_path = true;
1078 break;
1079 case 'r':
1080 ctx.rand = true;
1081 break;
1082 case 's':
1083 slow = true;
1084 ctx.cpus = 1;
1085 ctx.smoke_test = true;
1086 ctx.rhost = xstrdup(optarg);
1087 break;
1088 case 'R':
1089 ctx.rfraw = true;
1090 break;
1091 case 'J':
1092 ctx.jumbo_support = true;
1093 break;
1094 case 'c':
1095 case 'i':
1096 confname = xstrdup(optarg);
1097 if (c == 'i' && strstr(confname, ".pcap")) {
1098 ctx.sh.type = SHAPER_TSTAMP;
1099 ctx.pcap_in = confname;
1100 } else if (!strncmp("-", confname, strlen("-")))
1101 ctx.cpus = 1;
1102 break;
1103 case 'u':
1104 ctx.uid = strtoul(optarg, NULL, 0);
1105 ctx.enforce = true;
1106 break;
1107 case 'g':
1108 ctx.gid = strtoul(optarg, NULL, 0);
1109 ctx.enforce = true;
1110 break;
1111 case 'k':
1112 printf("Option -k/--kernel-pull is no longer used and "
1113 "will be removed in a future release!\n");
1114 break;
1115 case 'E':
1116 seed = strtoul(optarg, NULL, 0);
1117 reseed = false;
1118 break;
1119 case 'n':
1120 orig_num = strtoul(optarg, NULL, 0);
1121 ctx.num = orig_num;
1122 break;
1123 case 't':
1124 gap = strtoul(optarg, &ptr, 0);
1125 if (!gap && optarg == ptr)
1126 panic("Invalid gap param\n");
1128 if (!strncmp(ptr, "ns", strlen("ns"))) {
1129 delay.tv_sec = gap / 1000000000;
1130 delay.tv_nsec = gap % 1000000000;
1131 } else if (*ptr == '\0' || !strncmp(ptr, "us", strlen("us"))) {
1132 /* Default to microseconds for backwards
1133 * compatibility if no postfix is given.
1135 delay.tv_sec = gap / 1000000;
1136 delay.tv_nsec = (gap % 1000000) * 1000;
1137 } else if (!strncmp(ptr, "ms", strlen("ms"))) {
1138 delay.tv_sec = gap / 1000;
1139 delay.tv_nsec = (gap % 1000) * 1000000;
1140 } else if (!strncmp(ptr, "s", strlen("s"))) {
1141 delay.tv_sec = gap;
1142 delay.tv_nsec = 0;
1143 } else {
1144 panic("Syntax error in time param!\n");
1147 shaper_set_delay(&ctx.sh, delay.tv_sec, delay.tv_nsec);
1148 break;
1149 case 'b':
1150 rate = strtoul(optarg, &ptr, 0);
1151 if (!rate && optarg == ptr)
1152 panic("Invalid rate param\n");
1154 if (strncmp(ptr, "pps", strlen("pps")) == 0) {
1155 shape_type = SHAPER_PKTS;
1156 } else if (strncmp(ptr, "kpps", strlen("kpps")) == 0) {
1157 shape_type = SHAPER_PKTS;
1158 rate *= 1000;
1159 } else if (strncmp(ptr, "Mpps", strlen("Mpps")) == 0) {
1160 shape_type = SHAPER_PKTS;
1161 rate *= 1000 * 1000;
1162 } else if (strncmp(ptr, "B", strlen("B")) == 0) {
1163 shape_type = SHAPER_BYTES;
1164 } else if (strncmp(ptr, "kB", strlen("kB")) == 0) {
1165 shape_type = SHAPER_BYTES;
1166 rate *= 1000;
1167 } else if (strncmp(ptr, "MB", strlen("MB")) == 0) {
1168 shape_type = SHAPER_BYTES;
1169 rate *= 1000 * 1000;
1170 } else if (strncmp(ptr, "GB", strlen("GB")) == 0) {
1171 shape_type = SHAPER_BYTES;
1172 rate *= 1000 * 1000 * 1000;
1173 } else if (strncmp(ptr, "kbit", strlen("kbit")) == 0) {
1174 shape_type = SHAPER_BYTES;
1175 rate *= 1000 / 8;
1176 } else if (strncmp(ptr, "Mbit", strlen("Mbit")) == 0) {
1177 shape_type = SHAPER_BYTES;
1178 rate *= 1000 * 1000 / 8;
1179 } else if (strncmp(ptr, "Gbit", strlen("Gbit")) == 0) {
1180 shape_type = SHAPER_BYTES;
1181 rate *= 1000 * 1000 * 1000 / 8;
1182 } else if (strncmp(ptr, "KiB", strlen("KiB")) == 0) {
1183 shape_type = SHAPER_BYTES;
1184 rate *= 1 << 10;
1185 } else if (strncmp(ptr, "MiB", strlen("MiB")) == 0) {
1186 shape_type = SHAPER_BYTES;
1187 rate *= 1 << 20;
1188 } else if (strncmp(ptr, "GiB", strlen("GiB")) == 0) {
1189 shape_type = SHAPER_BYTES;
1190 rate *= 1 << 30;
1191 } else if (!rate) {
1192 shape_type = SHAPER_NONE;
1193 } else {
1194 panic("Invalid unit type for rate\n");
1197 shaper_set_rate(&ctx.sh, rate, shape_type);
1198 break;
1199 case 'S':
1200 ctx.reserve_size = strtoul(optarg, &ptr, 0);
1201 if (ctx.reserve_size == 0 && ptr == optarg)
1202 panic("Invalid ring size param\n");
1204 if (!strncmp(ptr, "KiB", strlen("KiB")))
1205 ctx.reserve_size *= 1 << 10;
1206 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1207 ctx.reserve_size = 1 << 20;
1208 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1209 ctx.reserve_size *= 1 << 30;
1210 else
1211 panic("Invalid ring size unit type\n");
1213 break;
1214 case '?':
1215 switch (optopt) {
1216 case 'd':
1217 case 'c':
1218 case 'n':
1219 case 'S':
1220 case 's':
1221 case 'P':
1222 case 'o':
1223 case 'E':
1224 case 'i':
1225 case 'k':
1226 case 'u':
1227 case 'g':
1228 case 't':
1229 panic("Option -%c requires an argument!\n",
1230 optopt);
1231 default:
1232 if (isprint(optopt))
1233 printf("Unknown option character `0x%X\'!\n", optopt);
1234 die();
1236 default:
1237 break;
1241 if (argc >= optind) {
1242 min_opts = 4;
1243 ctx.packet_str = argv2str(optind, argc, argv);
1246 if (argc < min_opts)
1247 help();
1248 if (ctx.device == NULL)
1249 panic("No networking device given!\n");
1250 if (confname == NULL && !ctx.packet_str)
1251 panic("No configuration file or packet string given!\n");
1253 register_signal(SIGINT, signal_handler);
1254 register_signal(SIGQUIT, signal_handler);
1255 register_signal(SIGTERM, signal_handler);
1256 register_signal(SIGHUP, signal_handler);
1258 if (prio_high) {
1259 set_proc_prio(-20);
1260 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1263 if (set_sock_mem)
1264 set_system_socket_memory(vals, array_size(vals));
1265 xlockme();
1267 if (ctx.pcap_in) {
1268 ctx.dev_in = dev_io_create(ctx.pcap_in, DEV_IO_IN);
1269 if (!ctx.dev_in)
1270 panic("Failed to open input device\n");
1271 dev_io_open(ctx.dev_in);
1274 ctx.dev_out = dev_io_create(ctx.device, DEV_IO_OUT);
1275 if (!ctx.dev_out)
1276 panic("Failed to open output device\n");
1278 if (ctx.rfraw) {
1279 if (dev_io_link_type_set(ctx.dev_out, LINKTYPE_IEEE802_11_RADIOTAP))
1280 panic("Failed to setup rfraw device\n");
1282 panic_handler_add(on_panic_del_rfmon, ctx.dev_out);
1285 protos_init(ctx.dev_out);
1287 if (shaper_is_set(&ctx.sh) || (ctx.dev_in && !dev_io_is_netdev(ctx.dev_in))
1288 || !dev_io_is_netdev(ctx.dev_out)) {
1290 prctl(PR_SET_TIMERSLACK, 1UL);
1291 /* Fall back to single core to not mess up correct timing.
1292 * We are slow anyway!
1294 ctx.cpus = 1;
1295 slow = true;
1299 * If number of packets is smaller than number of CPUs use only as
1300 * many CPUs as there are packets. Otherwise we end up sending more
1301 * packets than intended or none at all.
1303 if (ctx.num)
1304 ctx.cpus = min_t(unsigned int, ctx.num, ctx.cpus);
1306 if (set_irq_aff && dev_io_is_netdev(ctx.dev_out)) {
1307 irq = device_irq_number(ctx.device);
1308 device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);
1311 stats = setup_shared_var(ctx.cpus);
1313 for (i = 0; i < ctx.cpus; i++) {
1314 pid_t pid = fork();
1316 switch (pid) {
1317 case 0:
1318 if (reseed)
1319 seed = generate_srand_seed();
1320 srand(seed);
1322 cpu_affinity(i);
1323 main_loop(&ctx, confname, slow, i, invoke_cpp,
1324 cpp_argv, orig_num);
1326 goto thread_out;
1327 case -1:
1328 panic("Cannot fork processes!\n");
1332 for (i = 0; i < ctx.cpus; i++) {
1333 int status;
1335 wait(&status);
1336 if (WEXITSTATUS(status) == EXIT_FAILURE)
1337 die();
1340 if (set_sock_mem)
1341 reset_system_socket_memory(vals, array_size(vals));
1343 for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
1344 while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
1345 sched_yield();
1347 tx_packets += stats[i].tx_packets;
1348 tx_bytes += stats[i].tx_bytes;
1351 fflush(stdout);
1352 printf("\n");
1353 printf("\r%12llu packets outgoing\n", tx_packets);
1354 printf("\r%12llu bytes outgoing\n", tx_bytes);
1355 for (i = 0; cpustats && i < ctx.cpus; i++) {
1356 printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
1357 stats[i].tv_sec, stats[i].tv_usec, i,
1358 stats[i].tx_packets);
1361 thread_out:
1362 xunlockme();
1363 destroy_shared_var(stats, ctx.cpus);
1364 if (dev_io_is_netdev(ctx.dev_out) && set_irq_aff)
1365 device_restore_irq_affinity_list();
1367 argv_free(cpp_argv);
1368 free(ctx.device);
1369 free(ctx.rhost);
1370 free(confname);
1371 free(ctx.packet_str);
1373 return 0;