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.
16 #include <sys/socket.h>
17 #include <sys/types.h>
18 #include <sys/fsuid.h>
19 #include <sys/prctl.h>
23 #include <net/ethernet.h>
24 #include <netinet/in.h>
25 #include <netinet/ip.h>
26 #include <linux/icmp.h>
28 #include <arpa/inet.h>
52 #include "trafgen_conf.h"
57 #include "trafgen_proto.h"
59 #include "trafgen_dev.h"
70 enum shaper_type type
;
71 unsigned long long sent
;
72 unsigned long long rate
;
73 struct timeval tstamp
;
74 struct timespec delay
;
80 bool rand
, rfraw
, jumbo_support
, verbose
, smoke_test
, enforce
, qdisc_path
;
82 struct dev_io
*dev_out
;
83 struct dev_io
*dev_in
;
88 struct sockaddr_in dest
;
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
;
102 static sig_atomic_t sigint
= 0;
104 struct packet
*packets
= NULL
;
107 struct packet_dyn
*packet_dyn
= NULL
;
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'},
143 static const char *copyright
= "Please report bugs to <netsniff-ng@googlegroups.com>\n"
144 "Copyright (C) 2011-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,\n"
145 "Swiss federal institute of technology (ETH Zurich)\n"
146 "License: GNU GPL version 2.0\n"
147 "This is free software: you are free to change and redistribute it.\n"
148 "There is NO WARRANTY, to the extent permitted by law.";
150 static struct cpu_stats
*stats
;
151 static unsigned int seed
;
153 #define CPU_STATS_STATE_CFG 1
154 #define CPU_STATS_STATE_CHK 2
155 #define CPU_STATS_STATE_RES 4
158 # define ICMP_FILTER 1
165 #define SMOKE_N_PROBES 100
167 #define PKT_MIN_LEN 14
169 static void signal_handler(int number
)
182 static void __noreturn
help(void)
184 printf("trafgen %s, multithreaded zero-copy network packet generator\n", VERSION_STRING
);
185 puts("http://www.netsniff-ng.org\n\n"
186 "Usage: trafgen [options] [packet]\n"
188 " -i|-c|--in|--conf <cfg/-> Packet configuration file/stdin\n"
189 " -o|-d|--out|--dev <netdev|.cfg|.pcap> Networking device or configuration file i.e., eth0\n"
190 " -p|--cpp Run packet config through C preprocessor\n"
191 " -D|--define Add macro/define for C preprocessor\n"
192 " -J|--jumbo-support Support 64KB super jumbo frames (def: 2048B)\n"
193 " -R|--rfraw Inject raw 802.11 frames\n"
194 " -s|--smoke-test <ipv4> Probe if machine survived fuzz-tested packet\n"
195 " -n|--num <uint> Number of packets until exit (def: 0)\n"
196 " -r|--rand Randomize packet selection (def: round robin)\n"
197 " -P|--cpus <uint> Specify number of forks(<= CPUs) (def: #CPUs)\n"
198 " -t|--gap <time> Set approx. interpacket gap (s/ms/us/ns, def: us)\n"
199 " -b|--rate <rate> Send traffic at specified rate (pps/B/kB/MB/GB/kbit/Mbit/Gbit/KiB/MiB/GiB)\n"
200 " -S|--ring-size <size> Manually set mmap size (KiB/MiB/GiB)\n"
201 " -E|--seed <uint> Manually set srand(3) seed\n"
202 " -u|--user <userid> Drop privileges and change to userid\n"
203 " -g|--group <groupid> Drop privileges and change to groupid\n"
204 " -H|--prio-high Make this high priority process\n"
205 " -A|--no-sock-mem Don't tune core socket memory\n"
206 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
207 " -q|--qdisc-path Enable qdisc kernel path (default off since 3.14)\n"
208 " -V|--verbose Be more verbose\n"
209 " -C|--no-cpu-stats Do not print CPU time statistics on exit\n"
210 " -v|--version Show version and exit\n"
211 " -e|--example Show built-in packet config example\n"
212 " -h|--help Guess what?!\n\n"
214 " trafgen --dev eth0 --conf trafgen.cfg\n"
215 " trafgen -e | trafgen -i - -o eth0 --cpp -n 1\n"
216 " trafgen --dev eth0 --conf fuzzing.cfg --smoke-test 10.0.0.1\n"
217 " trafgen --dev wlan0 --rfraw --conf beacon-test.txf -V --cpus 2\n"
218 " trafgen --dev eth0 --conf frag_dos.cfg --rand --gap 1000us\n"
219 " trafgen --dev eth0 --conf icmp.cfg --rand --num 1400000 -k1000\n"
220 " trafgen --dev eth0 --conf tcp_syn.cfg -u `id -u bob` -g `id -g bob`\n"
221 " trafgen --dev eth0 '{ fill(0xff, 6), 0x00, 0x02, 0xb3, rnd(3), c16(0x0800), fill(0xca, 64) }'\n\n"
222 "Arbitrary packet config examples (e.g. trafgen -e > trafgen.cfg):\n"
223 " Run packet on all CPUs: { fill(0xff, 64) csum16(0, 64) }\n"
224 " Run packet only on CPU1: cpu(1): { rnd(64), 0b11001100, 0xaa }\n"
225 " Run packet only on CPU1-2: cpu(1-2): { drnd(64),'a',csum16(1, 8),'b',42 }\n\n"
226 "Generate config files from existing pcap using netsniff-ng:\n"
227 " netsniff-ng --in dump.pcap --out dump.cfg\n\n"
229 " Smoke/fuzz test example: machine A, 10.0.0.2 (trafgen) is directly\n"
230 " connected to machine B (test kernel), 10.0.0.1. If ICMP reply fails\n"
231 " we assume the kernel crashed, thus we print the packet and quit.\n"
232 " In case you find a ping-of-death, please mention trafgen in your\n"
233 " commit message of the fix!\n\n"
234 " For introducing bit errors, delays with random variation and more,\n"
235 " make use of tc(8) with its different disciplines, i.e. netem.\n\n"
236 " For generating different package distributions, you can use scripting\n"
237 " to generate a trafgen config file with packet ratios as:\n\n"
238 " IMIX 64:7, 570:4, 1518:1\n"
239 " Tolly 64:55, 78:5, 576:17, 1518:23\n"
240 " Cisco 64:7, 594:4, 1518:1\n"
241 " RPR Trimodal 64:60, 512:20, 1518:20\n"
242 " RPR Quadrimodal 64:50, 512:15, 1518:15, 9218:20\n");
247 static void __noreturn
example(void)
250 "/* Note: dynamic elements make trafgen slower! */\n"
251 "#include <stddef.h>\n\n"
253 " /* MAC Destination */\n"
254 " fill(0xff, ETH_ALEN),\n"
255 " /* MAC Source */\n"
256 " 0x00, 0x02, 0xb3, drnd(3),\n"
257 " /* IPv4 Protocol */\n"
259 " /* IPv4 Version, IHL, TOS */\n"
261 " /* IPv4 Total Len */\n"
263 " /* IPv4 Ident */\n"
265 " /* IPv4 Flags, Frag Off */\n"
271 " /* IPv4 Checksum (IP header from, to) */\n"
277 " /* TCP Source Port */\n"
279 " /* TCP Dest Port */\n"
281 " /* TCP Sequence Number */\n"
283 " /* TCP Ackn. Number */\n"
285 " /* TCP Header length + TCP SYN/ECN Flag */\n"
286 " c16((8 << 12) | TCP_FLAG_SYN | TCP_FLAG_ECE)\n"
287 " /* Window Size */\n"
289 " /* TCP Checksum (offset IP, offset TCP) */\n"
290 " csumtcp(14, 34),\n"
291 " /* TCP Options */\n"
292 " 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0x06,\n"
293 " 0x91, 0x68, 0x7d, 0x06, 0x91, 0x68, 0x6f,\n"
301 static void __noreturn
version(void)
303 printf("trafgen %s, Git id: %s\n", VERSION_LONG
, GITVERSION
);
304 puts("multithreaded zero-copy network packet generator\n"
305 "http://www.netsniff-ng.org\n");
310 static void apply_counter(int id
)
312 size_t j
, counter_max
= packet_dyn
[id
].clen
;
314 for (j
= 0; j
< counter_max
; ++j
) {
316 struct counter
*counter
= &packet_dyn
[id
].cnt
[j
];
318 val
= counter
->val
- counter
->min
;
319 val
= (val
+ counter
->inc
) % (counter
->max
- counter
->min
+ 1);
321 counter
->val
= val
+ counter
->min
;
322 packets
[id
].payload
[counter
->off
] = counter
->val
;
326 static void apply_randomizer(int id
)
328 size_t j
, rand_max
= packet_dyn
[id
].rlen
;
330 for (j
= 0; j
< rand_max
; ++j
) {
331 uint8_t val
= (uint8_t) rand();
332 struct randomizer
*randomizer
= &packet_dyn
[id
].rnd
[j
];
334 packets
[id
].payload
[randomizer
->off
] = val
;
338 static void apply_csum16(int id
)
340 size_t j
, csum_max
= packet_dyn
[id
].slen
;
342 for (j
= 0; j
< csum_max
; ++j
) {
344 struct csum16
*csum
= &packet_dyn
[id
].csum
[j
];
346 memset(&packets
[id
].payload
[csum
->off
], 0, sizeof(sum
));
347 if (unlikely((size_t) csum
->to
>= packets
[id
].len
))
348 csum
->to
= packets
[id
].len
- 1;
350 switch (csum
->which
) {
352 sum
= calc_csum(packets
[id
].payload
+ csum
->from
,
353 csum
->to
- csum
->from
+ 1);
356 sum
= p4_csum((void *) packets
[id
].payload
+ csum
->from
,
357 packets
[id
].payload
+ csum
->to
,
358 (packets
[id
].len
- csum
->to
),
362 sum
= p4_csum((void *) packets
[id
].payload
+ csum
->from
,
363 packets
[id
].payload
+ csum
->to
,
364 (packets
[id
].len
- csum
->to
),
368 sum
= p6_csum((void *) packets
[id
].payload
+ csum
->from
,
369 packets
[id
].payload
+ csum
->to
,
370 (packets
[id
].len
- csum
->to
),
374 sum
= p6_csum((void *) packets
[id
].payload
+ csum
->from
,
375 packets
[id
].payload
+ csum
->to
,
376 (packets
[id
].len
- csum
->to
),
380 sum
= p6_csum((void *) packets
[id
].payload
+ csum
->from
,
381 packets
[id
].payload
+ csum
->to
,
382 (packets
[id
].len
- csum
->to
),
390 memcpy(&packets
[id
].payload
[csum
->off
], &sum
, sizeof(sum
));
394 static void preprocess_packets(void)
398 for (i
= 0; i
< plen
; i
++) {
399 struct packet_dyn
*pktd
= &packet_dyn
[i
];
401 if (packet_dyn_has_only_csums(pktd
)) {
409 static struct cpu_stats
*setup_shared_var(unsigned int cpus
)
412 size_t len
= cpus
* sizeof(struct cpu_stats
);
413 char *zbuff
, file
[256];
414 struct cpu_stats
*buff
;
416 slprintf(file
, sizeof(file
), ".tmp_mmap.XXXXXX");
417 fd
= mkostemp_or_die(file
, O_RDWR
| O_CREAT
| O_TRUNC
);
418 zbuff
= xzmalloc(len
);
419 write_or_die(fd
, zbuff
, len
);
422 buff
= mmap(NULL
, len
, PROT_READ
| PROT_WRITE
,
424 if (buff
== MAP_FAILED
)
425 panic("Cannot setup shared variable!\n");
430 memset(buff
, 0, len
);
434 static void destroy_shared_var(void *buff
, unsigned int cpus
)
436 munmap(buff
, cpus
* sizeof(struct cpu_stats
));
439 static void dump_trafgen_snippet(uint8_t *payload
, size_t len
)
444 for (i
= 0; i
< len
; ++i
) {
447 printf("0x%02x, ", payload
[i
]);
453 static int xmit_smoke_setup(struct ctx
*ctx
)
455 int icmp_sock
, ret
, ttl
= 64;
456 struct icmp_filter filter
;
458 icmp_sock
= socket(AF_INET
, SOCK_RAW
, IPPROTO_ICMP
);
460 panic("Cannot get a ICMP socket: %s!\n", strerror(errno
));
462 filter
.data
= ~(1 << ICMP_ECHOREPLY
);
464 ret
= setsockopt(icmp_sock
, SOL_RAW
, ICMP_FILTER
, &filter
, sizeof(filter
));
466 panic("Cannot install filter!\n");
468 ret
= setsockopt(icmp_sock
, SOL_IP
, IP_TTL
, &ttl
, sizeof(ttl
));
470 panic("Cannot set TTL!\n");
472 memset(&ctx
->dest
, 0, sizeof(ctx
->dest
));
473 ctx
->dest
.sin_family
= AF_INET
;
474 ctx
->dest
.sin_port
= 0;
476 ret
= inet_aton(ctx
->rhost
, &ctx
->dest
.sin_addr
);
478 panic("Cannot resolve address!\n");
483 static int xmit_smoke_probe(int icmp_sock
, struct ctx
*ctx
)
487 short ident
, cnt
= 1, idstore
[SMOKE_N_PROBES
];
488 uint8_t outpack
[512], *data
;
489 struct icmphdr
*icmp
;
491 size_t len
= sizeof(*icmp
) + 56;
492 struct sockaddr_in from
;
494 struct pollfd fds
= {
499 memset(idstore
, 0, sizeof(idstore
));
500 for (j
= 0; j
< SMOKE_N_PROBES
; j
++) {
501 while ((ident
= htons((short) rand())) == 0)
505 memset(outpack
, 0, sizeof(outpack
));
506 icmp
= (void *) outpack
;
507 icmp
->type
= ICMP_ECHO
;
508 icmp
->un
.echo
.id
= ident
;
509 icmp
->un
.echo
.sequence
= htons(cnt
++);
511 data
= ((uint8_t *) outpack
+ sizeof(*icmp
));
512 for (i
= 0; i
< 56; ++i
)
513 data
[i
] = (uint8_t) rand();
515 icmp
->checksum
= csum((unsigned short *) outpack
,
516 len
/ sizeof(unsigned short));
518 ret
= sendto(icmp_sock
, outpack
, len
, MSG_DONTWAIT
,
519 (struct sockaddr
*) &ctx
->dest
, sizeof(ctx
->dest
));
520 if (unlikely(ret
!= (int) len
))
521 panic("Cannot send out probe: %s!\n", strerror(errno
));
523 ret
= poll(&fds
, 1, 50);
525 panic("Poll failed!\n");
527 if (fds
.revents
& POLLIN
) {
528 ret
= recvfrom(icmp_sock
, outpack
, sizeof(outpack
), 0,
529 (struct sockaddr
*) &from
, &from_len
);
530 if (unlikely(ret
<= 0))
531 panic("Probe receive failed!\n");
532 if (unlikely(from_len
!= sizeof(ctx
->dest
)))
534 if (unlikely(memcmp(&from
, &ctx
->dest
, sizeof(ctx
->dest
))))
536 if (unlikely((size_t) ret
< sizeof(*ip
) + sizeof(*icmp
)))
538 ip
= (void *) outpack
;
539 if (unlikely(ip
->ihl
* 4 + sizeof(*icmp
) > (size_t) ret
))
541 icmp
= (void *) outpack
+ ip
->ihl
* 4;
542 for (i
= 0; i
< array_size(idstore
); ++i
) {
543 if (unlikely(icmp
->un
.echo
.id
!= idstore
[i
]))
553 static bool shaper_is_set(struct shaper
*sh
)
555 return sh
->type
!= SHAPER_NONE
;
558 static void shaper_init(struct shaper
*sh
)
560 if (sh
->type
== SHAPER_NONE
|| sh
->type
== SHAPER_DELAY
)
563 memset(&sh
->delay
, 0, sizeof(struct timespec
));
564 bug_on(gettimeofday(&sh
->start
, NULL
));
568 static void shaper_set_delay(struct shaper
*sh
, time_t sec
, long int ns
)
571 sh
->type
= SHAPER_NONE
;
575 sh
->type
= SHAPER_DELAY
;
576 sh
->delay
.tv_sec
= sec
;
577 sh
->delay
.tv_nsec
= ns
;
580 static void shaper_set_rate(struct shaper
*sh
, unsigned long long rate
,
581 enum shaper_type type
)
583 memset(sh
, 0, sizeof(struct shaper
));
588 static void shaper_set_tstamp(struct shaper
*sh
, struct timespec
*ts
)
590 TIMESPEC_TO_TIMEVAL(&sh
->tstamp
, ts
);
593 static void shaper_delay(struct shaper
*sh
, struct packet
*pkt
)
595 if (sh
->type
== SHAPER_BYTES
|| sh
->type
== SHAPER_PKTS
) {
596 unsigned long pkt_len
= pkt
->len
;
598 sh
->sent
+= sh
->type
== SHAPER_BYTES
? pkt_len
: 1;
600 if (sh
->sent
>= sh
->rate
&& sh
->rate
> 0) {
601 struct timeval delay_us
;
602 struct timeval time_sent
;
603 struct timeval time_1s
= { .tv_sec
= 1 };
605 bug_on(gettimeofday(&sh
->end
, NULL
));
606 timersub(&sh
->end
, &sh
->start
, &time_sent
);
608 if (timercmp(&time_1s
, &time_sent
, > )) {
609 timersub(&time_1s
, &time_sent
, &delay_us
);
610 TIMEVAL_TO_TIMESPEC(&delay_us
, &sh
->delay
);
613 } else if (sh
->type
== SHAPER_TSTAMP
) {
614 struct timeval tstamp
;
615 struct timeval pkt_diff
;
618 bug_on(gettimeofday(&sh
->end
, NULL
));
619 TIMESPEC_TO_TIMEVAL(&tstamp
, &pkt
->tstamp
);
620 timersub(&sh
->end
, &sh
->start
, &diff
);
621 timersub(&tstamp
, &sh
->tstamp
, &pkt_diff
);
623 if (timercmp(&diff
, &pkt_diff
, <)) {
624 struct timeval delay
;
626 timersub(&pkt_diff
, &diff
, &delay
);
627 TIMEVAL_TO_TIMESPEC(&delay
, &sh
->delay
);
630 memcpy(&sh
->tstamp
, &tstamp
, sizeof(sh
->tstamp
));
633 if ((sh
->delay
.tv_sec
| sh
->delay
.tv_nsec
) > 0) {
634 nanosleep(&sh
->delay
, NULL
);
640 static inline void packet_apply_dyn_elements(int idx
)
642 if (packet_dyn_has_elems(&packet_dyn
[idx
])) {
644 apply_randomizer(idx
);
648 if (packet_dyn_has_fields(&packet_dyn
[idx
])) {
651 for (i
= 0; i
< packet_dyn
[idx
].flen
; i
++)
652 proto_field_dyn_apply(packet_dyn
[idx
].fields
[i
]);
654 proto_packet_update(idx
);
658 static void xmit_slowpath_or_die(struct ctx
*ctx
, unsigned int cpu
, unsigned long orig_num
)
660 int ret
, icmp_sock
= -1;
661 unsigned long num
= 1, i
= 0;
662 struct timeval start
, end
, diff
;
663 unsigned long long tx_bytes
= 0, tx_packets
= 0;
667 if (ctx
->num
== 0 && orig_num
> 0)
671 icmp_sock
= xmit_smoke_setup(ctx
);
673 drop_privileges(ctx
->enforce
, ctx
->uid
, ctx
->gid
);
675 bug_on(gettimeofday(&start
, NULL
));
677 if (shaper_is_set(&ctx
->sh
))
678 shaper_init(&ctx
->sh
);
680 while (likely(sigint
== 0 && num
> 0 && plen
> 0)) {
681 packet_apply_dyn_elements(i
);
683 ret
= dev_io_write(ctx
->dev_out
, &packets
[i
]);
684 if (unlikely(ret
< 0)) {
685 if (errno
== ENOBUFS
) {
690 panic("Sendto error: %s!\n", strerror(errno
));
693 tx_bytes
+= packets
[i
].len
;
696 if (ctx
->smoke_test
) {
697 ret
= xmit_smoke_probe(icmp_sock
, ctx
);
698 if (unlikely(ret
< 0)) {
699 printf("%sSmoke test alert:%s\n", colorize_start(bold
), colorize_end());
700 printf(" Remote host seems to be unresponsive to ICMP probes!\n");
701 printf(" Last instance was packet%lu, seed:%u, trafgen snippet:\n\n",
704 dump_trafgen_snippet(packets
[i
].payload
, packets
[i
].len
);
719 if (shaper_is_set(&ctx
->sh
))
720 shaper_delay(&ctx
->sh
, &packets
[i
]);
723 bug_on(gettimeofday(&end
, NULL
));
724 timersub(&end
, &start
, &diff
);
729 stats
[cpu
].tx_packets
= tx_packets
;
730 stats
[cpu
].tx_bytes
= tx_bytes
;
731 stats
[cpu
].tv_sec
= diff
.tv_sec
;
732 stats
[cpu
].tv_usec
= diff
.tv_usec
;
734 stats
[cpu
].state
|= CPU_STATS_STATE_RES
;
737 static void xmit_fastpath_or_die(struct ctx
*ctx
, unsigned int cpu
, unsigned long orig_num
)
739 int ifindex
= dev_io_ifindex_get(ctx
->dev_out
);
741 unsigned int it
= 0, retry
= 100;
742 unsigned long num
= 1, i
= 0;
743 size_t size
= ring_size(dev_io_name_get(ctx
->dev_out
), ctx
->reserve_size
);
745 struct frame_map
*hdr
;
746 struct timeval start
, end
, diff
;
747 unsigned long long tx_bytes
= 0, tx_packets
= 0;
748 int sock
= dev_io_fd_get(ctx
->dev_out
);
750 set_sock_prio(sock
, 512);
752 ring_tx_setup(&tx_ring
, sock
, size
, ifindex
, ctx
->jumbo_support
, ctx
->verbose
);
754 drop_privileges(ctx
->enforce
, ctx
->uid
, ctx
->gid
);
758 if (ctx
->num
== 0 && orig_num
> 0)
761 bug_on(gettimeofday(&start
, NULL
));
763 while (likely(sigint
== 0 && num
> 0 && plen
> 0)) {
764 if (!user_may_pull_from_tx(tx_ring
.frames
[it
].iov_base
)) {
765 int ret
= pull_and_flush_tx_ring(sock
);
766 if (unlikely(ret
< 0)) {
767 /* We could hit EBADF if the socket has been closed before
768 * the timer was triggered.
770 if (errno
!= EBADF
&& errno
!= ENOBUFS
)
771 panic("Flushing TX_RING failed: %s!\n", strerror(errno
));
777 hdr
= tx_ring
.frames
[it
].iov_base
;
778 out
= ((uint8_t *) hdr
) + TPACKET2_HDRLEN
- sizeof(struct sockaddr_ll
);
780 hdr
->tp_h
.tp_snaplen
= packets
[i
].len
;
781 hdr
->tp_h
.tp_len
= packets
[i
].len
;
783 packet_apply_dyn_elements(i
);
785 memcpy(out
, packets
[i
].payload
, packets
[i
].len
);
787 tx_bytes
+= packets
[i
].len
;
797 kernel_may_pull_from_tx(&hdr
->tp_h
);
800 if (it
>= tx_ring
.layout
.tp_frame_nr
)
807 bug_on(gettimeofday(&end
, NULL
));
808 timersub(&end
, &start
, &diff
);
810 while (pull_and_flush_tx_ring_wait(sock
) < 0 && errno
== ENOBUFS
&& retry
-- > 0)
812 destroy_tx_ring(sock
, &tx_ring
);
814 stats
[cpu
].tx_packets
= tx_packets
;
815 stats
[cpu
].tx_bytes
= tx_bytes
;
816 stats
[cpu
].tv_sec
= diff
.tv_sec
;
817 stats
[cpu
].tv_usec
= diff
.tv_usec
;
819 stats
[cpu
].state
|= CPU_STATS_STATE_RES
;
822 static inline void __set_state(unsigned int cpu
, sig_atomic_t s
)
824 stats
[cpu
].state
= s
;
827 static inline sig_atomic_t __get_state(unsigned int cpu
)
829 return stats
[cpu
].state
;
832 static unsigned long __wait_and_sum_others(struct ctx
*ctx
, unsigned int cpu
)
837 for (i
= 0, total
= plen
; i
< ctx
->cpus
; i
++) {
841 while ((__get_state(i
) &
842 (CPU_STATS_STATE_CFG
|
843 CPU_STATS_STATE_RES
)) == 0 &&
847 total
+= stats
[i
].cf_packets
;
853 static void __correct_global_delta(struct ctx
*ctx
, unsigned int cpu
, unsigned long orig
)
858 long long delta_correction
= 0;
860 for (i
= 0, total
= ctx
->num
; i
< ctx
->cpus
; i
++) {
864 while ((__get_state(i
) &
865 (CPU_STATS_STATE_CHK
|
866 CPU_STATS_STATE_RES
)) == 0 &&
870 total
+= stats
[i
].cd_packets
;
874 delta_correction
= -1 * ((long long) total
- orig
);
876 delta_correction
= +1 * ((long long) orig
- total
);
878 for (cpu_sel
= -1, i
= 0; i
< ctx
->cpus
; i
++) {
879 if (stats
[i
].cd_packets
> 0) {
880 if ((long long) stats
[i
].cd_packets
+
881 delta_correction
>= 0) {
888 if ((int) cpu
== cpu_sel
)
889 ctx
->num
+= delta_correction
;
892 static void __set_state_cf(unsigned int cpu
, unsigned long p
, unsigned long b
,
895 stats
[cpu
].cf_packets
= p
;
896 stats
[cpu
].cf_bytes
= b
;
897 stats
[cpu
].state
= s
;
900 static void __set_state_cd(unsigned int cpu
, unsigned long p
, sig_atomic_t s
)
902 stats
[cpu
].cd_packets
= p
;
903 stats
[cpu
].state
= s
;
906 static void xmit_packet_precheck(struct ctx
*ctx
, unsigned int cpu
)
908 unsigned long plen_total
, orig
= ctx
->num
;
909 size_t total_len
= 0;
912 bug_on(plen
!= dlen
);
914 for (i
= 0; i
< plen
; ++i
)
915 total_len
+= packets
[i
].len
;
917 __set_state_cf(cpu
, plen
, total_len
, CPU_STATS_STATE_CFG
);
918 plen_total
= __wait_and_sum_others(ctx
, cpu
);
921 ctx
->num
= (unsigned long) round((1.0 * plen
/ plen_total
) * orig
);
923 __set_state_cd(cpu
, ctx
->num
, CPU_STATS_STATE_CHK
|
924 CPU_STATS_STATE_CFG
);
925 __correct_global_delta(ctx
, cpu
, orig
);
929 __set_state(cpu
, CPU_STATS_STATE_RES
);
934 static void pcap_load_packets(struct dev_io
*dev
)
938 while ((pkt
= dev_io_read(dev
)) != 0)
942 static void main_loop(struct ctx
*ctx
, char *confname
, bool slow
,
943 unsigned int cpu
, bool invoke_cpp
, char **cpp_argv
,
944 unsigned long orig_num
)
946 if (ctx
->dev_in
&& dev_io_is_pcap(ctx
->dev_in
)) {
947 pcap_load_packets(ctx
->dev_in
);
948 shaper_set_tstamp(&ctx
->sh
, &packets
[0].tstamp
);
952 compile_packets_str(ctx
->packet_str
, ctx
->verbose
, cpu
);
954 compile_packets(confname
, ctx
->verbose
, cpu
, invoke_cpp
, cpp_argv
);
956 preprocess_packets();
959 xmit_packet_precheck(ctx
, cpu
);
963 size_t total_len
= 0, total_pkts
= 0;
965 for (i
= 0; i
< ctx
->cpus
; ++i
) {
966 total_len
+= stats
[i
].cf_bytes
;
967 total_pkts
+= stats
[i
].cf_packets
;
970 printf("%6zu packets to schedule\n", total_pkts
);
971 printf("%6zu bytes in total\n", total_len
);
972 printf("Running! Hang up with ^C!\n\n");
976 dev_io_open(ctx
->dev_out
);
977 if (dev_io_is_netdev(ctx
->dev_out
) && ctx
->qdisc_path
== false)
978 set_sock_qdisc_bypass(dev_io_fd_get(ctx
->dev_out
), ctx
->verbose
);
981 xmit_slowpath_or_die(ctx
, cpu
, orig_num
);
983 xmit_fastpath_or_die(ctx
, cpu
, orig_num
);
985 dev_io_close(ctx
->dev_out
);
987 dev_io_close(ctx
->dev_in
);
992 static unsigned int generate_srand_seed(void)
997 fd
= open("/dev/urandom", O_RDONLY
);
1001 read_or_die(fd
, &_seed
, sizeof(_seed
));
1007 static void on_panic_del_rfmon(void *arg
)
1012 int main(int argc
, char **argv
)
1014 bool slow
= false, invoke_cpp
= false, reseed
= true, cpustats
= true;
1015 bool prio_high
= false, set_irq_aff
= true, set_sock_mem
= true;
1016 int c
, vals
[4] = {0}, irq
;
1019 char *confname
= NULL
, *ptr
;
1020 unsigned long cpus_tmp
, orig_num
= 0;
1021 unsigned long long tx_packets
, tx_bytes
;
1024 char **cpp_argv
= NULL
;
1025 size_t cpp_argc
= 0;
1026 unsigned long long rate
;
1027 enum shaper_type shape_type
;
1028 struct timespec delay
;
1030 memset(&ctx
, 0, sizeof(ctx
));
1031 ctx
.cpus
= get_number_cpus_online();
1034 ctx
.qdisc_path
= false;
1036 /* Keep an initial small default size to reduce cache-misses. */
1037 ctx
.reserve_size
= 512 * (1 << 10);
1039 while ((c
= getopt_long(argc
, argv
, short_options
, long_options
,
1058 cpp_argv
= argv_insert(cpp_argv
, &cpp_argc
, "-D");
1059 cpp_argv
= argv_insert(cpp_argv
, &cpp_argc
, optarg
);
1065 cpus_tmp
= strtoul(optarg
, NULL
, 0);
1066 if (cpus_tmp
> 0 && cpus_tmp
< ctx
.cpus
)
1067 ctx
.cpus
= cpus_tmp
;
1071 ctx
.device
= xstrdup(optarg
);
1077 set_sock_mem
= false;
1080 set_irq_aff
= false;
1083 ctx
.qdisc_path
= true;
1091 ctx
.smoke_test
= true;
1092 ctx
.rhost
= xstrdup(optarg
);
1098 ctx
.jumbo_support
= true;
1102 confname
= xstrdup(optarg
);
1103 if (c
== 'i' && strstr(confname
, ".pcap")) {
1104 ctx
.sh
.type
= SHAPER_TSTAMP
;
1105 ctx
.pcap_in
= confname
;
1106 } else if (!strncmp("-", confname
, strlen("-")))
1110 ctx
.uid
= strtoul(optarg
, NULL
, 0);
1114 ctx
.gid
= strtoul(optarg
, NULL
, 0);
1118 printf("Option -k/--kernel-pull is no longer used and "
1119 "will be removed in a future release!\n");
1122 seed
= strtoul(optarg
, NULL
, 0);
1126 orig_num
= strtoul(optarg
, NULL
, 0);
1130 gap
= strtoul(optarg
, &ptr
, 0);
1131 if (!gap
&& optarg
== ptr
)
1132 panic("Invalid gap param\n");
1134 if (!strncmp(ptr
, "ns", strlen("ns"))) {
1135 delay
.tv_sec
= gap
/ 1000000000;
1136 delay
.tv_nsec
= gap
% 1000000000;
1137 } else if (*ptr
== '\0' || !strncmp(ptr
, "us", strlen("us"))) {
1138 /* Default to microseconds for backwards
1139 * compatibility if no postfix is given.
1141 delay
.tv_sec
= gap
/ 1000000;
1142 delay
.tv_nsec
= (gap
% 1000000) * 1000;
1143 } else if (!strncmp(ptr
, "ms", strlen("ms"))) {
1144 delay
.tv_sec
= gap
/ 1000;
1145 delay
.tv_nsec
= (gap
% 1000) * 1000000;
1146 } else if (!strncmp(ptr
, "s", strlen("s"))) {
1150 panic("Syntax error in time param!\n");
1153 shaper_set_delay(&ctx
.sh
, delay
.tv_sec
, delay
.tv_nsec
);
1156 rate
= strtoul(optarg
, &ptr
, 0);
1157 if (!rate
&& optarg
== ptr
)
1158 panic("Invalid rate param\n");
1160 if (strncmp(ptr
, "pps", strlen("pps")) == 0) {
1161 shape_type
= SHAPER_PKTS
;
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
;
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
;
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
;
1185 } else if (strncmp(ptr
, "MiB", strlen("MiB")) == 0) {
1186 shape_type
= SHAPER_BYTES
;
1188 } else if (strncmp(ptr
, "GiB", strlen("GiB")) == 0) {
1189 shape_type
= SHAPER_BYTES
;
1192 shape_type
= SHAPER_NONE
;
1194 panic("Invalid unit type for rate\n");
1197 shaper_set_rate(&ctx
.sh
, rate
, shape_type
);
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;
1211 panic("Invalid ring size unit type\n");
1229 panic("Option -%c requires an argument!\n",
1232 if (isprint(optopt
))
1233 printf("Unknown option character `0x%X\'!\n", optopt
);
1241 if (argc
>= optind
) {
1243 ctx
.packet_str
= argv2str(optind
, argc
, argv
);
1246 if (argc
< min_opts
)
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
);
1260 set_sched_status(SCHED_FIFO
, sched_get_priority_max(SCHED_FIFO
));
1264 set_system_socket_memory(vals
, array_size(vals
));
1268 ctx
.dev_in
= dev_io_create(ctx
.pcap_in
, DEV_IO_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
);
1276 panic("Failed to open output device\n");
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!
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.
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
++) {
1319 seed
= generate_srand_seed();
1323 main_loop(&ctx
, confname
, slow
, i
, invoke_cpp
,
1324 cpp_argv
, orig_num
);
1328 panic("Cannot fork processes!\n");
1332 for (i
= 0; i
< ctx
.cpus
; i
++) {
1336 if (WEXITSTATUS(status
) == EXIT_FAILURE
)
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)
1347 tx_packets
+= stats
[i
].tx_packets
;
1348 tx_bytes
+= stats
[i
].tx_bytes
;
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
);
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
);
1371 free(ctx
.packet_str
);