proto_icmpv6.h: add neighbor discovery options
[netsniff-ng.git] / src / netsniff-ng.c
blob358c75ddabb040bc701b924144a8ef5baf262571
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 "xsys.h"
217 #include "built_in.h"
218 #include "pcap.h"
219 #include "bpf.h"
220 #include "xio.h"
221 #include "xstring.h"
222 #include "die.h"
223 #include "tprintf.h"
224 #include "dissector.h"
225 #include "xmalloc.h"
226 #include "mtrand.h"
228 #define CPU_UNKNOWN -1
229 #define CPU_NOTOUCH -2
230 #define PACKET_ALL -1
231 #define DUMP_INTERVAL 60
233 struct mode {
234 char *device_in;
235 char *device_out;
236 char *filter;
237 int cpu;
238 int dump;
239 int link_type;
240 int print_mode;
241 unsigned int reserve_size;
242 int packet_type;
243 bool randomize;
244 bool promiscuous;
245 enum pcap_ops_groups pcap;
246 unsigned long kpull;
247 int jumbo_support;
248 int dump_dir;
249 unsigned long dump_interval;
252 struct tx_stats {
253 unsigned long tx_bytes;
254 unsigned long tx_packets;
257 volatile sig_atomic_t sigint = 0;
259 static int tx_sock;
260 static unsigned long frame_cnt_max = 0;
261 static unsigned long interval = TX_KERNEL_PULL_INT;
262 static struct itimerval itimer;
263 static volatile bool next_dump = false;
265 static const char *short_options = "d:i:o:rf:MJt:S:k:n:b:B:HQmcsqXlvhF:";
267 static struct option long_options[] = {
268 {"dev", required_argument, 0, 'd'},
269 {"in", required_argument, 0, 'i'},
270 {"out", required_argument, 0, 'o'},
271 {"rand", no_argument, 0, 'r'},
272 {"mmap", no_argument, 0, 'm'},
273 {"clrw", no_argument, 0, 'c'},
274 {"jumbo-support", no_argument, 0, 'J'},
275 {"filter", required_argument, 0, 'f'},
276 {"no-promisc", no_argument, 0, 'M'},
277 {"num", required_argument, 0, 'n'},
278 {"type", required_argument, 0, 't'},
279 {"interval", required_argument, 0, 'F'},
280 {"ring-size", required_argument, 0, 'S'},
281 {"kernel-pull", required_argument, 0, 'k'},
282 {"bind-cpu", required_argument, 0, 'b'},
283 {"unbind-cpu", required_argument, 0, 'B'},
284 {"prio-high", no_argument, 0, 'H'},
285 {"notouch-irq", no_argument, 0, 'Q'},
286 {"silent", no_argument, 0, 's'},
287 {"less", no_argument, 0, 'q'},
288 {"hex", no_argument, 0, 'X'},
289 {"ascii", no_argument, 0, 'l'},
290 {"version", no_argument, 0, 'v'},
291 {"help", no_argument, 0, 'h'},
292 {0, 0, 0, 0}
295 static void signal_handler(int number)
297 switch (number) {
298 case SIGINT:
299 sigint = 1;
300 break;
301 case SIGHUP:
302 break;
303 default:
304 break;
308 static void timer_elapsed(int number)
310 itimer.it_interval.tv_sec = 0;
311 itimer.it_interval.tv_usec = interval;
312 itimer.it_value.tv_sec = 0;
313 itimer.it_value.tv_usec = interval;
315 pull_and_flush_tx_ring(tx_sock);
316 setitimer(ITIMER_REAL, &itimer, NULL);
319 static void timer_next_dump(int number)
321 itimer.it_interval.tv_sec = interval;
322 itimer.it_interval.tv_usec = 0;
323 itimer.it_value.tv_sec = interval;
324 itimer.it_value.tv_usec = 0;
326 next_dump = true;
327 setitimer(ITIMER_REAL, &itimer, NULL);
330 static void enter_mode_pcap_to_tx(struct mode *mode)
332 int irq, ifindex, fd = 0, ret;
333 unsigned int size, it = 0;
334 struct ring tx_ring;
335 struct frame_map *hdr;
336 struct sock_fprog bpf_ops;
337 struct tx_stats stats;
338 uint8_t *out = NULL;
339 unsigned long trunced = 0;
341 if (!device_up_and_running(mode->device_out))
342 panic("Device not up and running!\n");
344 tx_sock = pf_socket();
346 if (!pcap_ops[mode->pcap])
347 panic("pcap group not supported!\n");
348 fd = open_or_die(mode->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
349 ret = pcap_ops[mode->pcap]->pull_file_header(fd);
350 if (ret)
351 panic("error reading pcap header!\n");
352 if (pcap_ops[mode->pcap]->prepare_reading_pcap) {
353 ret = pcap_ops[mode->pcap]->prepare_reading_pcap(fd);
354 if (ret)
355 panic("error prepare reading pcap!\n");
358 fmemset(&tx_ring, 0, sizeof(tx_ring));
359 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
360 fmemset(&stats, 0, sizeof(stats));
362 ifindex = device_ifindex(mode->device_out);
363 size = ring_size(mode->device_out, mode->reserve_size);
365 bpf_parse_rules(mode->filter, &bpf_ops);
367 set_packet_loss_discard(tx_sock);
368 setup_tx_ring_layout(tx_sock, &tx_ring, size, mode->jumbo_support);
369 create_tx_ring(tx_sock, &tx_ring);
370 mmap_tx_ring(tx_sock, &tx_ring);
371 alloc_tx_ring_frames(&tx_ring);
372 bind_tx_ring(tx_sock, &tx_ring, ifindex);
374 dissector_init_all(mode->print_mode);
376 if (mode->cpu >= 0 && ifindex > 0) {
377 irq = device_irq_number(mode->device_out);
378 device_bind_irq_to_cpu(mode->cpu, irq);
379 printf("IRQ: %s:%d > CPU%d\n", mode->device_out, irq,
380 mode->cpu);
383 if (mode->kpull)
384 interval = mode->kpull;
386 itimer.it_interval.tv_sec = 0;
387 itimer.it_interval.tv_usec = interval;
388 itimer.it_value.tv_sec = 0;
389 itimer.it_value.tv_usec = interval;
390 setitimer(ITIMER_REAL, &itimer, NULL);
392 printf("BPF:\n");
393 bpf_dump_all(&bpf_ops);
394 printf("MD: TX %luus %s ", interval, pcap_ops[mode->pcap]->name);
395 ioprio_print();
396 printf("\n");
398 while (likely(sigint == 0)) {
399 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
400 struct pcap_pkthdr phdr;
401 hdr = tx_ring.frames[it].iov_base;
402 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
403 * sizeof(struct sockaddr_ll); */
404 out = ((uint8_t *) hdr) + TPACKET_HDRLEN -
405 sizeof(struct sockaddr_ll);
407 do {
408 memset(&phdr, 0, sizeof(phdr));
409 ret = pcap_ops[mode->pcap]->read_pcap_pkt(fd, &phdr,
410 out, ring_frame_size(&tx_ring));
411 if (unlikely(ret <= 0))
412 goto out;
413 if (ring_frame_size(&tx_ring) < phdr.len) {
414 phdr.len = ring_frame_size(&tx_ring);
415 trunced++;
417 } while (mode->filter && !bpf_run_filter(&bpf_ops, out, phdr.len));
418 pcap_pkthdr_to_tpacket_hdr(&phdr, &hdr->tp_h);
420 stats.tx_bytes += hdr->tp_h.tp_len;;
421 stats.tx_packets++;
423 show_frame_hdr(hdr, mode->print_mode, RING_MODE_EGRESS);
424 dissector_entry_point(out, hdr->tp_h.tp_snaplen,
425 mode->link_type, mode->print_mode);
427 kernel_may_pull_from_tx(&hdr->tp_h);
428 next_slot_prewr(&it, &tx_ring);
430 if (unlikely(sigint == 1))
431 break;
432 if (frame_cnt_max != 0 &&
433 stats.tx_packets >= frame_cnt_max) {
434 sigint = 1;
435 break;
439 out:
440 fflush(stdout);
441 printf("\n");
442 printf("\r%12lu frames outgoing\n", stats.tx_packets);
443 printf("\r%12lu frames truncated (larger than frame)\n", trunced);
444 printf("\r%12lu bytes outgoing\n", stats.tx_bytes);
446 dissector_cleanup_all();
447 destroy_tx_ring(tx_sock, &tx_ring);
449 close(tx_sock);
450 if (pcap_ops[mode->pcap]->prepare_close_pcap)
451 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_READ);
452 close(fd);
455 static void enter_mode_rx_to_tx(struct mode *mode)
457 int rx_sock, ifindex_in, ifindex_out;
458 unsigned int size_in, size_out, it_in = 0, it_out = 0;
459 unsigned long fcnt = 0;
460 uint8_t *in, *out;
461 short ifflags = 0;
462 struct frame_map *hdr_in, *hdr_out;
463 struct ring tx_ring;
464 struct ring rx_ring;
465 struct pollfd rx_poll;
466 struct sock_fprog bpf_ops;
468 if (!strncmp(mode->device_in, mode->device_out,
469 strlen(mode->device_in)))
470 panic("Ingress/egress devices must be different!\n");
471 if (!device_up_and_running(mode->device_out))
472 panic("Egress device not up and running!\n");
473 if (!device_up_and_running(mode->device_in))
474 panic("Ingress device not up and running!\n");
476 rx_sock = pf_socket();
477 tx_sock = pf_socket();
479 fmemset(&tx_ring, 0, sizeof(tx_ring));
480 fmemset(&rx_ring, 0, sizeof(rx_ring));
481 fmemset(&rx_poll, 0, sizeof(rx_poll));
482 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
484 ifindex_in = device_ifindex(mode->device_in);
485 size_in = ring_size(mode->device_in, mode->reserve_size);
487 ifindex_out = device_ifindex(mode->device_out);
488 size_out = ring_size(mode->device_out, mode->reserve_size);
490 enable_kernel_bpf_jit_compiler();
491 bpf_parse_rules(mode->filter, &bpf_ops);
492 bpf_attach_to_sock(rx_sock, &bpf_ops);
494 setup_rx_ring_layout(rx_sock, &rx_ring, size_in, mode->jumbo_support);
495 create_rx_ring(rx_sock, &rx_ring);
496 mmap_rx_ring(rx_sock, &rx_ring);
497 alloc_rx_ring_frames(&rx_ring);
498 bind_rx_ring(rx_sock, &rx_ring, ifindex_in);
499 prepare_polling(rx_sock, &rx_poll);
501 set_packet_loss_discard(tx_sock);
502 setup_tx_ring_layout(tx_sock, &tx_ring, size_out, mode->jumbo_support);
503 create_tx_ring(tx_sock, &tx_ring);
504 mmap_tx_ring(tx_sock, &tx_ring);
505 alloc_tx_ring_frames(&tx_ring);
506 bind_tx_ring(tx_sock, &tx_ring, ifindex_out);
508 mt_init_by_seed_time();
509 dissector_init_all(mode->print_mode);
511 if (mode->promiscuous == true) {
512 ifflags = enter_promiscuous_mode(mode->device_in);
513 printf("PROMISC\n");
516 if (mode->kpull)
517 interval = mode->kpull;
519 itimer.it_interval.tv_sec = 0;
520 itimer.it_interval.tv_usec = interval;
521 itimer.it_value.tv_sec = 0;
522 itimer.it_value.tv_usec = interval;
523 setitimer(ITIMER_REAL, &itimer, NULL);
525 printf("BPF:\n");
526 bpf_dump_all(&bpf_ops);
527 printf("MD: RXTX %luus\n\n", interval);
528 printf("Running! Hang up with ^C!\n\n");
530 while (likely(sigint == 0)) {
531 while (user_may_pull_from_rx(rx_ring.frames[it_in].iov_base)) {
532 hdr_in = rx_ring.frames[it_in].iov_base;
533 in = ((uint8_t *) hdr_in) + hdr_in->tp_h.tp_mac;
534 fcnt++;
535 if (mode->packet_type != PACKET_ALL)
536 if (mode->packet_type != hdr_in->s_ll.sll_pkttype)
537 goto next;
539 hdr_out = tx_ring.frames[it_out].iov_base;
540 out = ((uint8_t *) hdr_out) + TPACKET_HDRLEN -
541 sizeof(struct sockaddr_ll);
543 for (; !user_may_pull_from_tx(tx_ring.frames[it_out].iov_base) &&
544 likely(!sigint);) {
545 if (mode->randomize)
546 next_rnd_slot(&it_out, &tx_ring);
547 else
548 next_slot(&it_out, &tx_ring);
549 hdr_out = tx_ring.frames[it_out].iov_base;
550 out = ((uint8_t *) hdr_out) + TPACKET_HDRLEN -
551 sizeof(struct sockaddr_ll);
554 tpacket_hdr_clone(&hdr_out->tp_h, &hdr_in->tp_h);
555 fmemcpy(out, in, hdr_in->tp_h.tp_len);
557 kernel_may_pull_from_tx(&hdr_out->tp_h);
558 if (mode->randomize)
559 next_rnd_slot(&it_out, &tx_ring);
560 else
561 next_slot(&it_out, &tx_ring);
563 show_frame_hdr(hdr_in, mode->print_mode, RING_MODE_INGRESS);
564 dissector_entry_point(in, hdr_in->tp_h.tp_snaplen,
565 mode->link_type, mode->print_mode);
567 if (frame_cnt_max != 0 && fcnt >= frame_cnt_max) {
568 sigint = 1;
569 break;
571 next:
572 kernel_may_pull_from_rx(&hdr_in->tp_h);
573 next_slot(&it_in, &rx_ring);
575 if (unlikely(sigint == 1))
576 goto out;
579 poll(&rx_poll, 1, -1);
580 poll_error_maybe_die(rx_sock, &rx_poll);
582 out:
583 sock_print_net_stats(rx_sock, 0);
585 dissector_cleanup_all();
586 destroy_tx_ring(tx_sock, &tx_ring);
587 destroy_rx_ring(rx_sock, &rx_ring);
589 if (mode->promiscuous == true)
590 leave_promiscuous_mode(mode->device_in, ifflags);
592 close(tx_sock);
593 close(rx_sock);
596 static void enter_mode_read_pcap(struct mode *mode)
598 int ret, fd, fdo = 0;
599 struct pcap_pkthdr phdr;
600 struct sock_fprog bpf_ops;
601 struct tx_stats stats;
602 struct frame_map fm;
603 uint8_t *out;
604 size_t out_len;
605 unsigned long trunced = 0;
607 if (!pcap_ops[mode->pcap])
608 panic("pcap group not supported!\n");
609 fd = open_or_die(mode->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
610 ret = pcap_ops[mode->pcap]->pull_file_header(fd);
611 if (ret)
612 panic("error reading pcap header!\n");
613 if (pcap_ops[mode->pcap]->prepare_reading_pcap) {
614 ret = pcap_ops[mode->pcap]->prepare_reading_pcap(fd);
615 if (ret)
616 panic("error prepare reading pcap!\n");
619 fmemset(&fm, 0, sizeof(fm));
620 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
621 fmemset(&stats, 0, sizeof(stats));
623 bpf_parse_rules(mode->filter, &bpf_ops);
624 dissector_init_all(mode->print_mode);
626 out_len = device_mtu("eth0");
627 if (out_len == 0)
628 out_len = device_mtu("lo");
629 out = xmalloc_aligned(out_len, CO_CACHE_LINE_SIZE);
631 printf("BPF:\n");
632 bpf_dump_all(&bpf_ops);
633 printf("MD: RD %s ", pcap_ops[mode->pcap]->name);
634 ioprio_print();
635 printf("\n");
637 if (mode->device_out) {
638 fdo = open_or_die_m(mode->device_out, O_RDWR | O_CREAT |
639 O_TRUNC | O_LARGEFILE, S_IRUSR | S_IWUSR);
642 while (likely(sigint == 0)) {
643 do {
644 memset(&phdr, 0, sizeof(phdr));
645 ret = pcap_ops[mode->pcap]->read_pcap_pkt(fd, &phdr,
646 out, out_len);
647 if (unlikely(ret < 0))
648 goto out;
649 if (unlikely(phdr.len == 0)) {
650 trunced++;
651 continue;
653 if (unlikely(phdr.len > out_len)) {
654 phdr.len = out_len;
655 trunced++;
657 } while (mode->filter &&
658 !bpf_run_filter(&bpf_ops, out, phdr.len));
660 pcap_pkthdr_to_tpacket_hdr(&phdr, &fm.tp_h);
662 stats.tx_bytes += fm.tp_h.tp_len;
663 stats.tx_packets++;
665 show_frame_hdr(&fm, mode->print_mode, RING_MODE_EGRESS);
666 dissector_entry_point(out, fm.tp_h.tp_snaplen,
667 mode->link_type, mode->print_mode);
669 if (mode->device_out) {
670 int i = 0;
671 char bout[80];
672 slprintf(bout, sizeof(bout), "$P%u {\n ", stats.tx_packets);
673 write_or_die(fdo, bout, strlen(bout));
675 while (i < fm.tp_h.tp_snaplen) {
676 slprintf(bout, sizeof(bout), "0x%02x, ", out[i]);
677 write_or_die(fdo, bout, strlen(bout));
678 i++;
679 if (i % 10 == 0) {
680 slprintf(bout, sizeof(bout), "\n", out[i]);
681 write_or_die(fdo, bout, strlen(bout));
682 if (i < fm.tp_h.tp_snaplen) {
683 slprintf(bout, sizeof(bout), " ", out[i]);
684 write_or_die(fdo, bout, strlen(bout));
688 if (i % 10 != 0) {
689 slprintf(bout, sizeof(bout), "\n");
690 write_or_die(fdo, bout, strlen(bout));
692 slprintf(bout, sizeof(bout), "}\n\n");
693 write_or_die(fdo, bout, strlen(bout));
696 if (frame_cnt_max != 0 &&
697 stats.tx_packets >= frame_cnt_max) {
698 sigint = 1;
699 break;
702 out:
703 fflush(stdout);
704 printf("\n");
705 printf("\r%12lu frames outgoing\n", stats.tx_packets);
706 printf("\r%12lu frames truncated (larger than mtu)\n", trunced);
707 printf("\r%12lu bytes outgoing\n", stats.tx_bytes);
709 xfree(out);
710 dissector_cleanup_all();
711 if (pcap_ops[mode->pcap]->prepare_close_pcap)
712 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_READ);
713 close(fd);
715 if (mode->device_out)
716 close(fdo);
719 static void finish_multi_pcap_file(struct mode *mode, int fd)
721 pcap_ops[mode->pcap]->fsync_pcap(fd);
722 if (pcap_ops[mode->pcap]->prepare_close_pcap)
723 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_WRITE);
724 close(fd);
726 fmemset(&itimer, 0, sizeof(itimer));
727 setitimer(ITIMER_REAL, &itimer, NULL);
730 static int next_multi_pcap_file(struct mode *mode, int fd)
732 int ret;
733 char tmp[512];
735 pcap_ops[mode->pcap]->fsync_pcap(fd);
736 if (pcap_ops[mode->pcap]->prepare_close_pcap)
737 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_WRITE);
738 close(fd);
740 slprintf(tmp, sizeof(tmp), "%s/%lu.pcap", mode->device_out, time(0));
742 fd = open_or_die_m(tmp, O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE,
743 S_IRUSR | S_IWUSR);
744 ret = pcap_ops[mode->pcap]->push_file_header(fd);
745 if (ret)
746 panic("error writing pcap header!\n");
747 if (pcap_ops[mode->pcap]->prepare_writing_pcap) {
748 ret = pcap_ops[mode->pcap]->prepare_writing_pcap(fd);
749 if (ret)
750 panic("error prepare writing pcap!\n");
753 return fd;
756 static int begin_multi_pcap_file(struct mode *mode)
758 int fd, ret;
759 char tmp[512];
761 if (!pcap_ops[mode->pcap])
762 panic("pcap group not supported!\n");
763 if (mode->device_out[strlen(mode->device_out) - 1] == '/')
764 mode->device_out[strlen(mode->device_out) - 1] = 0;
766 slprintf(tmp, sizeof(tmp), "%s/%lu.pcap", mode->device_out, time(0));
768 fd = open_or_die_m(tmp, O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE,
769 S_IRUSR | S_IWUSR);
770 ret = pcap_ops[mode->pcap]->push_file_header(fd);
771 if (ret)
772 panic("error writing pcap header!\n");
773 if (pcap_ops[mode->pcap]->prepare_writing_pcap) {
774 ret = pcap_ops[mode->pcap]->prepare_writing_pcap(fd);
775 if (ret)
776 panic("error prepare writing pcap!\n");
779 interval = mode->dump_interval;
780 itimer.it_interval.tv_sec = interval;
781 itimer.it_interval.tv_usec = 0;
782 itimer.it_value.tv_sec = interval;
783 itimer.it_value.tv_usec = 0;
784 setitimer(ITIMER_REAL, &itimer, NULL);
786 return fd;
789 static void finish_single_pcap_file(struct mode *mode, int fd)
791 pcap_ops[mode->pcap]->fsync_pcap(fd);
792 if (pcap_ops[mode->pcap]->prepare_close_pcap)
793 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_WRITE);
794 close(fd);
797 static int begin_single_pcap_file(struct mode *mode)
799 int fd, ret;
801 if (!pcap_ops[mode->pcap])
802 panic("pcap group not supported!\n");
803 fd = open_or_die_m(mode->device_out,
804 O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE,
805 S_IRUSR | S_IWUSR);
806 ret = pcap_ops[mode->pcap]->push_file_header(fd);
807 if (ret)
808 panic("error writing pcap header!\n");
809 if (pcap_ops[mode->pcap]->prepare_writing_pcap) {
810 ret = pcap_ops[mode->pcap]->prepare_writing_pcap(fd);
811 if (ret)
812 panic("error prepare writing pcap!\n");
815 return fd;
818 static void enter_mode_rx_only_or_dump(struct mode *mode)
820 int sock, irq, ifindex, fd = 0, ret;
821 unsigned int size, it = 0;
822 unsigned long fcnt = 0, skipped = 0;
823 short ifflags = 0;
824 uint8_t *packet;
825 struct ring rx_ring;
826 struct pollfd rx_poll;
827 struct frame_map *hdr;
828 struct sock_fprog bpf_ops;
830 if (!device_up_and_running(mode->device_in))
831 panic("Device not up and running!\n");
833 sock = pf_socket();
835 if (mode->dump) {
836 struct stat tmp;
837 fmemset(&tmp, 0, sizeof(tmp));
838 ret = stat(mode->device_out, &tmp);
839 if (ret < 0) {
840 mode->dump_dir = 0;
841 goto try_file;
843 mode->dump_dir = !!S_ISDIR(tmp.st_mode);
844 if (mode->dump_dir) {
845 fd = begin_multi_pcap_file(mode);
846 } else {
847 try_file:
848 fd = begin_single_pcap_file(mode);
852 fmemset(&rx_ring, 0, sizeof(rx_ring));
853 fmemset(&rx_poll, 0, sizeof(rx_poll));
854 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
856 ifindex = device_ifindex(mode->device_in);
857 size = ring_size(mode->device_in, mode->reserve_size);
859 enable_kernel_bpf_jit_compiler();
860 bpf_parse_rules(mode->filter, &bpf_ops);
861 bpf_attach_to_sock(sock, &bpf_ops);
863 setup_rx_ring_layout(sock, &rx_ring, size, mode->jumbo_support);
864 create_rx_ring(sock, &rx_ring);
865 mmap_rx_ring(sock, &rx_ring);
866 alloc_rx_ring_frames(&rx_ring);
867 bind_rx_ring(sock, &rx_ring, ifindex);
869 prepare_polling(sock, &rx_poll);
870 dissector_init_all(mode->print_mode);
872 if (mode->cpu >= 0 && ifindex > 0) {
873 irq = device_irq_number(mode->device_in);
874 device_bind_irq_to_cpu(mode->cpu, irq);
875 printf("IRQ: %s:%d > CPU%d\n", mode->device_in, irq,
876 mode->cpu);
879 if (mode->promiscuous == true) {
880 ifflags = enter_promiscuous_mode(mode->device_in);
881 printf("PROMISC\n");
884 printf("BPF:\n");
885 bpf_dump_all(&bpf_ops);
886 printf("MD: RX %s ", mode->dump ? pcap_ops[mode->pcap]->name : "");
887 ioprio_print();
888 printf("\n");
890 while (likely(sigint == 0)) {
891 while (user_may_pull_from_rx(rx_ring.frames[it].iov_base)) {
892 hdr = rx_ring.frames[it].iov_base;
893 packet = ((uint8_t *) hdr) + hdr->tp_h.tp_mac;
894 fcnt++;
896 if (mode->packet_type != PACKET_ALL)
897 if (mode->packet_type != hdr->s_ll.sll_pkttype)
898 goto next;
899 if (unlikely(ring_frame_size(&rx_ring) <
900 hdr->tp_h.tp_snaplen)) {
901 skipped++;
902 goto next;
904 if (mode->dump) {
905 struct pcap_pkthdr phdr;
906 tpacket_hdr_to_pcap_pkthdr(&hdr->tp_h, &phdr);
907 ret = pcap_ops[mode->pcap]->write_pcap_pkt(fd, &phdr,
908 packet, phdr.len);
909 if (unlikely(ret != sizeof(phdr) + phdr.len))
910 panic("Write error to pcap!\n");
913 show_frame_hdr(hdr, mode->print_mode, RING_MODE_INGRESS);
914 dissector_entry_point(packet, hdr->tp_h.tp_snaplen,
915 mode->link_type, mode->print_mode);
917 if (frame_cnt_max != 0 && fcnt >= frame_cnt_max) {
918 sigint = 1;
919 break;
921 next:
922 kernel_may_pull_from_rx(&hdr->tp_h);
923 next_slot_prerd(&it, &rx_ring);
925 if (unlikely(sigint == 1))
926 break;
927 if (mode->dump && next_dump) {
928 struct tpacket_stats kstats;
929 socklen_t slen = sizeof(kstats);
930 fmemset(&kstats, 0, sizeof(kstats));
931 getsockopt(sock, SOL_PACKET, PACKET_STATISTICS,
932 &kstats, &slen);
933 fd = next_multi_pcap_file(mode, fd);
934 next_dump = false;
935 if (mode->print_mode == FNTTYPE_PRINT_NONE) {
936 printf(".(+%lu/-%lu)",
937 1UL * kstats.tp_packets -
938 kstats.tp_drops -
939 skipped, 1UL * kstats.tp_drops +
940 skipped);
941 fflush(stdout);
946 poll(&rx_poll, 1, -1);
947 poll_error_maybe_die(sock, &rx_poll);
950 if (!(mode->dump_dir && mode->print_mode == FNTTYPE_PRINT_NONE))
951 sock_print_net_stats(sock, skipped);
952 else {
953 printf("\n\n");
954 fflush(stdout);
956 dissector_cleanup_all();
957 destroy_rx_ring(sock, &rx_ring);
958 if (mode->promiscuous == true)
959 leave_promiscuous_mode(mode->device_in, ifflags);
960 close(sock);
961 if (mode->dump) {
962 if (mode->dump_dir)
963 finish_multi_pcap_file(mode, fd);
964 else
965 finish_single_pcap_file(mode, fd);
969 static void help(void)
971 printf("\n%s %s, the packet sniffing beast\n", PROGNAME_STRING,
972 VERSION_STRING);
973 printf("http://www.netsniff-ng.org\n\n");
974 printf("Usage: netsniff-ng [options]\n");
975 printf("Options:\n");
976 printf(" -i|-d|--dev|--in <dev|pcap> Input source as netdev or pcap\n");
977 printf(" -o|--out <dev|pcap|dir|txf> Output sink as netdev, pcap, directory, txf file\n");
978 printf(" -f|--filter <bpf-file> Use BPF filter file from bpfc\n");
979 printf(" -t|--type <type> Only handle packets of defined type:\n");
980 printf(" host|broadcast|multicast|others|outgoing\n");
981 printf(" -F|--interval <uint> Dump interval in sec if -o is a directory where\n");
982 printf(" pcap files should be stored (default: 60)\n");
983 printf(" -J|--jumbo-support Support for 64KB Super Jumbo Frames\n");
984 printf(" Default RX/TX slot: 2048Byte\n");
985 printf(" -n|--num <uint> Number of packets until exit\n");
986 printf(" `-- 0 Loop until interrupted (default)\n");
987 printf(" `- n Send n packets and done\n");
988 printf("Options for printing:\n");
989 printf(" -s|--silent Do not print captured packets\n");
990 printf(" -q|--less Print less-verbose packet information\n");
991 printf(" -X|--hex Print packet data in hex format\n");
992 printf(" -l|--ascii Print human-readable packet data\n");
993 printf("Options, advanced:\n");
994 printf(" -r|--rand Randomize packet forwarding order\n");
995 printf(" -M|--no-promisc No promiscuous mode for netdev\n");
996 printf(" -m|--mmap Mmap pcap file i.e., for replaying\n");
997 printf(" Default: scatter-gather I/O\n");
998 printf(" -c|--clrw Use slower read(2)/write(2) I/O\n");
999 printf(" -S|--ring-size <size> Manually set ring size to <size>:\n");
1000 printf(" mmap space in KB/MB/GB, e.g. \'10MB\'\n");
1001 printf(" -k|--kernel-pull <uint> Kernel pull from user interval in us\n");
1002 printf(" Default is 10us where the TX_RING\n");
1003 printf(" is populated with payload from uspace\n");
1004 printf(" -b|--bind-cpu <cpu> Bind to specific CPU (or CPU-range)\n");
1005 printf(" -B|--unbind-cpu <cpu> Forbid to use specific CPU (or CPU-range)\n");
1006 printf(" -H|--prio-high Make this high priority process\n");
1007 printf(" -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n");
1008 printf(" -v|--version Show version\n");
1009 printf(" -h|--help Guess what?!\n");
1010 printf("\n");
1011 printf("Examples:\n");
1012 printf(" netsniff-ng --in eth0 --out dump.pcap --silent --bind-cpu 0\n");
1013 printf(" netsniff-ng --in dump.pcap --mmap --out eth0 --silent --bind-cpu 0\n");
1014 printf(" netsniff-ng --in dump.pcap --out dump.txf --silent --bind-cpu 0\n");
1015 printf(" netsniff-ng --in eth0 --out eth1 --silent --bind-cpu 0 --type host\n");
1016 printf(" netsniff-ng --in eth1 --out /opt/probe1/ -s -m -J --interval 30 -b 0\n");
1017 printf(" netsniff-ng --in any --filter http.bpf --jumbo-support --ascii\n");
1018 printf("\n");
1019 printf("Note:\n");
1020 printf(" This tool is targeted for network developers! You should\n");
1021 printf(" be aware of what you are doing and what these options above\n");
1022 printf(" mean! Use netsniff-ng's bpfc compiler for generating filter files.\n");
1023 printf(" Further, netsniff-ng automatically enables the kernel BPF JIT\n");
1024 printf(" if present. Txf file output is only possible if the input source\n");
1025 printf(" is a pcap file.\n");
1026 printf("\n");
1027 printf("Please report bugs to <bugs@netsniff-ng.org>\n");
1028 printf("Copyright (C) 2009-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n");
1029 printf("Copyright (C) 2009-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n");
1030 printf("License: GNU GPL version 2\n");
1031 printf("This is free software: you are free to change and redistribute it.\n");
1032 printf("There is NO WARRANTY, to the extent permitted by law.\n\n");
1033 die();
1036 static void version(void)
1038 printf("\n%s %s, the packet sniffing beast\n", PROGNAME_STRING,
1039 VERSION_STRING);
1040 printf("http://www.netsniff-ng.org\n\n");
1041 printf("Please report bugs to <bugs@netsniff-ng.org>\n");
1042 printf("Copyright (C) 2009-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n");
1043 printf("Copyright (C) 2009-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n");
1044 printf("License: GNU GPL version 2\n");
1045 printf("This is free software: you are free to change and redistribute it.\n");
1046 printf("There is NO WARRANTY, to the extent permitted by law.\n\n");
1047 die();
1050 static void header(void)
1052 printf("%s%s%s\n", colorize_start(bold), PROGNAME_STRING " "
1053 VERSION_STRING, colorize_end());
1056 int main(int argc, char **argv)
1058 int c, i, j, opt_index;
1059 char *ptr;
1060 bool prio_high = false;
1061 struct mode mode;
1062 void (*enter_mode)(struct mode *mode) = NULL;
1064 check_for_root_maybe_die();
1066 fmemset(&mode, 0, sizeof(mode));
1067 mode.link_type = LINKTYPE_EN10MB;
1068 mode.print_mode = FNTTYPE_PRINT_NORM;
1069 mode.cpu = CPU_UNKNOWN;
1070 mode.packet_type = PACKET_ALL;
1071 mode.promiscuous = true;
1072 mode.randomize = false;
1073 mode.pcap = PCAP_OPS_SG;
1074 mode.dump_interval = DUMP_INTERVAL;
1076 while ((c = getopt_long(argc, argv, short_options, long_options,
1077 &opt_index)) != EOF) {
1078 switch (c) {
1079 case 'd':
1080 case 'i':
1081 mode.device_in = xstrdup(optarg);
1082 break;
1083 case 'o':
1084 mode.device_out = xstrdup(optarg);
1085 break;
1086 case 'r':
1087 mode.randomize = true;
1088 break;
1089 case 'J':
1090 mode.jumbo_support = 1;
1091 break;
1092 case 'f':
1093 mode.filter = xstrdup(optarg);
1094 break;
1095 case 'M':
1096 mode.promiscuous = false;
1097 break;
1098 case 't':
1099 if (!strncmp(optarg, "host", strlen("host")))
1100 mode.packet_type = PACKET_HOST;
1101 else if (!strncmp(optarg, "broadcast", strlen("broadcast")))
1102 mode.packet_type = PACKET_BROADCAST;
1103 else if (!strncmp(optarg, "multicast", strlen("multicast")))
1104 mode.packet_type = PACKET_MULTICAST;
1105 else if (!strncmp(optarg, "others", strlen("others")))
1106 mode.packet_type = PACKET_OTHERHOST;
1107 else if (!strncmp(optarg, "outgoing", strlen("outgoing")))
1108 mode.packet_type = PACKET_OUTGOING;
1109 else
1110 mode.packet_type = PACKET_ALL;
1111 break;
1112 case 'S':
1113 ptr = optarg;
1114 mode.reserve_size = 0;
1116 for (j = i = strlen(optarg); i > 0; --i) {
1117 if (!isdigit(optarg[j - i]))
1118 break;
1119 ptr++;
1122 if (!strncmp(ptr, "KB", strlen("KB")))
1123 mode.reserve_size = 1 << 10;
1124 else if (!strncmp(ptr, "MB", strlen("MB")))
1125 mode.reserve_size = 1 << 20;
1126 else if (!strncmp(ptr, "GB", strlen("GB")))
1127 mode.reserve_size = 1 << 30;
1128 else
1129 panic("Syntax error in ring size param!\n");
1131 *ptr = 0;
1132 mode.reserve_size *= atoi(optarg);
1133 break;
1134 case 'b':
1135 set_cpu_affinity(optarg, 0);
1136 if (mode.cpu != CPU_NOTOUCH)
1137 mode.cpu = atoi(optarg);
1138 break;
1139 case 'B':
1140 set_cpu_affinity(optarg, 1);
1141 break;
1142 case 'H':
1143 prio_high = true;
1144 break;
1145 case 'c':
1146 mode.pcap = PCAP_OPS_RW;
1147 break;
1148 case 'm':
1149 mode.pcap = PCAP_OPS_MMAP;
1150 break;
1151 case 'Q':
1152 mode.cpu = CPU_NOTOUCH;
1153 break;
1154 case 's':
1155 mode.print_mode = FNTTYPE_PRINT_NONE;
1156 break;
1157 case 'q':
1158 mode.print_mode = FNTTYPE_PRINT_LESS;
1159 break;
1160 case 'X':
1161 mode.print_mode = FNTTYPE_PRINT_HEX;
1162 break;
1163 case 'l':
1164 mode.print_mode = FNTTYPE_PRINT_ASCII;
1165 break;
1166 case 'k':
1167 mode.kpull = (unsigned long) atol(optarg);
1168 break;
1169 case 'n':
1170 frame_cnt_max = (unsigned long) atol(optarg);
1171 break;
1172 case 'F':
1173 mode.dump_interval = (unsigned long) atol(optarg);
1174 break;
1175 case 'v':
1176 version();
1177 break;
1178 case 'h':
1179 help();
1180 break;
1181 case '?':
1182 switch (optopt) {
1183 case 'd':
1184 case 'i':
1185 case 'o':
1186 case 'f':
1187 case 't':
1188 case 'F':
1189 case 'n':
1190 case 'S':
1191 case 'b':
1192 case 'k':
1193 case 'B':
1194 case 'e':
1195 panic("Option -%c requires an argument!\n",
1196 optopt);
1197 default:
1198 if (isprint(optopt))
1199 whine("Unknown option character "
1200 "`0x%X\'!\n", optopt);
1201 die();
1203 default:
1204 break;
1208 if (!mode.device_in)
1209 mode.device_in = xstrdup("any");
1211 register_signal(SIGINT, signal_handler);
1212 register_signal(SIGHUP, signal_handler);
1214 init_pcap(mode.jumbo_support);
1215 tprintf_init();
1216 header();
1218 if (prio_high == true) {
1219 set_proc_prio(get_default_proc_prio());
1220 set_sched_status(get_default_sched_policy(),
1221 get_default_sched_prio());
1224 if (mode.device_in && (device_mtu(mode.device_in) ||
1225 !strncmp("any", mode.device_in, strlen(mode.device_in)))) {
1226 if (!mode.device_out) {
1227 mode.dump = 0;
1228 enter_mode = enter_mode_rx_only_or_dump;
1229 } else if (device_mtu(mode.device_out)) {
1230 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1231 enter_mode = enter_mode_rx_to_tx;
1232 } else {
1233 mode.dump = 1;
1234 register_signal_f(SIGALRM, timer_next_dump, SA_SIGINFO);
1235 enter_mode = enter_mode_rx_only_or_dump;
1237 } else {
1238 if (mode.device_out && device_mtu(mode.device_out)) {
1239 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1240 enter_mode = enter_mode_pcap_to_tx;
1241 } else {
1242 enter_mode = enter_mode_read_pcap;
1246 if (!enter_mode)
1247 panic("Selection not supported!\n");
1248 enter_mode(&mode);
1250 tprintf_cleanup();
1251 cleanup_pcap();
1253 if (mode.device_in)
1254 xfree(mode.device_in);
1255 if (mode.device_out)
1256 xfree(mode.device_out);
1257 return 0;