tprintf: fix va_list arg exhaustion
[netsniff-ng-old.git] / src / netsniff-ng.c
blob5b4428a34e68cb05b03bf7ac6f0a2ff32b0e2044
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * By Daniel Borkmann <daniel@netsniff-ng.org>
4 * Copyright 2009-2011 Daniel Borkmann.
5 * Copyright 2010 Emmanuel Roullit.
6 * Subject to the GPL, version 2.
8 * The first sniffer that invoked both, the zero-copy RX_RING as well as
9 * the zero-copy TX_RING for high-performance network I/O and scatter/gather
10 * or mmaped PCAP I/O.
12 * "I knew that danger lay ahead, of course; but I did not expect to
13 * meet it in our own Shire. Can't a hobbit walk from the Water to the
14 * River in peace?" "But it is not your own Shire," said Gildor. "Others
15 * dwelt here before hobbits were; and others will dwell here again when
16 * hobbits are no more. The wide world is all about you: you can fence
17 * yourselves in, but you cannot for ever fence it out."
19 * -- The Lord of the Rings, Gildor to Frodo,
20 * Chapter 'Three is Company'.
25 =head1 NAME
27 netsniff-ng - the packet sniffing beast
29 =head1 SYNOPSIS
31 netsniff-ng -i|-d|--dev|--in <dev|pcap> -o|--out <dev|pcap|dir|txf>
32 [-f|--filter <bpf-file>][-t|--type <type>][-F|--interval <uint>]
33 [-s|--silent][-J|--jumbo-support][-n|--num <uint>][-r|--rand]
34 [-M|--no-promisc][-m|--mmap | -c|--clrw][-S|--ring-size <size>]
35 [-k|--kernel-pull <uint>][-b|--bind-cpu <cpu> | -B|--unbind-cpu <cpu>]
36 [-H|--prio-high][-Q|--notouch-irq][-q|--less | -X|--hex | -l|--ascii]
37 [-v|--version][-h|--help]
39 =head1 DESCRIPTION
41 The first sniffer that invoked both, the zero-copy RX_RING as well as
42 the zero-copy TX_RING for high-performance network I/O and scatter/gather
43 or mmaped PCAP I/O.
45 =head1 EXAMPLES
47 =over
49 =item netsniff-ng --in eth0 --out dump.pcap
51 Capture traffic from interface 'eth0' and save it pcap file 'dump.pcap'
53 =item netsniff-ng --in any --filter http.bpf --payload
55 Capture HTTP traffic from any interface and print its payload on stdout
57 =item netsniff-ng --in wlan0 --bind-cpu 0,1
59 Capture all traffic from wlan0 interface.
60 Schedule process on CPU 0 and 1.
62 =back
64 =head1 OPTIONS
66 =over
68 =item -i|-d|--dev|--in <dev|pcap>
70 Input source. Can be a network device or pcap file.
72 =item -o|--out <dev|pcap|dir|txf>
74 Output sink. Can be a network device, pcap file, a trafgen txf file or a
75 directory. (There's only pcap to txf translation possible.)
77 =item -f|--filter <bpf-file>
79 Use BPF filter file from bpfc.
81 =item -t|--type <type>
83 =over
85 =item Only handle packets of defined type:
87 =over
89 =item - broadcast
91 =item - multicast
93 =item - others
95 =item - outgoing
97 =back
99 =back
101 =item -F|--interval <uint>
103 Dump interval in seconds. if -o is a directory, a new pcap will be created at each interval.
104 The older files are left untouched. (default value: 60 seconds)
106 =item -s|--silent
108 Do not print captured packets to stdout.
110 =item -J|--jumbo-support
112 Support for 64KB Super Jumbo Frames.
114 =item -n|--num <uint>
116 When zerp, capture/replay until SIGINT is received (default).
117 When non-zero, capture/replay the number of packets.
119 =item -r|--rand
121 Randomize packet forwarding order (replay mode only).
123 =item -M|--no-promisc
125 Do not place the interface in promiscuous mode.
127 =item -m|--mmap
129 Mmap pcap file i.e., for replaying. Default: scatter/gather I/O.
131 =item -c|--clrw
133 Instead of using scatter/gather I/O use slower read(2)/write(2) I/O.
135 =item -S|--ring-size <size>
137 Manually set ring size in KB/MB/GB, e.g. '10MB'.
139 =item -k|--kernel-pull <uint>
141 Kernel pull from user interval in microseconds. Default is 10us. (replay mode only).
143 =item -b|--bind-cpu <cpu>
145 Bind to specific CPU (or CPU-range).
147 =item -B|--unbind-cpu <cpu>
149 Forbid to use specific CPU (or CPU-range).
151 =item -H|--prio-high
153 Run the process in high-priority mode.
155 =item -Q|--notouch-irq
157 Do not touch IRQ CPU affinity of NIC.
159 =item -q|--less
161 Print less-verbose packet information.
163 =item -X|--hex
165 Print packet data in hex format.
167 =item -l|--ascii
169 Print human-readable packet data.
171 =item -v|--version
173 Print version.
175 =item -h|--help
177 Print help text and lists all options.
179 =back
181 =head1 AUTHOR
183 Written by Daniel Borkmann <daniel@netsniff-ng.org> and Emmanuel Roullit <emmanuel@netsniff-ng.org>
185 =head1 DOCUMENTATION
187 Documentation by Emmanuel Roullit <emmanuel@netsniff-ng.org>
189 =head1 BUGS
191 Please report bugs to <bugs@netsniff-ng.org>
193 =cut
197 #define _GNU_SOURCE
198 #include <stdio.h>
199 #include <stdlib.h>
200 #include <signal.h>
201 #include <getopt.h>
202 #include <ctype.h>
203 #include <time.h>
204 #include <string.h>
205 #include <sys/socket.h>
206 #include <sys/types.h>
207 #include <sys/stat.h>
208 #include <sys/time.h>
209 #include <unistd.h>
210 #include <stdbool.h>
211 #include <pthread.h>
212 #include <fcntl.h>
214 #include "ring_rx.h"
215 #include "ring_tx.h"
216 #include "mac80211.h"
217 #include "xsys.h"
218 #include "built_in.h"
219 #include "pcap.h"
220 #include "bpf.h"
221 #include "xio.h"
222 #include "xstring.h"
223 #include "die.h"
224 #include "tprintf.h"
225 #include "dissector.h"
226 #include "xmalloc.h"
227 #include "mtrand.h"
229 #define CPU_UNKNOWN -1
230 #define CPU_NOTOUCH -2
231 #define PACKET_ALL -1
232 #define DUMP_INTERVAL 60
234 struct mode {
235 char *device_in;
236 char *device_out;
237 char *device_trans;
238 char *filter;
239 int cpu;
240 int rfraw;
241 int dump;
242 uint32_t link_type;
243 int print_mode;
244 unsigned int reserve_size;
245 int packet_type;
246 bool randomize;
247 bool promiscuous;
248 enum pcap_ops_groups pcap;
249 unsigned long kpull;
250 int jumbo_support;
251 int dump_dir;
252 unsigned long dump_interval;
255 struct tx_stats {
256 unsigned long tx_bytes;
257 unsigned long tx_packets;
260 volatile sig_atomic_t sigint = 0;
262 static int tx_sock;
263 static unsigned long frame_cnt_max = 0;
264 static unsigned long interval = TX_KERNEL_PULL_INT;
265 static struct itimerval itimer;
266 static volatile bool next_dump = false;
268 static const char *short_options = "d:i:o:rf:MJt:S:k:n:b:B:HQmcsqXlvhF:R";
270 static struct option long_options[] = {
271 {"dev", required_argument, 0, 'd'},
272 {"in", required_argument, 0, 'i'},
273 {"out", required_argument, 0, 'o'},
274 {"rand", no_argument, 0, 'r'},
275 {"rfraw", no_argument, 0, 'R'},
276 {"mmap", no_argument, 0, 'm'},
277 {"clrw", no_argument, 0, 'c'},
278 {"jumbo-support", no_argument, 0, 'J'},
279 {"filter", required_argument, 0, 'f'},
280 {"no-promisc", no_argument, 0, 'M'},
281 {"num", required_argument, 0, 'n'},
282 {"type", required_argument, 0, 't'},
283 {"interval", required_argument, 0, 'F'},
284 {"ring-size", required_argument, 0, 'S'},
285 {"kernel-pull", required_argument, 0, 'k'},
286 {"bind-cpu", required_argument, 0, 'b'},
287 {"unbind-cpu", required_argument, 0, 'B'},
288 {"prio-high", no_argument, 0, 'H'},
289 {"notouch-irq", no_argument, 0, 'Q'},
290 {"silent", no_argument, 0, 's'},
291 {"less", no_argument, 0, 'q'},
292 {"hex", no_argument, 0, 'X'},
293 {"ascii", no_argument, 0, 'l'},
294 {"version", no_argument, 0, 'v'},
295 {"help", no_argument, 0, 'h'},
296 {0, 0, 0, 0}
299 static void signal_handler(int number)
301 switch (number) {
302 case SIGINT:
303 sigint = 1;
304 break;
305 case SIGHUP:
306 break;
307 default:
308 break;
312 static void timer_elapsed(int number)
314 itimer.it_interval.tv_sec = 0;
315 itimer.it_interval.tv_usec = interval;
316 itimer.it_value.tv_sec = 0;
317 itimer.it_value.tv_usec = interval;
319 pull_and_flush_tx_ring(tx_sock);
320 setitimer(ITIMER_REAL, &itimer, NULL);
323 static void timer_next_dump(int number)
325 itimer.it_interval.tv_sec = interval;
326 itimer.it_interval.tv_usec = 0;
327 itimer.it_value.tv_sec = interval;
328 itimer.it_value.tv_usec = 0;
330 next_dump = true;
331 setitimer(ITIMER_REAL, &itimer, NULL);
334 static void enter_mode_pcap_to_tx(struct mode *mode)
336 int irq, ifindex, fd = 0, ret;
337 unsigned int size, it = 0;
338 struct ring tx_ring;
339 struct frame_map *hdr;
340 struct sock_fprog bpf_ops;
341 struct tx_stats stats;
342 uint8_t *out = NULL;
343 unsigned long trunced = 0;
345 if (!device_up_and_running(mode->device_out))
346 panic("Device not up and running!\n");
348 tx_sock = pf_socket();
350 if (!pcap_ops[mode->pcap])
351 panic("pcap group not supported!\n");
352 fd = open_or_die(mode->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
353 ret = pcap_ops[mode->pcap]->pull_file_header(fd, &mode->link_type);
354 if (ret)
355 panic("error reading pcap header!\n");
356 if (pcap_ops[mode->pcap]->prepare_reading_pcap) {
357 ret = pcap_ops[mode->pcap]->prepare_reading_pcap(fd);
358 if (ret)
359 panic("error prepare reading pcap!\n");
362 fmemset(&tx_ring, 0, sizeof(tx_ring));
363 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
364 fmemset(&stats, 0, sizeof(stats));
366 if (mode->rfraw) {
367 mode->device_trans = xstrdup(mode->device_out);
368 xfree(mode->device_out);
370 enter_rfmon_mac80211(mode->device_trans, &mode->device_out);
371 if (mode->link_type != LINKTYPE_IEEE802_11)
372 panic("Wrong linktype of pcap!\n");
375 ifindex = device_ifindex(mode->device_out);
376 size = ring_size(mode->device_out, mode->reserve_size);
378 bpf_parse_rules(mode->filter, &bpf_ops);
380 set_packet_loss_discard(tx_sock);
381 set_sockopt_hwtimestamp(tx_sock, mode->device_out);
382 setup_tx_ring_layout(tx_sock, &tx_ring, size, mode->jumbo_support);
383 create_tx_ring(tx_sock, &tx_ring);
384 mmap_tx_ring(tx_sock, &tx_ring);
385 alloc_tx_ring_frames(&tx_ring);
386 bind_tx_ring(tx_sock, &tx_ring, ifindex);
388 dissector_init_all(mode->print_mode);
390 if (mode->cpu >= 0 && ifindex > 0) {
391 irq = device_irq_number(mode->device_out);
392 device_bind_irq_to_cpu(mode->cpu, irq);
393 printf("IRQ: %s:%d > CPU%d\n", mode->device_out, irq,
394 mode->cpu);
397 if (mode->kpull)
398 interval = mode->kpull;
400 itimer.it_interval.tv_sec = 0;
401 itimer.it_interval.tv_usec = interval;
402 itimer.it_value.tv_sec = 0;
403 itimer.it_value.tv_usec = interval;
404 setitimer(ITIMER_REAL, &itimer, NULL);
406 printf("BPF:\n");
407 bpf_dump_all(&bpf_ops);
408 printf("MD: TX %luus %s ", interval, pcap_ops[mode->pcap]->name);
409 if (mode->rfraw)
410 printf("802.11 raw via %s ", mode->device_out);
411 ioprio_print();
412 printf("\n");
414 while (likely(sigint == 0)) {
415 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
416 struct pcap_pkthdr phdr;
417 hdr = tx_ring.frames[it].iov_base;
418 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
419 * sizeof(struct sockaddr_ll); */
420 out = ((uint8_t *) hdr) + TPACKET_HDRLEN -
421 sizeof(struct sockaddr_ll);
423 do {
424 memset(&phdr, 0, sizeof(phdr));
425 ret = pcap_ops[mode->pcap]->read_pcap_pkt(fd, &phdr,
426 out, ring_frame_size(&tx_ring));
427 if (unlikely(ret <= 0))
428 goto out;
429 if (ring_frame_size(&tx_ring) < phdr.len) {
430 phdr.len = ring_frame_size(&tx_ring);
431 trunced++;
433 } while (mode->filter && !bpf_run_filter(&bpf_ops, out, phdr.len));
434 pcap_pkthdr_to_tpacket_hdr(&phdr, &hdr->tp_h);
436 stats.tx_bytes += hdr->tp_h.tp_len;;
437 stats.tx_packets++;
439 show_frame_hdr(hdr, mode->print_mode, RING_MODE_EGRESS);
440 dissector_entry_point(out, hdr->tp_h.tp_snaplen,
441 mode->link_type, mode->print_mode);
443 kernel_may_pull_from_tx(&hdr->tp_h);
444 next_slot_prewr(&it, &tx_ring);
446 if (unlikely(sigint == 1))
447 break;
448 if (frame_cnt_max != 0 &&
449 stats.tx_packets >= frame_cnt_max) {
450 sigint = 1;
451 break;
455 out:
456 fflush(stdout);
457 printf("\n");
458 printf("\r%12lu frames outgoing\n", stats.tx_packets);
459 printf("\r%12lu frames truncated (larger than frame)\n", trunced);
460 printf("\r%12lu bytes outgoing\n", stats.tx_bytes);
462 bpf_release(&bpf_ops);
463 dissector_cleanup_all();
464 destroy_tx_ring(tx_sock, &tx_ring);
466 if (mode->rfraw)
467 leave_rfmon_mac80211(mode->device_trans, mode->device_out);
469 close(tx_sock);
470 if (pcap_ops[mode->pcap]->prepare_close_pcap)
471 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_READ);
472 close(fd);
475 static void enter_mode_rx_to_tx(struct mode *mode)
477 int rx_sock, ifindex_in, ifindex_out;
478 unsigned int size_in, size_out, it_in = 0, it_out = 0;
479 unsigned long fcnt = 0;
480 uint8_t *in, *out;
481 short ifflags = 0;
482 struct frame_map *hdr_in, *hdr_out;
483 struct ring tx_ring;
484 struct ring rx_ring;
485 struct pollfd rx_poll;
486 struct sock_fprog bpf_ops;
488 if (!strncmp(mode->device_in, mode->device_out,
489 strlen(mode->device_in)))
490 panic("Ingress/egress devices must be different!\n");
491 if (!device_up_and_running(mode->device_out))
492 panic("Egress device not up and running!\n");
493 if (!device_up_and_running(mode->device_in))
494 panic("Ingress device not up and running!\n");
496 rx_sock = pf_socket();
497 tx_sock = pf_socket();
499 fmemset(&tx_ring, 0, sizeof(tx_ring));
500 fmemset(&rx_ring, 0, sizeof(rx_ring));
501 fmemset(&rx_poll, 0, sizeof(rx_poll));
502 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
504 ifindex_in = device_ifindex(mode->device_in);
505 size_in = ring_size(mode->device_in, mode->reserve_size);
507 ifindex_out = device_ifindex(mode->device_out);
508 size_out = ring_size(mode->device_out, mode->reserve_size);
510 enable_kernel_bpf_jit_compiler();
511 bpf_parse_rules(mode->filter, &bpf_ops);
512 bpf_attach_to_sock(rx_sock, &bpf_ops);
514 setup_rx_ring_layout(rx_sock, &rx_ring, size_in, mode->jumbo_support);
515 create_rx_ring(rx_sock, &rx_ring);
516 mmap_rx_ring(rx_sock, &rx_ring);
517 alloc_rx_ring_frames(&rx_ring);
518 bind_rx_ring(rx_sock, &rx_ring, ifindex_in);
519 prepare_polling(rx_sock, &rx_poll);
521 set_packet_loss_discard(tx_sock);
522 setup_tx_ring_layout(tx_sock, &tx_ring, size_out, mode->jumbo_support);
523 create_tx_ring(tx_sock, &tx_ring);
524 mmap_tx_ring(tx_sock, &tx_ring);
525 alloc_tx_ring_frames(&tx_ring);
526 bind_tx_ring(tx_sock, &tx_ring, ifindex_out);
528 mt_init_by_seed_time();
529 dissector_init_all(mode->print_mode);
531 if (mode->promiscuous == true) {
532 ifflags = enter_promiscuous_mode(mode->device_in);
533 printf("PROMISC\n");
536 if (mode->kpull)
537 interval = mode->kpull;
539 itimer.it_interval.tv_sec = 0;
540 itimer.it_interval.tv_usec = interval;
541 itimer.it_value.tv_sec = 0;
542 itimer.it_value.tv_usec = interval;
543 setitimer(ITIMER_REAL, &itimer, NULL);
545 printf("BPF:\n");
546 bpf_dump_all(&bpf_ops);
547 printf("MD: RXTX %luus\n\n", interval);
548 printf("Running! Hang up with ^C!\n\n");
550 while (likely(sigint == 0)) {
551 while (user_may_pull_from_rx(rx_ring.frames[it_in].iov_base)) {
552 hdr_in = rx_ring.frames[it_in].iov_base;
553 in = ((uint8_t *) hdr_in) + hdr_in->tp_h.tp_mac;
554 fcnt++;
555 if (mode->packet_type != PACKET_ALL)
556 if (mode->packet_type != hdr_in->s_ll.sll_pkttype)
557 goto next;
559 hdr_out = tx_ring.frames[it_out].iov_base;
560 out = ((uint8_t *) hdr_out) + TPACKET_HDRLEN -
561 sizeof(struct sockaddr_ll);
563 for (; !user_may_pull_from_tx(tx_ring.frames[it_out].iov_base) &&
564 likely(!sigint);) {
565 if (mode->randomize)
566 next_rnd_slot(&it_out, &tx_ring);
567 else
568 next_slot(&it_out, &tx_ring);
569 hdr_out = tx_ring.frames[it_out].iov_base;
570 out = ((uint8_t *) hdr_out) + TPACKET_HDRLEN -
571 sizeof(struct sockaddr_ll);
574 tpacket_hdr_clone(&hdr_out->tp_h, &hdr_in->tp_h);
575 fmemcpy(out, in, hdr_in->tp_h.tp_len);
577 kernel_may_pull_from_tx(&hdr_out->tp_h);
578 if (mode->randomize)
579 next_rnd_slot(&it_out, &tx_ring);
580 else
581 next_slot(&it_out, &tx_ring);
583 show_frame_hdr(hdr_in, mode->print_mode, RING_MODE_INGRESS);
584 dissector_entry_point(in, hdr_in->tp_h.tp_snaplen,
585 mode->link_type, mode->print_mode);
587 if (frame_cnt_max != 0 && fcnt >= frame_cnt_max) {
588 sigint = 1;
589 break;
591 next:
592 kernel_may_pull_from_rx(&hdr_in->tp_h);
593 next_slot(&it_in, &rx_ring);
595 if (unlikely(sigint == 1))
596 goto out;
599 poll(&rx_poll, 1, -1);
600 poll_error_maybe_die(rx_sock, &rx_poll);
602 out:
603 sock_print_net_stats(rx_sock, 0);
605 bpf_release(&bpf_ops);
606 dissector_cleanup_all();
607 destroy_tx_ring(tx_sock, &tx_ring);
608 destroy_rx_ring(rx_sock, &rx_ring);
610 if (mode->promiscuous == true)
611 leave_promiscuous_mode(mode->device_in, ifflags);
613 close(tx_sock);
614 close(rx_sock);
617 static void enter_mode_read_pcap(struct mode *mode)
619 int ret, fd, fdo = 0;
620 struct pcap_pkthdr phdr;
621 struct sock_fprog bpf_ops;
622 struct tx_stats stats;
623 struct frame_map fm;
624 uint8_t *out;
625 size_t out_len;
626 unsigned long trunced = 0;
628 if (!pcap_ops[mode->pcap])
629 panic("pcap group not supported!\n");
630 fd = open_or_die(mode->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
631 ret = pcap_ops[mode->pcap]->pull_file_header(fd, &mode->link_type);
632 if (ret)
633 panic("error reading pcap header!\n");
634 if (pcap_ops[mode->pcap]->prepare_reading_pcap) {
635 ret = pcap_ops[mode->pcap]->prepare_reading_pcap(fd);
636 if (ret)
637 panic("error prepare reading pcap!\n");
640 fmemset(&fm, 0, sizeof(fm));
641 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
642 fmemset(&stats, 0, sizeof(stats));
644 bpf_parse_rules(mode->filter, &bpf_ops);
645 dissector_init_all(mode->print_mode);
647 out_len = 64 * 1024;
648 out = xmalloc_aligned(out_len, CO_CACHE_LINE_SIZE);
650 printf("BPF:\n");
651 bpf_dump_all(&bpf_ops);
652 printf("MD: RD %s ", pcap_ops[mode->pcap]->name);
653 ioprio_print();
654 printf("\n");
656 if (mode->device_out) {
657 fdo = open_or_die_m(mode->device_out, O_RDWR | O_CREAT |
658 O_TRUNC | O_LARGEFILE, S_IRUSR | S_IWUSR);
661 while (likely(sigint == 0)) {
662 do {
663 memset(&phdr, 0, sizeof(phdr));
664 ret = pcap_ops[mode->pcap]->read_pcap_pkt(fd, &phdr,
665 out, out_len);
666 if (unlikely(ret < 0))
667 goto out;
668 if (unlikely(phdr.len == 0)) {
669 trunced++;
670 continue;
672 if (unlikely(phdr.len > out_len)) {
673 phdr.len = out_len;
674 trunced++;
676 } while (mode->filter &&
677 !bpf_run_filter(&bpf_ops, out, phdr.len));
679 pcap_pkthdr_to_tpacket_hdr(&phdr, &fm.tp_h);
681 stats.tx_bytes += fm.tp_h.tp_len;
682 stats.tx_packets++;
684 show_frame_hdr(&fm, mode->print_mode, RING_MODE_EGRESS);
685 dissector_entry_point(out, fm.tp_h.tp_snaplen,
686 mode->link_type, mode->print_mode);
688 if (mode->device_out) {
689 int i = 0;
690 char bout[80];
691 slprintf(bout, sizeof(bout), "{\n ");
692 write_or_die(fdo, bout, strlen(bout));
694 while (i < fm.tp_h.tp_snaplen) {
695 slprintf(bout, sizeof(bout), "0x%02x, ", out[i]);
696 write_or_die(fdo, bout, strlen(bout));
697 i++;
698 if (i % 10 == 0) {
699 slprintf(bout, sizeof(bout), "\n", out[i]);
700 write_or_die(fdo, bout, strlen(bout));
701 if (i < fm.tp_h.tp_snaplen) {
702 slprintf(bout, sizeof(bout), " ", out[i]);
703 write_or_die(fdo, bout, strlen(bout));
707 if (i % 10 != 0) {
708 slprintf(bout, sizeof(bout), "\n");
709 write_or_die(fdo, bout, strlen(bout));
711 slprintf(bout, sizeof(bout), "}\n\n");
712 write_or_die(fdo, bout, strlen(bout));
715 if (frame_cnt_max != 0 &&
716 stats.tx_packets >= frame_cnt_max) {
717 sigint = 1;
718 break;
721 out:
722 fflush(stdout);
723 printf("\n");
724 printf("\r%12lu frames outgoing\n", stats.tx_packets);
725 printf("\r%12lu frames truncated (larger than mtu)\n", trunced);
726 printf("\r%12lu bytes outgoing\n", stats.tx_bytes);
728 xfree(out);
730 bpf_release(&bpf_ops);
731 dissector_cleanup_all();
732 if (pcap_ops[mode->pcap]->prepare_close_pcap)
733 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_READ);
734 close(fd);
736 if (mode->device_out)
737 close(fdo);
740 static void finish_multi_pcap_file(struct mode *mode, int fd)
742 pcap_ops[mode->pcap]->fsync_pcap(fd);
743 if (pcap_ops[mode->pcap]->prepare_close_pcap)
744 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_WRITE);
745 close(fd);
747 fmemset(&itimer, 0, sizeof(itimer));
748 setitimer(ITIMER_REAL, &itimer, NULL);
751 static int next_multi_pcap_file(struct mode *mode, int fd)
753 int ret;
754 char tmp[512];
756 pcap_ops[mode->pcap]->fsync_pcap(fd);
757 if (pcap_ops[mode->pcap]->prepare_close_pcap)
758 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_WRITE);
759 close(fd);
761 slprintf(tmp, sizeof(tmp), "%s/%lu.pcap", mode->device_out, time(0));
763 fd = open_or_die_m(tmp, O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE,
764 S_IRUSR | S_IWUSR);
765 ret = pcap_ops[mode->pcap]->push_file_header(fd, mode->link_type);
766 if (ret)
767 panic("error writing pcap header!\n");
768 if (pcap_ops[mode->pcap]->prepare_writing_pcap) {
769 ret = pcap_ops[mode->pcap]->prepare_writing_pcap(fd);
770 if (ret)
771 panic("error prepare writing pcap!\n");
774 return fd;
777 static int begin_multi_pcap_file(struct mode *mode)
779 int fd, ret;
780 char tmp[512];
782 if (!pcap_ops[mode->pcap])
783 panic("pcap group not supported!\n");
784 if (mode->device_out[strlen(mode->device_out) - 1] == '/')
785 mode->device_out[strlen(mode->device_out) - 1] = 0;
787 slprintf(tmp, sizeof(tmp), "%s/%lu.pcap", mode->device_out, time(0));
789 fd = open_or_die_m(tmp, O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE,
790 S_IRUSR | S_IWUSR);
791 ret = pcap_ops[mode->pcap]->push_file_header(fd, mode->link_type);
792 if (ret)
793 panic("error writing pcap header!\n");
794 if (pcap_ops[mode->pcap]->prepare_writing_pcap) {
795 ret = pcap_ops[mode->pcap]->prepare_writing_pcap(fd);
796 if (ret)
797 panic("error prepare writing pcap!\n");
800 interval = mode->dump_interval;
801 itimer.it_interval.tv_sec = interval;
802 itimer.it_interval.tv_usec = 0;
803 itimer.it_value.tv_sec = interval;
804 itimer.it_value.tv_usec = 0;
805 setitimer(ITIMER_REAL, &itimer, NULL);
807 return fd;
810 static void finish_single_pcap_file(struct mode *mode, int fd)
812 pcap_ops[mode->pcap]->fsync_pcap(fd);
813 if (pcap_ops[mode->pcap]->prepare_close_pcap)
814 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_WRITE);
815 close(fd);
818 static int begin_single_pcap_file(struct mode *mode)
820 int fd, ret;
822 if (!pcap_ops[mode->pcap])
823 panic("pcap group not supported!\n");
824 fd = open_or_die_m(mode->device_out,
825 O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE,
826 S_IRUSR | S_IWUSR);
827 ret = pcap_ops[mode->pcap]->push_file_header(fd, mode->link_type);
828 if (ret)
829 panic("error writing pcap header!\n");
830 if (pcap_ops[mode->pcap]->prepare_writing_pcap) {
831 ret = pcap_ops[mode->pcap]->prepare_writing_pcap(fd);
832 if (ret)
833 panic("error prepare writing pcap!\n");
836 return fd;
839 static void enter_mode_rx_only_or_dump(struct mode *mode)
841 int sock, irq, ifindex, fd = 0, ret;
842 unsigned int size, it = 0;
843 unsigned long fcnt = 0, skipped = 0;
844 short ifflags = 0;
845 uint8_t *packet;
846 struct ring rx_ring;
847 struct pollfd rx_poll;
848 struct frame_map *hdr;
849 struct sock_fprog bpf_ops;
851 if (!device_up_and_running(mode->device_in))
852 panic("Device not up and running!\n");
854 sock = pf_socket();
856 if (mode->rfraw) {
857 mode->device_trans = xstrdup(mode->device_in);
858 xfree(mode->device_in);
860 enter_rfmon_mac80211(mode->device_trans, &mode->device_in);
861 mode->link_type = LINKTYPE_IEEE802_11;
864 if (mode->dump) {
865 struct stat tmp;
866 fmemset(&tmp, 0, sizeof(tmp));
867 ret = stat(mode->device_out, &tmp);
868 if (ret < 0) {
869 mode->dump_dir = 0;
870 goto try_file;
872 mode->dump_dir = !!S_ISDIR(tmp.st_mode);
873 if (mode->dump_dir) {
874 fd = begin_multi_pcap_file(mode);
875 } else {
876 try_file:
877 fd = begin_single_pcap_file(mode);
881 fmemset(&rx_ring, 0, sizeof(rx_ring));
882 fmemset(&rx_poll, 0, sizeof(rx_poll));
883 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
885 ifindex = device_ifindex(mode->device_in);
886 size = ring_size(mode->device_in, mode->reserve_size);
888 enable_kernel_bpf_jit_compiler();
889 bpf_parse_rules(mode->filter, &bpf_ops);
890 bpf_attach_to_sock(sock, &bpf_ops);
892 set_sockopt_hwtimestamp(sock, mode->device_in);
893 setup_rx_ring_layout(sock, &rx_ring, size, mode->jumbo_support);
894 create_rx_ring(sock, &rx_ring);
895 mmap_rx_ring(sock, &rx_ring);
896 alloc_rx_ring_frames(&rx_ring);
897 bind_rx_ring(sock, &rx_ring, ifindex);
899 prepare_polling(sock, &rx_poll);
900 dissector_init_all(mode->print_mode);
902 if (mode->cpu >= 0 && ifindex > 0) {
903 irq = device_irq_number(mode->device_in);
904 device_bind_irq_to_cpu(mode->cpu, irq);
905 printf("IRQ: %s:%d > CPU%d\n", mode->device_in, irq,
906 mode->cpu);
909 if (mode->promiscuous == true) {
910 ifflags = enter_promiscuous_mode(mode->device_in);
911 printf("PROMISC\n");
914 printf("BPF:\n");
915 bpf_dump_all(&bpf_ops);
916 printf("MD: RX %s ", mode->dump ? pcap_ops[mode->pcap]->name : "");
917 if (mode->rfraw)
918 printf("802.11 raw via %s ", mode->device_in);
919 ioprio_print();
920 printf("\n");
922 while (likely(sigint == 0)) {
923 while (user_may_pull_from_rx(rx_ring.frames[it].iov_base)) {
924 hdr = rx_ring.frames[it].iov_base;
925 packet = ((uint8_t *) hdr) + hdr->tp_h.tp_mac;
926 fcnt++;
928 if (mode->packet_type != PACKET_ALL)
929 if (mode->packet_type != hdr->s_ll.sll_pkttype)
930 goto next;
931 if (unlikely(ring_frame_size(&rx_ring) <
932 hdr->tp_h.tp_snaplen)) {
933 skipped++;
934 goto next;
936 if (mode->dump) {
937 struct pcap_pkthdr phdr;
938 tpacket_hdr_to_pcap_pkthdr(&hdr->tp_h, &phdr);
939 ret = pcap_ops[mode->pcap]->write_pcap_pkt(fd, &phdr,
940 packet, phdr.len);
941 if (unlikely(ret != sizeof(phdr) + phdr.len))
942 panic("Write error to pcap!\n");
945 show_frame_hdr(hdr, mode->print_mode, RING_MODE_INGRESS);
946 dissector_entry_point(packet, hdr->tp_h.tp_snaplen,
947 mode->link_type, mode->print_mode);
949 if (frame_cnt_max != 0 && fcnt >= frame_cnt_max) {
950 sigint = 1;
951 break;
953 next:
954 kernel_may_pull_from_rx(&hdr->tp_h);
955 next_slot_prerd(&it, &rx_ring);
957 if (unlikely(sigint == 1))
958 break;
959 if (mode->dump && next_dump) {
960 struct tpacket_stats kstats;
961 socklen_t slen = sizeof(kstats);
962 fmemset(&kstats, 0, sizeof(kstats));
963 getsockopt(sock, SOL_PACKET, PACKET_STATISTICS,
964 &kstats, &slen);
965 fd = next_multi_pcap_file(mode, fd);
966 next_dump = false;
967 if (mode->print_mode == FNTTYPE_PRINT_NONE) {
968 printf(".(+%lu/-%lu)",
969 1UL * kstats.tp_packets -
970 kstats.tp_drops -
971 skipped, 1UL * kstats.tp_drops +
972 skipped);
973 fflush(stdout);
978 poll(&rx_poll, 1, -1);
979 poll_error_maybe_die(sock, &rx_poll);
982 if (!(mode->dump_dir && mode->print_mode == FNTTYPE_PRINT_NONE))
983 sock_print_net_stats(sock, skipped);
984 else {
985 printf("\n\n");
986 fflush(stdout);
989 bpf_release(&bpf_ops);
990 dissector_cleanup_all();
991 destroy_rx_ring(sock, &rx_ring);
993 if (mode->promiscuous == true)
994 leave_promiscuous_mode(mode->device_in, ifflags);
996 if (mode->rfraw)
997 leave_rfmon_mac80211(mode->device_trans, mode->device_in);
999 close(sock);
1001 if (mode->dump) {
1002 if (mode->dump_dir)
1003 finish_multi_pcap_file(mode, fd);
1004 else
1005 finish_single_pcap_file(mode, fd);
1009 static void help(void)
1011 printf("\n%s %s, the packet sniffing beast\n", PROGNAME_STRING,
1012 VERSION_STRING);
1013 printf("http://www.netsniff-ng.org\n\n");
1014 printf("Usage: netsniff-ng [options]\n");
1015 printf("Options:\n");
1016 printf(" -i|-d|--dev|--in <dev|pcap> Input source as netdev or pcap\n");
1017 printf(" -o|--out <dev|pcap|dir|txf> Output sink as netdev, pcap, directory, txf file\n");
1018 printf(" -f|--filter <bpf-file> Use BPF filter file from bpfc\n");
1019 printf(" -t|--type <type> Only handle packets of defined type:\n");
1020 printf(" host|broadcast|multicast|others|outgoing\n");
1021 printf(" -F|--interval <uint> Dump interval in sec if -o is a directory where\n");
1022 printf(" pcap files should be stored (default: 60)\n");
1023 printf(" -J|--jumbo-support Support for 64KB Super Jumbo Frames\n");
1024 printf(" Default RX/TX slot: 2048Byte\n");
1025 printf(" -R|--rfraw Capture or inject raw 802.11 frames\n");
1026 printf(" -n|--num <uint> Number of packets until exit\n");
1027 printf(" `-- 0 Loop until interrupted (default)\n");
1028 printf(" `- n Send n packets and done\n");
1029 printf("Options for printing:\n");
1030 printf(" -s|--silent Do not print captured packets\n");
1031 printf(" -q|--less Print less-verbose packet information\n");
1032 printf(" -X|--hex Print packet data in hex format\n");
1033 printf(" -l|--ascii Print human-readable packet data\n");
1034 printf("Options, advanced:\n");
1035 printf(" -r|--rand Randomize packet forwarding order\n");
1036 printf(" -M|--no-promisc No promiscuous mode for netdev\n");
1037 printf(" -m|--mmap Mmap pcap file i.e., for replaying\n");
1038 printf(" Default: scatter-gather I/O\n");
1039 printf(" -c|--clrw Use slower read(2)/write(2) I/O\n");
1040 printf(" -S|--ring-size <size> Manually set ring size to <size>:\n");
1041 printf(" mmap space in KB/MB/GB, e.g. \'10MB\'\n");
1042 printf(" -k|--kernel-pull <uint> Kernel pull from user interval in us\n");
1043 printf(" Default is 10us where the TX_RING\n");
1044 printf(" is populated with payload from uspace\n");
1045 printf(" -b|--bind-cpu <cpu> Bind to specific CPU (or CPU-range)\n");
1046 printf(" -B|--unbind-cpu <cpu> Forbid to use specific CPU (or CPU-range)\n");
1047 printf(" -H|--prio-high Make this high priority process\n");
1048 printf(" -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n");
1049 printf(" -v|--version Show version\n");
1050 printf(" -h|--help Guess what?!\n");
1051 printf("\n");
1052 printf("Examples:\n");
1053 printf(" netsniff-ng --in eth0 --out dump.pcap --silent --bind-cpu 0\n");
1054 printf(" netsniff-ng --in wlan0 --rfraw --out dump.pcap --silent --bind-cpu 0\n");
1055 printf(" netsniff-ng --in dump.pcap --mmap --out eth0 --silent --bind-cpu 0\n");
1056 printf(" netsniff-ng --in dump.pcap --out dump.txf --silent --bind-cpu 0\n");
1057 printf(" netsniff-ng --in eth0 --out eth1 --silent --bind-cpu 0 --type host\n");
1058 printf(" netsniff-ng --in eth1 --out /opt/probe1/ -s -m -J --interval 30 -b 0\n");
1059 printf(" netsniff-ng --in any --filter http.bpf --jumbo-support --ascii\n");
1060 printf("\n");
1061 printf("Note:\n");
1062 printf(" This tool is targeted for network developers! You should\n");
1063 printf(" be aware of what you are doing and what these options above\n");
1064 printf(" mean! Use netsniff-ng's bpfc compiler for generating filter files.\n");
1065 printf(" Further, netsniff-ng automatically enables the kernel BPF JIT\n");
1066 printf(" if present. Txf file output is only possible if the input source\n");
1067 printf(" is a pcap file.\n");
1068 printf("\n");
1069 printf("Please report bugs to <bugs@netsniff-ng.org>\n");
1070 printf("Copyright (C) 2009-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n");
1071 printf("Copyright (C) 2009-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n");
1072 printf("License: GNU GPL version 2\n");
1073 printf("This is free software: you are free to change and redistribute it.\n");
1074 printf("There is NO WARRANTY, to the extent permitted by law.\n\n");
1075 die();
1078 static void version(void)
1080 printf("\n%s %s, the packet sniffing beast\n", PROGNAME_STRING,
1081 VERSION_STRING);
1082 printf("http://www.netsniff-ng.org\n\n");
1083 printf("Please report bugs to <bugs@netsniff-ng.org>\n");
1084 printf("Copyright (C) 2009-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n");
1085 printf("Copyright (C) 2009-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n");
1086 printf("License: GNU GPL version 2\n");
1087 printf("This is free software: you are free to change and redistribute it.\n");
1088 printf("There is NO WARRANTY, to the extent permitted by law.\n\n");
1089 die();
1092 static void header(void)
1094 printf("%s%s%s\n", colorize_start(bold), PROGNAME_STRING " "
1095 VERSION_STRING, colorize_end());
1098 int main(int argc, char **argv)
1100 int c, i, j, opt_index;
1101 char *ptr;
1102 bool prio_high = false;
1103 struct mode mode;
1104 void (*enter_mode)(struct mode *mode) = NULL;
1106 check_for_root_maybe_die();
1108 fmemset(&mode, 0, sizeof(mode));
1109 mode.link_type = LINKTYPE_EN10MB;
1110 mode.print_mode = FNTTYPE_PRINT_NORM;
1111 mode.cpu = CPU_UNKNOWN;
1112 mode.packet_type = PACKET_ALL;
1113 mode.promiscuous = true;
1114 mode.randomize = false;
1115 mode.pcap = PCAP_OPS_SG;
1116 mode.dump_interval = DUMP_INTERVAL;
1118 while ((c = getopt_long(argc, argv, short_options, long_options,
1119 &opt_index)) != EOF) {
1120 switch (c) {
1121 case 'd':
1122 case 'i':
1123 mode.device_in = xstrdup(optarg);
1124 break;
1125 case 'o':
1126 mode.device_out = xstrdup(optarg);
1127 break;
1128 case 'R':
1129 mode.link_type = LINKTYPE_IEEE802_11;
1130 mode.rfraw = 1;
1131 break;
1132 case 'r':
1133 mode.randomize = true;
1134 break;
1135 case 'J':
1136 mode.jumbo_support = 1;
1137 break;
1138 case 'f':
1139 mode.filter = xstrdup(optarg);
1140 break;
1141 case 'M':
1142 mode.promiscuous = false;
1143 break;
1144 case 't':
1145 if (!strncmp(optarg, "host", strlen("host")))
1146 mode.packet_type = PACKET_HOST;
1147 else if (!strncmp(optarg, "broadcast", strlen("broadcast")))
1148 mode.packet_type = PACKET_BROADCAST;
1149 else if (!strncmp(optarg, "multicast", strlen("multicast")))
1150 mode.packet_type = PACKET_MULTICAST;
1151 else if (!strncmp(optarg, "others", strlen("others")))
1152 mode.packet_type = PACKET_OTHERHOST;
1153 else if (!strncmp(optarg, "outgoing", strlen("outgoing")))
1154 mode.packet_type = PACKET_OUTGOING;
1155 else
1156 mode.packet_type = PACKET_ALL;
1157 break;
1158 case 'S':
1159 ptr = optarg;
1160 mode.reserve_size = 0;
1162 for (j = i = strlen(optarg); i > 0; --i) {
1163 if (!isdigit(optarg[j - i]))
1164 break;
1165 ptr++;
1168 if (!strncmp(ptr, "KB", strlen("KB")))
1169 mode.reserve_size = 1 << 10;
1170 else if (!strncmp(ptr, "MB", strlen("MB")))
1171 mode.reserve_size = 1 << 20;
1172 else if (!strncmp(ptr, "GB", strlen("GB")))
1173 mode.reserve_size = 1 << 30;
1174 else
1175 panic("Syntax error in ring size param!\n");
1177 *ptr = 0;
1178 mode.reserve_size *= atoi(optarg);
1179 break;
1180 case 'b':
1181 set_cpu_affinity(optarg, 0);
1182 if (mode.cpu != CPU_NOTOUCH)
1183 mode.cpu = atoi(optarg);
1184 break;
1185 case 'B':
1186 set_cpu_affinity(optarg, 1);
1187 break;
1188 case 'H':
1189 prio_high = true;
1190 break;
1191 case 'c':
1192 mode.pcap = PCAP_OPS_RW;
1193 break;
1194 case 'm':
1195 mode.pcap = PCAP_OPS_MMAP;
1196 break;
1197 case 'Q':
1198 mode.cpu = CPU_NOTOUCH;
1199 break;
1200 case 's':
1201 mode.print_mode = FNTTYPE_PRINT_NONE;
1202 break;
1203 case 'q':
1204 mode.print_mode = FNTTYPE_PRINT_LESS;
1205 break;
1206 case 'X':
1207 mode.print_mode = (mode.print_mode == FNTTYPE_PRINT_ASCII) ?
1208 FNTTYPE_PRINT_HEX_ASCII : FNTTYPE_PRINT_HEX;
1209 break;
1210 case 'l':
1211 mode.print_mode = (mode.print_mode == FNTTYPE_PRINT_HEX) ?
1212 FNTTYPE_PRINT_HEX_ASCII : FNTTYPE_PRINT_ASCII;
1213 break;
1214 case 'k':
1215 mode.kpull = (unsigned long) atol(optarg);
1216 break;
1217 case 'n':
1218 frame_cnt_max = (unsigned long) atol(optarg);
1219 break;
1220 case 'F':
1221 mode.dump_interval = (unsigned long) atol(optarg);
1222 break;
1223 case 'v':
1224 version();
1225 break;
1226 case 'h':
1227 help();
1228 break;
1229 case '?':
1230 switch (optopt) {
1231 case 'd':
1232 case 'i':
1233 case 'o':
1234 case 'f':
1235 case 't':
1236 case 'F':
1237 case 'n':
1238 case 'S':
1239 case 'b':
1240 case 'k':
1241 case 'B':
1242 case 'e':
1243 panic("Option -%c requires an argument!\n",
1244 optopt);
1245 default:
1246 if (isprint(optopt))
1247 whine("Unknown option character "
1248 "`0x%X\'!\n", optopt);
1249 die();
1251 default:
1252 break;
1256 if (!mode.device_in)
1257 mode.device_in = xstrdup("any");
1259 register_signal(SIGINT, signal_handler);
1260 register_signal(SIGHUP, signal_handler);
1262 init_pcap(mode.jumbo_support);
1263 tprintf_init();
1264 header();
1266 if (prio_high == true) {
1267 set_proc_prio(get_default_proc_prio());
1268 set_sched_status(get_default_sched_policy(),
1269 get_default_sched_prio());
1272 if (mode.device_in && (device_mtu(mode.device_in) ||
1273 !strncmp("any", mode.device_in, strlen(mode.device_in)))) {
1274 if (!mode.device_out) {
1275 mode.dump = 0;
1276 enter_mode = enter_mode_rx_only_or_dump;
1277 } else if (device_mtu(mode.device_out)) {
1278 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1279 enter_mode = enter_mode_rx_to_tx;
1280 } else {
1281 mode.dump = 1;
1282 register_signal_f(SIGALRM, timer_next_dump, SA_SIGINFO);
1283 enter_mode = enter_mode_rx_only_or_dump;
1285 } else {
1286 if (mode.device_out && device_mtu(mode.device_out)) {
1287 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1288 enter_mode = enter_mode_pcap_to_tx;
1289 } else {
1290 enter_mode = enter_mode_read_pcap;
1294 if (!enter_mode)
1295 panic("Selection not supported!\n");
1296 enter_mode(&mode);
1298 tprintf_cleanup();
1299 cleanup_pcap();
1301 if (mode.device_in)
1302 xfree(mode.device_in);
1303 if (mode.device_out)
1304 xfree(mode.device_out);
1305 if (mode.device_trans)
1306 xfree(mode.device_trans);
1308 return 0;