docs: bpfc: document number input format
[netsniff-ng.git] / src / netsniff-ng.c
blob21b864d4771a8c2b63b6dda6b3e9d349a1b347b7
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'.
23 #define _GNU_SOURCE
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <signal.h>
27 #include <getopt.h>
28 #include <ctype.h>
29 #include <time.h>
30 #include <string.h>
31 #include <sys/socket.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/time.h>
35 #include <unistd.h>
36 #include <stdbool.h>
37 #include <pthread.h>
38 #include <fcntl.h>
40 #include "ring_rx.h"
41 #include "ring_tx.h"
42 #include "mac80211.h"
43 #include "xutils.h"
44 #include "built_in.h"
45 #include "pcap.h"
46 #include "bpf.h"
47 #include "xio.h"
48 #include "die.h"
49 #include "tprintf.h"
50 #include "dissector.h"
51 #include "xmalloc.h"
52 #include "mtrand.h"
54 #define CPU_UNKNOWN -1
55 #define CPU_NOTOUCH -2
56 #define PACKET_ALL -1
57 #define DUMP_INTERVAL 60
59 struct mode {
60 char *device_in;
61 char *device_out;
62 char *device_trans;
63 char *filter;
64 int cpu;
65 int rfraw;
66 int dump;
67 uint32_t link_type;
68 int print_mode;
69 unsigned int reserve_size;
70 int packet_type;
71 bool randomize;
72 bool promiscuous;
73 enum pcap_ops_groups pcap;
74 unsigned long kpull;
75 int jumbo_support;
76 int dump_dir;
77 unsigned long dump_interval;
80 struct tx_stats {
81 unsigned long tx_bytes;
82 unsigned long tx_packets;
85 volatile sig_atomic_t sigint = 0;
87 static int tx_sock;
88 static unsigned long frame_cnt_max = 0;
89 static unsigned long interval = TX_KERNEL_PULL_INT;
90 static struct itimerval itimer;
91 static volatile bool next_dump = false;
93 static const char *short_options = "d:i:o:rf:MJt:S:k:n:b:B:HQmcsqXlvhF:RgA";
94 static const struct option long_options[] = {
95 {"dev", required_argument, NULL, 'd'},
96 {"in", required_argument, NULL, 'i'},
97 {"out", required_argument, NULL, 'o'},
98 {"filter", required_argument, NULL, 'f'},
99 {"num", required_argument, NULL, 'n'},
100 {"type", required_argument, NULL, 't'},
101 {"interval", required_argument, NULL, 'F'},
102 {"ring-size", required_argument, NULL, 'S'},
103 {"kernel-pull", required_argument, NULL, 'k'},
104 {"bind-cpu", required_argument, NULL, 'b'},
105 {"unbind-cpu", required_argument, NULL, 'B'},
106 {"rand", no_argument, NULL, 'r'},
107 {"rfraw", no_argument, NULL, 'R'},
108 {"mmap", no_argument, NULL, 'm'},
109 {"sg", no_argument, NULL, 'g'},
110 {"clrw", no_argument, NULL, 'c'},
111 {"jumbo-support", no_argument, NULL, 'J'},
112 {"no-promisc", no_argument, NULL, 'M'},
113 {"prio-high", no_argument, NULL, 'H'},
114 {"notouch-irq", no_argument, NULL, 'Q'},
115 {"silent", no_argument, NULL, 's'},
116 {"less", no_argument, NULL, 'q'},
117 {"hex", no_argument, NULL, 'X'},
118 {"ascii", no_argument, NULL, 'l'},
119 {"no-sock-mem", no_argument, NULL, 'A'},
120 {"version", no_argument, NULL, 'v'},
121 {"help", no_argument, NULL, 'h'},
122 {NULL, 0, NULL, 0}
125 static void signal_handler(int number)
127 switch (number) {
128 case SIGINT:
129 sigint = 1;
130 break;
131 case SIGHUP:
132 break;
133 default:
134 break;
138 static void timer_elapsed(int number)
140 itimer.it_interval.tv_sec = 0;
141 itimer.it_interval.tv_usec = interval;
142 itimer.it_value.tv_sec = 0;
143 itimer.it_value.tv_usec = interval;
145 pull_and_flush_tx_ring(tx_sock);
146 setitimer(ITIMER_REAL, &itimer, NULL);
149 static void timer_next_dump(int number)
151 itimer.it_interval.tv_sec = interval;
152 itimer.it_interval.tv_usec = 0;
153 itimer.it_value.tv_sec = interval;
154 itimer.it_value.tv_usec = 0;
156 next_dump = true;
157 setitimer(ITIMER_REAL, &itimer, NULL);
160 static void enter_mode_pcap_to_tx(struct mode *mode)
162 int irq, ifindex, fd = 0, ret;
163 unsigned int size, it = 0;
164 struct ring tx_ring;
165 struct frame_map *hdr;
166 struct sock_fprog bpf_ops;
167 struct tx_stats stats;
168 uint8_t *out = NULL;
169 unsigned long trunced = 0;
170 struct timeval start, end, diff;
172 if (!device_up_and_running(mode->device_out))
173 panic("Device not up and running!\n");
175 tx_sock = pf_socket();
177 if (!pcap_ops[mode->pcap])
178 panic("pcap group not supported!\n");
179 fd = open_or_die(mode->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
180 ret = pcap_ops[mode->pcap]->pull_file_header(fd, &mode->link_type);
181 if (ret)
182 panic("error reading pcap header!\n");
183 if (pcap_ops[mode->pcap]->prepare_reading_pcap) {
184 ret = pcap_ops[mode->pcap]->prepare_reading_pcap(fd);
185 if (ret)
186 panic("error prepare reading pcap!\n");
189 fmemset(&tx_ring, 0, sizeof(tx_ring));
190 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
191 fmemset(&stats, 0, sizeof(stats));
193 if (mode->rfraw) {
194 mode->device_trans = xstrdup(mode->device_out);
195 xfree(mode->device_out);
197 enter_rfmon_mac80211(mode->device_trans, &mode->device_out);
198 if (mode->link_type != LINKTYPE_IEEE802_11)
199 panic("Wrong linktype of pcap!\n");
202 ifindex = device_ifindex(mode->device_out);
203 size = ring_size(mode->device_out, mode->reserve_size);
205 bpf_parse_rules(mode->filter, &bpf_ops);
207 set_packet_loss_discard(tx_sock);
208 set_sockopt_hwtimestamp(tx_sock, mode->device_out);
209 setup_tx_ring_layout(tx_sock, &tx_ring, size, mode->jumbo_support);
210 create_tx_ring(tx_sock, &tx_ring);
211 mmap_tx_ring(tx_sock, &tx_ring);
212 alloc_tx_ring_frames(&tx_ring);
213 bind_tx_ring(tx_sock, &tx_ring, ifindex);
215 dissector_init_all(mode->print_mode);
217 if (mode->cpu >= 0 && ifindex > 0) {
218 irq = device_irq_number(mode->device_out);
219 device_bind_irq_to_cpu(mode->cpu, irq);
220 printf("IRQ: %s:%d > CPU%d\n", mode->device_out, irq,
221 mode->cpu);
224 if (mode->kpull)
225 interval = mode->kpull;
227 itimer.it_interval.tv_sec = 0;
228 itimer.it_interval.tv_usec = interval;
229 itimer.it_value.tv_sec = 0;
230 itimer.it_value.tv_usec = interval;
231 setitimer(ITIMER_REAL, &itimer, NULL);
233 printf("BPF:\n");
234 bpf_dump_all(&bpf_ops);
235 printf("MD: TX %luus %s ", interval, pcap_ops[mode->pcap]->name);
236 if (mode->rfraw)
237 printf("802.11 raw via %s ", mode->device_out);
238 #ifdef _LARGEFILE64_SOURCE
239 printf("lf64 ");
240 #endif
241 ioprio_print();
242 printf("\n");
244 gettimeofday(&start, NULL);
246 while (likely(sigint == 0)) {
247 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
248 struct pcap_pkthdr phdr;
249 hdr = tx_ring.frames[it].iov_base;
250 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
251 * sizeof(struct sockaddr_ll); */
252 out = ((uint8_t *) hdr) + TPACKET_HDRLEN -
253 sizeof(struct sockaddr_ll);
255 do {
256 memset(&phdr, 0, sizeof(phdr));
257 ret = pcap_ops[mode->pcap]->read_pcap_pkt(fd, &phdr,
258 out, ring_frame_size(&tx_ring));
259 if (unlikely(ret <= 0))
260 goto out;
261 if (ring_frame_size(&tx_ring) < phdr.len) {
262 phdr.len = ring_frame_size(&tx_ring);
263 trunced++;
265 } while (mode->filter && !bpf_run_filter(&bpf_ops, out, phdr.len));
266 pcap_pkthdr_to_tpacket_hdr(&phdr, &hdr->tp_h);
268 stats.tx_bytes += hdr->tp_h.tp_len;;
269 stats.tx_packets++;
271 show_frame_hdr(hdr, mode->print_mode, RING_MODE_EGRESS);
272 dissector_entry_point(out, hdr->tp_h.tp_snaplen,
273 mode->link_type, mode->print_mode);
275 kernel_may_pull_from_tx(&hdr->tp_h);
276 next_slot_prewr(&it, &tx_ring);
278 if (unlikely(sigint == 1))
279 break;
280 if (frame_cnt_max != 0 &&
281 stats.tx_packets >= frame_cnt_max) {
282 sigint = 1;
283 break;
287 out:
288 gettimeofday(&end, NULL);
289 diff = tv_subtract(end, start);
291 fflush(stdout);
292 printf("\n");
293 printf("\r%12lu frames outgoing\n", stats.tx_packets);
294 printf("\r%12lu frames truncated (larger than frame)\n", trunced);
295 printf("\r%12lu bytes outgoing\n", stats.tx_bytes);
296 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
298 bpf_release(&bpf_ops);
299 dissector_cleanup_all();
300 destroy_tx_ring(tx_sock, &tx_ring);
302 if (mode->rfraw)
303 leave_rfmon_mac80211(mode->device_trans, mode->device_out);
305 close(tx_sock);
306 if (pcap_ops[mode->pcap]->prepare_close_pcap)
307 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_READ);
308 close(fd);
311 static void enter_mode_rx_to_tx(struct mode *mode)
313 int rx_sock, ifindex_in, ifindex_out;
314 unsigned int size_in, size_out, it_in = 0, it_out = 0;
315 unsigned long fcnt = 0;
316 uint8_t *in, *out;
317 short ifflags = 0;
318 struct frame_map *hdr_in, *hdr_out;
319 struct ring tx_ring;
320 struct ring rx_ring;
321 struct pollfd rx_poll;
322 struct sock_fprog bpf_ops;
324 if (!strncmp(mode->device_in, mode->device_out,
325 strlen(mode->device_in)))
326 panic("Ingress/egress devices must be different!\n");
327 if (!device_up_and_running(mode->device_out))
328 panic("Egress device not up and running!\n");
329 if (!device_up_and_running(mode->device_in))
330 panic("Ingress device not up and running!\n");
332 rx_sock = pf_socket();
333 tx_sock = pf_socket();
335 fmemset(&tx_ring, 0, sizeof(tx_ring));
336 fmemset(&rx_ring, 0, sizeof(rx_ring));
337 fmemset(&rx_poll, 0, sizeof(rx_poll));
338 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
340 ifindex_in = device_ifindex(mode->device_in);
341 size_in = ring_size(mode->device_in, mode->reserve_size);
343 ifindex_out = device_ifindex(mode->device_out);
344 size_out = ring_size(mode->device_out, mode->reserve_size);
346 enable_kernel_bpf_jit_compiler();
347 bpf_parse_rules(mode->filter, &bpf_ops);
348 bpf_attach_to_sock(rx_sock, &bpf_ops);
350 setup_rx_ring_layout(rx_sock, &rx_ring, size_in, mode->jumbo_support);
351 create_rx_ring(rx_sock, &rx_ring);
352 mmap_rx_ring(rx_sock, &rx_ring);
353 alloc_rx_ring_frames(&rx_ring);
354 bind_rx_ring(rx_sock, &rx_ring, ifindex_in);
355 prepare_polling(rx_sock, &rx_poll);
357 set_packet_loss_discard(tx_sock);
358 setup_tx_ring_layout(tx_sock, &tx_ring, size_out, mode->jumbo_support);
359 create_tx_ring(tx_sock, &tx_ring);
360 mmap_tx_ring(tx_sock, &tx_ring);
361 alloc_tx_ring_frames(&tx_ring);
362 bind_tx_ring(tx_sock, &tx_ring, ifindex_out);
364 mt_init_by_seed_time();
365 dissector_init_all(mode->print_mode);
367 if (mode->promiscuous == true) {
368 ifflags = enter_promiscuous_mode(mode->device_in);
369 printf("PROMISC\n");
372 if (mode->kpull)
373 interval = mode->kpull;
375 itimer.it_interval.tv_sec = 0;
376 itimer.it_interval.tv_usec = interval;
377 itimer.it_value.tv_sec = 0;
378 itimer.it_value.tv_usec = interval;
379 setitimer(ITIMER_REAL, &itimer, NULL);
381 printf("BPF:\n");
382 bpf_dump_all(&bpf_ops);
383 printf("MD: RXTX %luus\n\n", interval);
384 printf("Running! Hang up with ^C!\n\n");
386 while (likely(sigint == 0)) {
387 while (user_may_pull_from_rx(rx_ring.frames[it_in].iov_base)) {
388 hdr_in = rx_ring.frames[it_in].iov_base;
389 in = ((uint8_t *) hdr_in) + hdr_in->tp_h.tp_mac;
390 fcnt++;
391 if (mode->packet_type != PACKET_ALL)
392 if (mode->packet_type != hdr_in->s_ll.sll_pkttype)
393 goto next;
395 hdr_out = tx_ring.frames[it_out].iov_base;
396 out = ((uint8_t *) hdr_out) + TPACKET_HDRLEN -
397 sizeof(struct sockaddr_ll);
399 for (; !user_may_pull_from_tx(tx_ring.frames[it_out].iov_base) &&
400 likely(!sigint);) {
401 if (mode->randomize)
402 next_rnd_slot(&it_out, &tx_ring);
403 else
404 next_slot(&it_out, &tx_ring);
405 hdr_out = tx_ring.frames[it_out].iov_base;
406 out = ((uint8_t *) hdr_out) + TPACKET_HDRLEN -
407 sizeof(struct sockaddr_ll);
410 tpacket_hdr_clone(&hdr_out->tp_h, &hdr_in->tp_h);
411 fmemcpy(out, in, hdr_in->tp_h.tp_len);
413 kernel_may_pull_from_tx(&hdr_out->tp_h);
414 if (mode->randomize)
415 next_rnd_slot(&it_out, &tx_ring);
416 else
417 next_slot(&it_out, &tx_ring);
419 show_frame_hdr(hdr_in, mode->print_mode, RING_MODE_INGRESS);
420 dissector_entry_point(in, hdr_in->tp_h.tp_snaplen,
421 mode->link_type, mode->print_mode);
423 if (frame_cnt_max != 0 && fcnt >= frame_cnt_max) {
424 sigint = 1;
425 break;
427 next:
428 kernel_may_pull_from_rx(&hdr_in->tp_h);
429 next_slot(&it_in, &rx_ring);
431 if (unlikely(sigint == 1))
432 goto out;
435 poll(&rx_poll, 1, -1);
436 poll_error_maybe_die(rx_sock, &rx_poll);
438 out:
439 sock_print_net_stats(rx_sock, 0);
441 bpf_release(&bpf_ops);
442 dissector_cleanup_all();
443 destroy_tx_ring(tx_sock, &tx_ring);
444 destroy_rx_ring(rx_sock, &rx_ring);
446 if (mode->promiscuous == true)
447 leave_promiscuous_mode(mode->device_in, ifflags);
449 close(tx_sock);
450 close(rx_sock);
453 static void enter_mode_read_pcap(struct mode *mode)
455 int ret, fd, fdo = 0;
456 struct pcap_pkthdr phdr;
457 struct sock_fprog bpf_ops;
458 struct tx_stats stats;
459 struct frame_map fm;
460 uint8_t *out;
461 size_t out_len;
462 unsigned long trunced = 0;
463 struct timeval start, end, diff;
465 if (!pcap_ops[mode->pcap])
466 panic("pcap group not supported!\n");
467 fd = open_or_die(mode->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
468 ret = pcap_ops[mode->pcap]->pull_file_header(fd, &mode->link_type);
469 if (ret)
470 panic("error reading pcap header!\n");
471 if (pcap_ops[mode->pcap]->prepare_reading_pcap) {
472 ret = pcap_ops[mode->pcap]->prepare_reading_pcap(fd);
473 if (ret)
474 panic("error prepare reading pcap!\n");
477 fmemset(&fm, 0, sizeof(fm));
478 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
479 fmemset(&stats, 0, sizeof(stats));
481 bpf_parse_rules(mode->filter, &bpf_ops);
482 dissector_init_all(mode->print_mode);
484 out_len = 64 * 1024;
485 out = xmalloc_aligned(out_len, CO_CACHE_LINE_SIZE);
487 printf("BPF:\n");
488 bpf_dump_all(&bpf_ops);
489 printf("MD: RD %s ", pcap_ops[mode->pcap]->name);
490 #ifdef _LARGEFILE64_SOURCE
491 printf("lf64 ");
492 #endif
493 ioprio_print();
494 printf("\n");
496 if (mode->device_out) {
497 fdo = open_or_die_m(mode->device_out, O_RDWR | O_CREAT |
498 O_TRUNC | O_LARGEFILE, DEFFILEMODE);
501 gettimeofday(&start, NULL);
503 while (likely(sigint == 0)) {
504 do {
505 memset(&phdr, 0, sizeof(phdr));
506 ret = pcap_ops[mode->pcap]->read_pcap_pkt(fd, &phdr,
507 out, out_len);
508 if (unlikely(ret < 0))
509 goto out;
510 if (unlikely(phdr.len == 0)) {
511 trunced++;
512 continue;
514 if (unlikely(phdr.len > out_len)) {
515 phdr.len = out_len;
516 trunced++;
518 } while (mode->filter &&
519 !bpf_run_filter(&bpf_ops, out, phdr.len));
521 pcap_pkthdr_to_tpacket_hdr(&phdr, &fm.tp_h);
523 stats.tx_bytes += fm.tp_h.tp_len;
524 stats.tx_packets++;
526 show_frame_hdr(&fm, mode->print_mode, RING_MODE_EGRESS);
527 dissector_entry_point(out, fm.tp_h.tp_snaplen,
528 mode->link_type, mode->print_mode);
530 if (mode->device_out) {
531 int i = 0;
532 char bout[80];
533 slprintf(bout, sizeof(bout), "{\n ");
534 write_or_die(fdo, bout, strlen(bout));
536 while (i < fm.tp_h.tp_snaplen) {
537 slprintf(bout, sizeof(bout), "0x%02x, ", out[i]);
538 write_or_die(fdo, bout, strlen(bout));
539 i++;
540 if (i % 10 == 0) {
541 slprintf(bout, sizeof(bout), "\n", out[i]);
542 write_or_die(fdo, bout, strlen(bout));
543 if (i < fm.tp_h.tp_snaplen) {
544 slprintf(bout, sizeof(bout), " ", out[i]);
545 write_or_die(fdo, bout, strlen(bout));
549 if (i % 10 != 0) {
550 slprintf(bout, sizeof(bout), "\n");
551 write_or_die(fdo, bout, strlen(bout));
553 slprintf(bout, sizeof(bout), "}\n\n");
554 write_or_die(fdo, bout, strlen(bout));
557 if (frame_cnt_max != 0 &&
558 stats.tx_packets >= frame_cnt_max) {
559 sigint = 1;
560 break;
563 out:
564 gettimeofday(&end, NULL);
565 diff = tv_subtract(end, start);
567 fflush(stdout);
568 printf("\n");
569 printf("\r%12lu frames outgoing\n", stats.tx_packets);
570 printf("\r%12lu frames truncated (larger than mtu)\n", trunced);
571 printf("\r%12lu bytes outgoing\n", stats.tx_bytes);
572 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
574 xfree(out);
576 bpf_release(&bpf_ops);
577 dissector_cleanup_all();
578 if (pcap_ops[mode->pcap]->prepare_close_pcap)
579 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_READ);
580 close(fd);
582 if (mode->device_out)
583 close(fdo);
586 static void finish_multi_pcap_file(struct mode *mode, int fd)
588 pcap_ops[mode->pcap]->fsync_pcap(fd);
589 if (pcap_ops[mode->pcap]->prepare_close_pcap)
590 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_WRITE);
591 close(fd);
593 fmemset(&itimer, 0, sizeof(itimer));
594 setitimer(ITIMER_REAL, &itimer, NULL);
597 static int next_multi_pcap_file(struct mode *mode, int fd)
599 int ret;
600 char tmp[512];
602 pcap_ops[mode->pcap]->fsync_pcap(fd);
603 if (pcap_ops[mode->pcap]->prepare_close_pcap)
604 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_WRITE);
605 close(fd);
607 slprintf(tmp, sizeof(tmp), "%s/%lu.pcap", mode->device_out, time(0));
609 fd = open_or_die_m(tmp, O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE,
610 DEFFILEMODE);
611 ret = pcap_ops[mode->pcap]->push_file_header(fd, mode->link_type);
612 if (ret)
613 panic("error writing pcap header!\n");
614 if (pcap_ops[mode->pcap]->prepare_writing_pcap) {
615 ret = pcap_ops[mode->pcap]->prepare_writing_pcap(fd);
616 if (ret)
617 panic("error prepare writing pcap!\n");
620 return fd;
623 static int begin_multi_pcap_file(struct mode *mode)
625 int fd, ret;
626 char tmp[512];
628 if (!pcap_ops[mode->pcap])
629 panic("pcap group not supported!\n");
630 if (mode->device_out[strlen(mode->device_out) - 1] == '/')
631 mode->device_out[strlen(mode->device_out) - 1] = 0;
633 slprintf(tmp, sizeof(tmp), "%s/%lu.pcap", mode->device_out, time(0));
635 fd = open_or_die_m(tmp, O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE,
636 DEFFILEMODE);
637 ret = pcap_ops[mode->pcap]->push_file_header(fd, mode->link_type);
638 if (ret)
639 panic("error writing pcap header!\n");
640 if (pcap_ops[mode->pcap]->prepare_writing_pcap) {
641 ret = pcap_ops[mode->pcap]->prepare_writing_pcap(fd);
642 if (ret)
643 panic("error prepare writing pcap!\n");
646 interval = mode->dump_interval;
647 itimer.it_interval.tv_sec = interval;
648 itimer.it_interval.tv_usec = 0;
649 itimer.it_value.tv_sec = interval;
650 itimer.it_value.tv_usec = 0;
651 setitimer(ITIMER_REAL, &itimer, NULL);
653 return fd;
656 static void finish_single_pcap_file(struct mode *mode, int fd)
658 pcap_ops[mode->pcap]->fsync_pcap(fd);
659 if (pcap_ops[mode->pcap]->prepare_close_pcap)
660 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_WRITE);
661 close(fd);
664 static int begin_single_pcap_file(struct mode *mode)
666 int fd, ret;
668 if (!pcap_ops[mode->pcap])
669 panic("pcap group not supported!\n");
670 fd = open_or_die_m(mode->device_out,
671 O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE,
672 DEFFILEMODE);
673 ret = pcap_ops[mode->pcap]->push_file_header(fd, mode->link_type);
674 if (ret)
675 panic("error writing pcap header!\n");
676 if (pcap_ops[mode->pcap]->prepare_writing_pcap) {
677 ret = pcap_ops[mode->pcap]->prepare_writing_pcap(fd);
678 if (ret)
679 panic("error prepare writing pcap!\n");
682 return fd;
685 static void enter_mode_rx_only_or_dump(struct mode *mode)
687 int sock, irq, ifindex, fd = 0, ret;
688 unsigned int size, it = 0;
689 unsigned long fcnt = 0, skipped = 0;
690 short ifflags = 0;
691 uint8_t *packet;
692 struct ring rx_ring;
693 struct pollfd rx_poll;
694 struct frame_map *hdr;
695 struct sock_fprog bpf_ops;
696 struct timeval start, end, diff;
698 if (!device_up_and_running(mode->device_in))
699 panic("Device not up and running!\n");
701 sock = pf_socket();
703 if (mode->rfraw) {
704 mode->device_trans = xstrdup(mode->device_in);
705 xfree(mode->device_in);
707 enter_rfmon_mac80211(mode->device_trans, &mode->device_in);
708 mode->link_type = LINKTYPE_IEEE802_11;
711 if (mode->dump) {
712 struct stat tmp;
713 fmemset(&tmp, 0, sizeof(tmp));
714 ret = stat(mode->device_out, &tmp);
715 if (ret < 0) {
716 mode->dump_dir = 0;
717 goto try_file;
719 mode->dump_dir = !!S_ISDIR(tmp.st_mode);
720 if (mode->dump_dir) {
721 fd = begin_multi_pcap_file(mode);
722 } else {
723 try_file:
724 fd = begin_single_pcap_file(mode);
728 fmemset(&rx_ring, 0, sizeof(rx_ring));
729 fmemset(&rx_poll, 0, sizeof(rx_poll));
730 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
732 ifindex = device_ifindex(mode->device_in);
733 size = ring_size(mode->device_in, mode->reserve_size);
735 enable_kernel_bpf_jit_compiler();
736 bpf_parse_rules(mode->filter, &bpf_ops);
737 bpf_attach_to_sock(sock, &bpf_ops);
739 set_sockopt_hwtimestamp(sock, mode->device_in);
740 setup_rx_ring_layout(sock, &rx_ring, size, mode->jumbo_support);
741 create_rx_ring(sock, &rx_ring);
742 mmap_rx_ring(sock, &rx_ring);
743 alloc_rx_ring_frames(&rx_ring);
744 bind_rx_ring(sock, &rx_ring, ifindex);
746 prepare_polling(sock, &rx_poll);
747 dissector_init_all(mode->print_mode);
749 if (mode->cpu >= 0 && ifindex > 0) {
750 irq = device_irq_number(mode->device_in);
751 device_bind_irq_to_cpu(mode->cpu, irq);
752 printf("IRQ: %s:%d > CPU%d\n", mode->device_in, irq,
753 mode->cpu);
756 if (mode->promiscuous == true) {
757 ifflags = enter_promiscuous_mode(mode->device_in);
758 printf("PROMISC\n");
761 printf("BPF:\n");
762 bpf_dump_all(&bpf_ops);
763 printf("MD: RX %s ", mode->dump ? pcap_ops[mode->pcap]->name : "");
764 if (mode->rfraw)
765 printf("802.11 raw via %s ", mode->device_in);
766 #ifdef _LARGEFILE64_SOURCE
767 printf("lf64 ");
768 #endif
769 ioprio_print();
770 printf("\n");
772 gettimeofday(&start, NULL);
774 while (likely(sigint == 0)) {
775 while (user_may_pull_from_rx(rx_ring.frames[it].iov_base)) {
776 hdr = rx_ring.frames[it].iov_base;
777 packet = ((uint8_t *) hdr) + hdr->tp_h.tp_mac;
778 fcnt++;
780 if (mode->packet_type != PACKET_ALL)
781 if (mode->packet_type != hdr->s_ll.sll_pkttype)
782 goto next;
783 if (unlikely(ring_frame_size(&rx_ring) <
784 hdr->tp_h.tp_snaplen)) {
785 skipped++;
786 goto next;
788 if (mode->dump) {
789 struct pcap_pkthdr phdr;
790 tpacket_hdr_to_pcap_pkthdr(&hdr->tp_h, &phdr);
791 ret = pcap_ops[mode->pcap]->write_pcap_pkt(fd, &phdr,
792 packet, phdr.len);
793 if (unlikely(ret != sizeof(phdr) + phdr.len))
794 panic("Write error to pcap!\n");
797 show_frame_hdr(hdr, mode->print_mode, RING_MODE_INGRESS);
798 dissector_entry_point(packet, hdr->tp_h.tp_snaplen,
799 mode->link_type, mode->print_mode);
801 if (frame_cnt_max != 0 && fcnt >= frame_cnt_max) {
802 sigint = 1;
803 break;
805 next:
806 kernel_may_pull_from_rx(&hdr->tp_h);
807 next_slot_prerd(&it, &rx_ring);
809 if (unlikely(sigint == 1))
810 break;
811 if (mode->dump && next_dump) {
812 struct tpacket_stats kstats;
813 socklen_t slen = sizeof(kstats);
814 fmemset(&kstats, 0, sizeof(kstats));
815 getsockopt(sock, SOL_PACKET, PACKET_STATISTICS,
816 &kstats, &slen);
817 fd = next_multi_pcap_file(mode, fd);
818 next_dump = false;
819 if (mode->print_mode == FNTTYPE_PRINT_NONE) {
820 printf(".(+%lu/-%lu)",
821 1UL * kstats.tp_packets -
822 kstats.tp_drops -
823 skipped, 1UL * kstats.tp_drops +
824 skipped);
825 fflush(stdout);
830 poll(&rx_poll, 1, -1);
831 poll_error_maybe_die(sock, &rx_poll);
834 gettimeofday(&end, NULL);
835 diff = tv_subtract(end, start);
837 if (!(mode->dump_dir && mode->print_mode == FNTTYPE_PRINT_NONE)) {
838 sock_print_net_stats(sock, skipped);
839 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec,
840 diff.tv_usec);
841 } else {
842 printf("\n\n");
843 fflush(stdout);
846 bpf_release(&bpf_ops);
847 dissector_cleanup_all();
848 destroy_rx_ring(sock, &rx_ring);
850 if (mode->promiscuous == true)
851 leave_promiscuous_mode(mode->device_in, ifflags);
853 if (mode->rfraw)
854 leave_rfmon_mac80211(mode->device_trans, mode->device_in);
856 close(sock);
858 if (mode->dump) {
859 if (mode->dump_dir)
860 finish_multi_pcap_file(mode, fd);
861 else
862 finish_single_pcap_file(mode, fd);
866 static void help(void)
868 printf("\n%s %s, the packet sniffing beast\n",
869 PROGNAME_STRING, VERSION_STRING);
870 puts("http://www.netsniff-ng.org\n\n"
871 "Usage: netsniff-ng [options]\n"
872 "Options:\n"
873 " -i|-d|--dev|--in <dev|pcap> Input source as netdev or pcap\n"
874 " -o|--out <dev|pcap|dir|txf> Output sink as netdev, pcap, directory, txf file\n"
875 " -f|--filter <bpf-file> Use BPF filter file from bpfc\n"
876 " -t|--type <type> Only handle packets of defined type:\n"
877 " host|broadcast|multicast|others|outgoing\n"
878 " -F|--interval <uint> Dump interval in sec if -o is a directory where\n"
879 " pcap files should be stored (default: 60)\n"
880 " -J|--jumbo-support Support for 64KB Super Jumbo Frames\n"
881 " Default RX/TX slot: 2048Byte\n"
882 " -R|--rfraw Capture or inject raw 802.11 frames\n"
883 " -n|--num <uint> Number of packets until exit\n"
884 " `-- 0 Loop until interrupted (default)\n"
885 " `- n Send n packets and done\n"
886 "Options for printing:\n"
887 " -s|--silent Do not print captured packets\n"
888 " -q|--less Print less-verbose packet information\n"
889 " -X|--hex Print packet data in hex format\n"
890 " -l|--ascii Print human-readable packet data\n"
891 "Options, advanced:\n"
892 " -r|--rand Randomize packet forwarding order\n"
893 " -M|--no-promisc No promiscuous mode for netdev\n"
894 " -A|--no-sock-mem Don't tune core socket memory\n"
895 " -m|--mmap Mmap pcap file i.e., for replaying\n"
896 " -g|--sg Scatter/gather pcap file I/O\n"
897 " -c|--clrw Use slower read(2)/write(2) I/O\n"
898 " -S|--ring-size <size> Manually set ring size to <size>:\n"
899 " mmap space in KB/MB/GB, e.g. \'10MB\'\n"
900 " -k|--kernel-pull <uint> Kernel pull from user interval in us\n"
901 " Default is 10us where the TX_RING\n"
902 " is populated with payload from uspace\n"
903 " -b|--bind-cpu <cpu> Bind to specific CPU (or CPU-range)\n"
904 " -B|--unbind-cpu <cpu> Forbid to use specific CPU (or CPU-range)\n"
905 " -H|--prio-high Make this high priority process\n"
906 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
907 " -v|--version Show version\n"
908 " -h|--help Guess what?!\n\n"
909 "Examples:\n"
910 " netsniff-ng --in eth0 --out dump.pcap --silent --bind-cpu 0\n"
911 " netsniff-ng --in wlan0 --rfraw --out dump.pcap --silent --bind-cpu 0\n"
912 " netsniff-ng --in dump.pcap --mmap --out eth0 --silent --bind-cpu 0\n"
913 " netsniff-ng --in dump.pcap --out dump.txf --silent --bind-cpu 0\n"
914 " netsniff-ng --in eth0 --out eth1 --silent --bind-cpu 0 --type host\n"
915 " netsniff-ng --in eth1 --out /opt/probe1/ -s -m -J --interval 30 -b 0\n"
916 " netsniff-ng --in any --filter http.bpf --jumbo-support --ascii\n\n"
917 "Note:\n"
918 " This tool is targeted for network developers! You should\n"
919 " be aware of what you are doing and what these options above\n"
920 " mean! Use netsniff-ng's bpfc compiler for generating filter files.\n"
921 " Further, netsniff-ng automatically enables the kernel BPF JIT\n"
922 " if present. Txf file output is only possible if the input source\n"
923 " is a pcap file.\n\n"
924 "Please report bugs to <bugs@netsniff-ng.org>\n"
925 "Copyright (C) 2009-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n"
926 "Copyright (C) 2009-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n"
927 "Copyright (C) 2012 Markus Amend <markus@netsniff-ng.org>\n"
928 "License: GNU GPL version 2.0\n"
929 "This is free software: you are free to change and redistribute it.\n"
930 "There is NO WARRANTY, to the extent permitted by law.\n");
931 die();
934 static void version(void)
936 printf("\n%s %s, the packet sniffing beast\n",
937 PROGNAME_STRING, VERSION_STRING);
938 puts("http://www.netsniff-ng.org\n\n"
939 "Please report bugs to <bugs@netsniff-ng.org>\n"
940 "Copyright (C) 2009-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n"
941 "Copyright (C) 2009-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n"
942 "Copyright (C) 2012 Markus Amend <markus@netsniff-ng.org>\n"
943 "License: GNU GPL version 2.0\n"
944 "This is free software: you are free to change and redistribute it.\n"
945 "There is NO WARRANTY, to the extent permitted by law.\n");
946 die();
949 static void header(void)
951 printf("%s%s%s\n", colorize_start(bold), PROGNAME_STRING " "
952 VERSION_STRING, colorize_end());
955 int main(int argc, char **argv)
957 int c, i, j, opt_index, ops_touched = 0;
958 int vals[4] = {0};
959 char *ptr;
960 bool prio_high = false;
961 bool setsockmem = true;
962 struct mode mode;
963 void (*enter_mode)(struct mode *mode) = NULL;
965 check_for_root_maybe_die();
967 fmemset(&mode, 0, sizeof(mode));
968 mode.link_type = LINKTYPE_EN10MB;
969 mode.print_mode = FNTTYPE_PRINT_NORM;
970 mode.cpu = CPU_UNKNOWN;
971 mode.packet_type = PACKET_ALL;
972 mode.promiscuous = true;
973 mode.randomize = false;
974 mode.pcap = PCAP_OPS_SG;
975 mode.dump_interval = DUMP_INTERVAL;
977 while ((c = getopt_long(argc, argv, short_options, long_options,
978 &opt_index)) != EOF) {
979 switch (c) {
980 case 'd':
981 case 'i':
982 mode.device_in = xstrdup(optarg);
983 break;
984 case 'o':
985 mode.device_out = xstrdup(optarg);
986 break;
987 case 'R':
988 mode.link_type = LINKTYPE_IEEE802_11;
989 mode.rfraw = 1;
990 break;
991 case 'r':
992 mode.randomize = true;
993 break;
994 case 'J':
995 mode.jumbo_support = 1;
996 break;
997 case 'f':
998 mode.filter = xstrdup(optarg);
999 break;
1000 case 'M':
1001 mode.promiscuous = false;
1002 break;
1003 case 'A':
1004 setsockmem = false;
1005 break;
1006 case 't':
1007 if (!strncmp(optarg, "host", strlen("host")))
1008 mode.packet_type = PACKET_HOST;
1009 else if (!strncmp(optarg, "broadcast", strlen("broadcast")))
1010 mode.packet_type = PACKET_BROADCAST;
1011 else if (!strncmp(optarg, "multicast", strlen("multicast")))
1012 mode.packet_type = PACKET_MULTICAST;
1013 else if (!strncmp(optarg, "others", strlen("others")))
1014 mode.packet_type = PACKET_OTHERHOST;
1015 else if (!strncmp(optarg, "outgoing", strlen("outgoing")))
1016 mode.packet_type = PACKET_OUTGOING;
1017 else
1018 mode.packet_type = PACKET_ALL;
1019 break;
1020 case 'S':
1021 ptr = optarg;
1022 mode.reserve_size = 0;
1024 for (j = i = strlen(optarg); i > 0; --i) {
1025 if (!isdigit(optarg[j - i]))
1026 break;
1027 ptr++;
1030 if (!strncmp(ptr, "KB", strlen("KB")))
1031 mode.reserve_size = 1 << 10;
1032 else if (!strncmp(ptr, "MB", strlen("MB")))
1033 mode.reserve_size = 1 << 20;
1034 else if (!strncmp(ptr, "GB", strlen("GB")))
1035 mode.reserve_size = 1 << 30;
1036 else
1037 panic("Syntax error in ring size param!\n");
1039 *ptr = 0;
1040 mode.reserve_size *= atoi(optarg);
1041 break;
1042 case 'b':
1043 set_cpu_affinity(optarg, 0);
1044 if (mode.cpu != CPU_NOTOUCH)
1045 mode.cpu = atoi(optarg);
1046 break;
1047 case 'B':
1048 set_cpu_affinity(optarg, 1);
1049 break;
1050 case 'H':
1051 prio_high = true;
1052 break;
1053 case 'c':
1054 mode.pcap = PCAP_OPS_RW;
1055 ops_touched = 1;
1056 break;
1057 case 'm':
1058 mode.pcap = PCAP_OPS_MMAP;
1059 ops_touched = 1;
1060 break;
1061 case 'g':
1062 mode.pcap = PCAP_OPS_SG;
1063 ops_touched = 1;
1064 break;
1065 case 'Q':
1066 mode.cpu = CPU_NOTOUCH;
1067 break;
1068 case 's':
1069 mode.print_mode = FNTTYPE_PRINT_NONE;
1070 break;
1071 case 'q':
1072 mode.print_mode = FNTTYPE_PRINT_LESS;
1073 break;
1074 case 'X':
1075 mode.print_mode = (mode.print_mode == FNTTYPE_PRINT_ASCII) ?
1076 FNTTYPE_PRINT_HEX_ASCII : FNTTYPE_PRINT_HEX;
1077 break;
1078 case 'l':
1079 mode.print_mode = (mode.print_mode == FNTTYPE_PRINT_HEX) ?
1080 FNTTYPE_PRINT_HEX_ASCII : FNTTYPE_PRINT_ASCII;
1081 break;
1082 case 'k':
1083 mode.kpull = (unsigned long) atol(optarg);
1084 break;
1085 case 'n':
1086 frame_cnt_max = (unsigned long) atol(optarg);
1087 break;
1088 case 'F':
1089 mode.dump_interval = (unsigned long) atol(optarg);
1090 break;
1091 case 'v':
1092 version();
1093 break;
1094 case 'h':
1095 help();
1096 break;
1097 case '?':
1098 switch (optopt) {
1099 case 'd':
1100 case 'i':
1101 case 'o':
1102 case 'f':
1103 case 't':
1104 case 'F':
1105 case 'n':
1106 case 'S':
1107 case 'b':
1108 case 'k':
1109 case 'B':
1110 case 'e':
1111 panic("Option -%c requires an argument!\n",
1112 optopt);
1113 default:
1114 if (isprint(optopt))
1115 whine("Unknown option character "
1116 "`0x%X\'!\n", optopt);
1117 die();
1119 default:
1120 break;
1124 if (!mode.device_in)
1125 mode.device_in = xstrdup("any");
1127 register_signal(SIGINT, signal_handler);
1128 register_signal(SIGHUP, signal_handler);
1130 init_pcap(mode.jumbo_support);
1131 tprintf_init();
1132 header();
1134 if (prio_high == true) {
1135 set_proc_prio(get_default_proc_prio());
1136 set_sched_status(get_default_sched_policy(),
1137 get_default_sched_prio());
1140 if (setsockmem == true) {
1141 if ((vals[0] = get_system_socket_mem(sock_rmem_max)) < SMEM_SUG_MAX)
1142 set_system_socket_mem(sock_rmem_max, SMEM_SUG_MAX);
1143 if ((vals[1] = get_system_socket_mem(sock_rmem_def)) < SMEM_SUG_DEF)
1144 set_system_socket_mem(sock_rmem_def, SMEM_SUG_DEF);
1145 if ((vals[2] = get_system_socket_mem(sock_wmem_max)) < SMEM_SUG_MAX)
1146 set_system_socket_mem(sock_wmem_max, SMEM_SUG_MAX);
1147 if ((vals[3] = get_system_socket_mem(sock_wmem_def)) < SMEM_SUG_DEF)
1148 set_system_socket_mem(sock_wmem_def, SMEM_SUG_DEF);
1151 if (mode.device_in && (device_mtu(mode.device_in) ||
1152 !strncmp("any", mode.device_in, strlen(mode.device_in)))) {
1153 if (!mode.device_out) {
1154 mode.dump = 0;
1155 enter_mode = enter_mode_rx_only_or_dump;
1156 } else if (device_mtu(mode.device_out)) {
1157 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1158 enter_mode = enter_mode_rx_to_tx;
1159 } else {
1160 mode.dump = 1;
1161 register_signal_f(SIGALRM, timer_next_dump, SA_SIGINFO);
1162 enter_mode = enter_mode_rx_only_or_dump;
1163 if (!ops_touched)
1164 mode.pcap = PCAP_OPS_SG;
1166 } else {
1167 if (mode.device_out && device_mtu(mode.device_out)) {
1168 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1169 enter_mode = enter_mode_pcap_to_tx;
1170 if (!ops_touched)
1171 mode.pcap = PCAP_OPS_MMAP;
1172 } else {
1173 enter_mode = enter_mode_read_pcap;
1174 if (!ops_touched)
1175 mode.pcap = PCAP_OPS_SG;
1179 if (!enter_mode)
1180 panic("Selection not supported!\n");
1181 enter_mode(&mode);
1183 tprintf_cleanup();
1184 cleanup_pcap();
1186 if (setsockmem == true) {
1187 set_system_socket_mem(sock_rmem_max, vals[0]);
1188 set_system_socket_mem(sock_rmem_def, vals[1]);
1189 set_system_socket_mem(sock_wmem_max, vals[2]);
1190 set_system_socket_mem(sock_wmem_def, vals[3]);
1193 free(mode.device_in);
1194 free(mode.device_out);
1195 free(mode.device_trans);
1197 return 0;