examples: bpf: different labeling
[netsniff-ng.git] / src / netsniff-ng.c
blobefee30b0d0e661ba8906c2f28250ab5bd725dcf4
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 !mode->rfraw)
174 panic("Device not up and running!\n");
176 tx_sock = pf_socket();
178 if (!pcap_ops[mode->pcap])
179 panic("pcap group not supported!\n");
180 fd = open_or_die(mode->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
181 ret = pcap_ops[mode->pcap]->pull_file_header(fd, &mode->link_type);
182 if (ret)
183 panic("error reading pcap header!\n");
184 if (pcap_ops[mode->pcap]->prepare_reading_pcap) {
185 ret = pcap_ops[mode->pcap]->prepare_reading_pcap(fd);
186 if (ret)
187 panic("error prepare reading pcap!\n");
190 fmemset(&tx_ring, 0, sizeof(tx_ring));
191 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
192 fmemset(&stats, 0, sizeof(stats));
194 if (mode->rfraw) {
195 mode->device_trans = xstrdup(mode->device_out);
196 xfree(mode->device_out);
198 enter_rfmon_mac80211(mode->device_trans, &mode->device_out);
199 if (mode->link_type != LINKTYPE_IEEE802_11)
200 panic("Wrong linktype of pcap!\n");
203 ifindex = device_ifindex(mode->device_out);
204 size = ring_size(mode->device_out, mode->reserve_size);
206 bpf_parse_rules(mode->filter, &bpf_ops);
208 set_packet_loss_discard(tx_sock);
209 set_sockopt_hwtimestamp(tx_sock, mode->device_out);
210 setup_tx_ring_layout(tx_sock, &tx_ring, size, mode->jumbo_support);
211 create_tx_ring(tx_sock, &tx_ring);
212 mmap_tx_ring(tx_sock, &tx_ring);
213 alloc_tx_ring_frames(&tx_ring);
214 bind_tx_ring(tx_sock, &tx_ring, ifindex);
216 dissector_init_all(mode->print_mode);
218 if (mode->cpu >= 0 && ifindex > 0) {
219 irq = device_irq_number(mode->device_out);
220 device_bind_irq_to_cpu(mode->cpu, irq);
221 printf("IRQ: %s:%d > CPU%d\n", mode->device_out, irq,
222 mode->cpu);
225 if (mode->kpull)
226 interval = mode->kpull;
228 itimer.it_interval.tv_sec = 0;
229 itimer.it_interval.tv_usec = interval;
230 itimer.it_value.tv_sec = 0;
231 itimer.it_value.tv_usec = interval;
232 setitimer(ITIMER_REAL, &itimer, NULL);
234 printf("BPF:\n");
235 bpf_dump_all(&bpf_ops);
236 printf("MD: TX %luus %s ", interval, pcap_ops[mode->pcap]->name);
237 if (mode->rfraw)
238 printf("802.11 raw via %s ", mode->device_out);
239 #ifdef _LARGEFILE64_SOURCE
240 printf("lf64 ");
241 #endif
242 ioprio_print();
243 printf("\n");
245 bug_on(gettimeofday(&start, NULL));
247 while (likely(sigint == 0)) {
248 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
249 struct pcap_pkthdr phdr;
250 hdr = tx_ring.frames[it].iov_base;
251 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
252 * sizeof(struct sockaddr_ll); */
253 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN -
254 sizeof(struct sockaddr_ll);
256 do {
257 memset(&phdr, 0, sizeof(phdr));
258 ret = pcap_ops[mode->pcap]->read_pcap_pkt(fd, &phdr,
259 out, ring_frame_size(&tx_ring));
260 if (unlikely(ret <= 0))
261 goto out;
262 if (ring_frame_size(&tx_ring) < phdr.len) {
263 phdr.len = ring_frame_size(&tx_ring);
264 trunced++;
266 } while (mode->filter && !bpf_run_filter(&bpf_ops, out, phdr.len));
267 pcap_pkthdr_to_tpacket_hdr(&phdr, &hdr->tp_h);
269 stats.tx_bytes += hdr->tp_h.tp_len;;
270 stats.tx_packets++;
272 show_frame_hdr(hdr, mode->print_mode, RING_MODE_EGRESS);
273 dissector_entry_point(out, hdr->tp_h.tp_snaplen,
274 mode->link_type, mode->print_mode);
276 kernel_may_pull_from_tx(&hdr->tp_h);
277 next_slot_prewr(&it, &tx_ring);
279 if (unlikely(sigint == 1))
280 break;
281 if (frame_cnt_max != 0 &&
282 stats.tx_packets >= frame_cnt_max) {
283 sigint = 1;
284 break;
288 out:
289 bug_on(gettimeofday(&end, NULL));
290 diff = tv_subtract(end, start);
292 fflush(stdout);
293 printf("\n");
294 printf("\r%12lu frames outgoing\n", stats.tx_packets);
295 printf("\r%12lu frames truncated (larger than frame)\n", trunced);
296 printf("\r%12lu bytes outgoing\n", stats.tx_bytes);
297 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
299 bpf_release(&bpf_ops);
300 dissector_cleanup_all();
301 destroy_tx_ring(tx_sock, &tx_ring);
303 if (mode->rfraw)
304 leave_rfmon_mac80211(mode->device_trans, mode->device_out);
306 close(tx_sock);
307 if (pcap_ops[mode->pcap]->prepare_close_pcap)
308 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_READ);
309 close(fd);
312 static void enter_mode_rx_to_tx(struct mode *mode)
314 int rx_sock, ifindex_in, ifindex_out;
315 unsigned int size_in, size_out, it_in = 0, it_out = 0;
316 unsigned long fcnt = 0;
317 uint8_t *in, *out;
318 short ifflags = 0;
319 struct frame_map *hdr_in, *hdr_out;
320 struct ring tx_ring;
321 struct ring rx_ring;
322 struct pollfd rx_poll;
323 struct sock_fprog bpf_ops;
325 if (!strncmp(mode->device_in, mode->device_out,
326 strlen(mode->device_in)))
327 panic("Ingress/egress devices must be different!\n");
328 if (!device_up_and_running(mode->device_out))
329 panic("Egress device not up and running!\n");
330 if (!device_up_and_running(mode->device_in))
331 panic("Ingress device not up and running!\n");
333 rx_sock = pf_socket();
334 tx_sock = pf_socket();
336 fmemset(&tx_ring, 0, sizeof(tx_ring));
337 fmemset(&rx_ring, 0, sizeof(rx_ring));
338 fmemset(&rx_poll, 0, sizeof(rx_poll));
339 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
341 ifindex_in = device_ifindex(mode->device_in);
342 size_in = ring_size(mode->device_in, mode->reserve_size);
344 ifindex_out = device_ifindex(mode->device_out);
345 size_out = ring_size(mode->device_out, mode->reserve_size);
347 enable_kernel_bpf_jit_compiler();
348 bpf_parse_rules(mode->filter, &bpf_ops);
349 bpf_attach_to_sock(rx_sock, &bpf_ops);
351 setup_rx_ring_layout(rx_sock, &rx_ring, size_in, mode->jumbo_support);
352 create_rx_ring(rx_sock, &rx_ring);
353 mmap_rx_ring(rx_sock, &rx_ring);
354 alloc_rx_ring_frames(&rx_ring);
355 bind_rx_ring(rx_sock, &rx_ring, ifindex_in);
356 prepare_polling(rx_sock, &rx_poll);
358 set_packet_loss_discard(tx_sock);
359 setup_tx_ring_layout(tx_sock, &tx_ring, size_out, mode->jumbo_support);
360 create_tx_ring(tx_sock, &tx_ring);
361 mmap_tx_ring(tx_sock, &tx_ring);
362 alloc_tx_ring_frames(&tx_ring);
363 bind_tx_ring(tx_sock, &tx_ring, ifindex_out);
365 mt_init_by_seed_time();
366 dissector_init_all(mode->print_mode);
368 if (mode->promiscuous == true) {
369 ifflags = enter_promiscuous_mode(mode->device_in);
370 printf("PROMISC\n");
373 if (mode->kpull)
374 interval = mode->kpull;
376 itimer.it_interval.tv_sec = 0;
377 itimer.it_interval.tv_usec = interval;
378 itimer.it_value.tv_sec = 0;
379 itimer.it_value.tv_usec = interval;
380 setitimer(ITIMER_REAL, &itimer, NULL);
382 printf("BPF:\n");
383 bpf_dump_all(&bpf_ops);
384 printf("MD: RXTX %luus\n\n", interval);
385 printf("Running! Hang up with ^C!\n\n");
387 while (likely(sigint == 0)) {
388 while (user_may_pull_from_rx(rx_ring.frames[it_in].iov_base)) {
389 hdr_in = rx_ring.frames[it_in].iov_base;
390 in = ((uint8_t *) hdr_in) + hdr_in->tp_h.tp_mac;
391 fcnt++;
392 if (mode->packet_type != PACKET_ALL)
393 if (mode->packet_type != hdr_in->s_ll.sll_pkttype)
394 goto next;
396 hdr_out = tx_ring.frames[it_out].iov_base;
397 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN -
398 sizeof(struct sockaddr_ll);
400 for (; !user_may_pull_from_tx(tx_ring.frames[it_out].iov_base) &&
401 likely(!sigint);) {
402 if (mode->randomize)
403 next_rnd_slot(&it_out, &tx_ring);
404 else
405 next_slot(&it_out, &tx_ring);
406 hdr_out = tx_ring.frames[it_out].iov_base;
407 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN -
408 sizeof(struct sockaddr_ll);
411 tpacket_hdr_clone(&hdr_out->tp_h, &hdr_in->tp_h);
412 fmemcpy(out, in, hdr_in->tp_h.tp_len);
414 kernel_may_pull_from_tx(&hdr_out->tp_h);
415 if (mode->randomize)
416 next_rnd_slot(&it_out, &tx_ring);
417 else
418 next_slot(&it_out, &tx_ring);
420 show_frame_hdr(hdr_in, mode->print_mode, RING_MODE_INGRESS);
421 dissector_entry_point(in, hdr_in->tp_h.tp_snaplen,
422 mode->link_type, mode->print_mode);
424 if (frame_cnt_max != 0 && fcnt >= frame_cnt_max) {
425 sigint = 1;
426 break;
428 next:
429 kernel_may_pull_from_rx(&hdr_in->tp_h);
430 next_slot(&it_in, &rx_ring);
432 if (unlikely(sigint == 1))
433 goto out;
436 poll(&rx_poll, 1, -1);
437 poll_error_maybe_die(rx_sock, &rx_poll);
439 out:
440 sock_print_net_stats(rx_sock, 0);
442 bpf_release(&bpf_ops);
443 dissector_cleanup_all();
444 destroy_tx_ring(tx_sock, &tx_ring);
445 destroy_rx_ring(rx_sock, &rx_ring);
447 if (mode->promiscuous == true)
448 leave_promiscuous_mode(mode->device_in, ifflags);
450 close(tx_sock);
451 close(rx_sock);
454 static void enter_mode_read_pcap(struct mode *mode)
456 int ret, fd, fdo = 0;
457 struct pcap_pkthdr phdr;
458 struct sock_fprog bpf_ops;
459 struct tx_stats stats;
460 struct frame_map fm;
461 uint8_t *out;
462 size_t out_len;
463 unsigned long trunced = 0;
464 struct timeval start, end, diff;
466 if (!pcap_ops[mode->pcap])
467 panic("pcap group not supported!\n");
468 fd = open_or_die(mode->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
469 ret = pcap_ops[mode->pcap]->pull_file_header(fd, &mode->link_type);
470 if (ret)
471 panic("error reading pcap header!\n");
472 if (pcap_ops[mode->pcap]->prepare_reading_pcap) {
473 ret = pcap_ops[mode->pcap]->prepare_reading_pcap(fd);
474 if (ret)
475 panic("error prepare reading pcap!\n");
478 fmemset(&fm, 0, sizeof(fm));
479 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
480 fmemset(&stats, 0, sizeof(stats));
482 bpf_parse_rules(mode->filter, &bpf_ops);
483 dissector_init_all(mode->print_mode);
485 out_len = 64 * 1024;
486 out = xmalloc_aligned(out_len, CO_CACHE_LINE_SIZE);
488 printf("BPF:\n");
489 bpf_dump_all(&bpf_ops);
490 printf("MD: RD %s ", pcap_ops[mode->pcap]->name);
491 #ifdef _LARGEFILE64_SOURCE
492 printf("lf64 ");
493 #endif
494 ioprio_print();
495 printf("\n");
497 if (mode->device_out) {
498 fdo = open_or_die_m(mode->device_out, O_RDWR | O_CREAT |
499 O_TRUNC | O_LARGEFILE, DEFFILEMODE);
502 bug_on(gettimeofday(&start, NULL));
504 while (likely(sigint == 0)) {
505 do {
506 memset(&phdr, 0, sizeof(phdr));
507 ret = pcap_ops[mode->pcap]->read_pcap_pkt(fd, &phdr,
508 out, out_len);
509 if (unlikely(ret < 0))
510 goto out;
511 if (unlikely(phdr.len == 0)) {
512 trunced++;
513 continue;
515 if (unlikely(phdr.len > out_len)) {
516 phdr.len = out_len;
517 trunced++;
519 } while (mode->filter &&
520 !bpf_run_filter(&bpf_ops, out, phdr.len));
522 pcap_pkthdr_to_tpacket_hdr(&phdr, &fm.tp_h);
524 stats.tx_bytes += fm.tp_h.tp_len;
525 stats.tx_packets++;
527 show_frame_hdr(&fm, mode->print_mode, RING_MODE_EGRESS);
528 dissector_entry_point(out, fm.tp_h.tp_snaplen,
529 mode->link_type, mode->print_mode);
531 if (mode->device_out) {
532 int i = 0;
533 char bout[80];
534 slprintf(bout, sizeof(bout), "{\n ");
535 write_or_die(fdo, bout, strlen(bout));
537 while (i < fm.tp_h.tp_snaplen) {
538 slprintf(bout, sizeof(bout), "0x%02x, ", out[i]);
539 write_or_die(fdo, bout, strlen(bout));
540 i++;
541 if (i % 10 == 0) {
542 slprintf(bout, sizeof(bout), "\n", out[i]);
543 write_or_die(fdo, bout, strlen(bout));
544 if (i < fm.tp_h.tp_snaplen) {
545 slprintf(bout, sizeof(bout), " ", out[i]);
546 write_or_die(fdo, bout, strlen(bout));
550 if (i % 10 != 0) {
551 slprintf(bout, sizeof(bout), "\n");
552 write_or_die(fdo, bout, strlen(bout));
554 slprintf(bout, sizeof(bout), "}\n\n");
555 write_or_die(fdo, bout, strlen(bout));
558 if (frame_cnt_max != 0 &&
559 stats.tx_packets >= frame_cnt_max) {
560 sigint = 1;
561 break;
564 out:
565 bug_on(gettimeofday(&end, NULL));
566 diff = tv_subtract(end, start);
568 fflush(stdout);
569 printf("\n");
570 printf("\r%12lu frames outgoing\n", stats.tx_packets);
571 printf("\r%12lu frames truncated (larger than mtu)\n", trunced);
572 printf("\r%12lu bytes outgoing\n", stats.tx_bytes);
573 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
575 xfree(out);
577 bpf_release(&bpf_ops);
578 dissector_cleanup_all();
579 if (pcap_ops[mode->pcap]->prepare_close_pcap)
580 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_READ);
581 close(fd);
583 if (mode->device_out)
584 close(fdo);
587 static void finish_multi_pcap_file(struct mode *mode, int fd)
589 pcap_ops[mode->pcap]->fsync_pcap(fd);
590 if (pcap_ops[mode->pcap]->prepare_close_pcap)
591 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_WRITE);
592 close(fd);
594 fmemset(&itimer, 0, sizeof(itimer));
595 setitimer(ITIMER_REAL, &itimer, NULL);
598 static int next_multi_pcap_file(struct mode *mode, int fd)
600 int ret;
601 char tmp[512];
603 pcap_ops[mode->pcap]->fsync_pcap(fd);
604 if (pcap_ops[mode->pcap]->prepare_close_pcap)
605 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_WRITE);
606 close(fd);
608 slprintf(tmp, sizeof(tmp), "%s/%lu.pcap", mode->device_out, time(0));
610 fd = open_or_die_m(tmp, O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE,
611 DEFFILEMODE);
612 ret = pcap_ops[mode->pcap]->push_file_header(fd, mode->link_type);
613 if (ret)
614 panic("error writing pcap header!\n");
615 if (pcap_ops[mode->pcap]->prepare_writing_pcap) {
616 ret = pcap_ops[mode->pcap]->prepare_writing_pcap(fd);
617 if (ret)
618 panic("error prepare writing pcap!\n");
621 return fd;
624 static int begin_multi_pcap_file(struct mode *mode)
626 int fd, ret;
627 char tmp[512];
629 if (!pcap_ops[mode->pcap])
630 panic("pcap group not supported!\n");
631 if (mode->device_out[strlen(mode->device_out) - 1] == '/')
632 mode->device_out[strlen(mode->device_out) - 1] = 0;
634 slprintf(tmp, sizeof(tmp), "%s/%lu.pcap", mode->device_out, time(0));
636 fd = open_or_die_m(tmp, O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE,
637 DEFFILEMODE);
638 ret = pcap_ops[mode->pcap]->push_file_header(fd, mode->link_type);
639 if (ret)
640 panic("error writing pcap header!\n");
641 if (pcap_ops[mode->pcap]->prepare_writing_pcap) {
642 ret = pcap_ops[mode->pcap]->prepare_writing_pcap(fd);
643 if (ret)
644 panic("error prepare writing pcap!\n");
647 interval = mode->dump_interval;
648 itimer.it_interval.tv_sec = interval;
649 itimer.it_interval.tv_usec = 0;
650 itimer.it_value.tv_sec = interval;
651 itimer.it_value.tv_usec = 0;
652 setitimer(ITIMER_REAL, &itimer, NULL);
654 return fd;
657 static void finish_single_pcap_file(struct mode *mode, int fd)
659 pcap_ops[mode->pcap]->fsync_pcap(fd);
660 if (pcap_ops[mode->pcap]->prepare_close_pcap)
661 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_WRITE);
662 close(fd);
665 static int begin_single_pcap_file(struct mode *mode)
667 int fd, ret;
669 if (!pcap_ops[mode->pcap])
670 panic("pcap group not supported!\n");
671 fd = open_or_die_m(mode->device_out,
672 O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE,
673 DEFFILEMODE);
674 ret = pcap_ops[mode->pcap]->push_file_header(fd, mode->link_type);
675 if (ret)
676 panic("error writing pcap header!\n");
677 if (pcap_ops[mode->pcap]->prepare_writing_pcap) {
678 ret = pcap_ops[mode->pcap]->prepare_writing_pcap(fd);
679 if (ret)
680 panic("error prepare writing pcap!\n");
683 return fd;
686 static void enter_mode_rx_only_or_dump(struct mode *mode)
688 int sock, irq, ifindex, fd = 0, ret;
689 unsigned int size, it = 0;
690 unsigned long fcnt = 0, skipped = 0;
691 short ifflags = 0;
692 uint8_t *packet;
693 struct ring rx_ring;
694 struct pollfd rx_poll;
695 struct frame_map *hdr;
696 struct sock_fprog bpf_ops;
697 struct timeval start, end, diff;
699 if (!device_up_and_running(mode->device_in) &&
700 !mode->rfraw)
701 panic("Device not up and running!\n");
703 sock = pf_socket();
705 if (mode->rfraw) {
706 mode->device_trans = xstrdup(mode->device_in);
707 xfree(mode->device_in);
709 enter_rfmon_mac80211(mode->device_trans, &mode->device_in);
710 mode->link_type = LINKTYPE_IEEE802_11;
713 if (mode->dump) {
714 struct stat tmp;
715 fmemset(&tmp, 0, sizeof(tmp));
716 ret = stat(mode->device_out, &tmp);
717 if (ret < 0) {
718 mode->dump_dir = 0;
719 goto try_file;
721 mode->dump_dir = !!S_ISDIR(tmp.st_mode);
722 if (mode->dump_dir) {
723 fd = begin_multi_pcap_file(mode);
724 } else {
725 try_file:
726 fd = begin_single_pcap_file(mode);
730 fmemset(&rx_ring, 0, sizeof(rx_ring));
731 fmemset(&rx_poll, 0, sizeof(rx_poll));
732 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
734 ifindex = device_ifindex(mode->device_in);
735 size = ring_size(mode->device_in, mode->reserve_size);
737 enable_kernel_bpf_jit_compiler();
738 bpf_parse_rules(mode->filter, &bpf_ops);
739 bpf_attach_to_sock(sock, &bpf_ops);
741 set_sockopt_hwtimestamp(sock, mode->device_in);
742 setup_rx_ring_layout(sock, &rx_ring, size, mode->jumbo_support);
743 create_rx_ring(sock, &rx_ring);
744 mmap_rx_ring(sock, &rx_ring);
745 alloc_rx_ring_frames(&rx_ring);
746 bind_rx_ring(sock, &rx_ring, ifindex);
748 prepare_polling(sock, &rx_poll);
749 dissector_init_all(mode->print_mode);
751 if (mode->cpu >= 0 && ifindex > 0) {
752 irq = device_irq_number(mode->device_in);
753 device_bind_irq_to_cpu(mode->cpu, irq);
754 printf("IRQ: %s:%d > CPU%d\n", mode->device_in, irq,
755 mode->cpu);
758 if (mode->promiscuous == true) {
759 ifflags = enter_promiscuous_mode(mode->device_in);
760 printf("PROMISC\n");
763 printf("BPF:\n");
764 bpf_dump_all(&bpf_ops);
765 printf("MD: RX %s ", mode->dump ? pcap_ops[mode->pcap]->name : "");
766 if (mode->rfraw)
767 printf("802.11 raw via %s ", mode->device_in);
768 #ifdef _LARGEFILE64_SOURCE
769 printf("lf64 ");
770 #endif
771 ioprio_print();
772 printf("\n");
774 bug_on(gettimeofday(&start, NULL));
776 while (likely(sigint == 0)) {
777 while (user_may_pull_from_rx(rx_ring.frames[it].iov_base)) {
778 hdr = rx_ring.frames[it].iov_base;
779 packet = ((uint8_t *) hdr) + hdr->tp_h.tp_mac;
780 fcnt++;
782 if (mode->packet_type != PACKET_ALL)
783 if (mode->packet_type != hdr->s_ll.sll_pkttype)
784 goto next;
785 if (unlikely(ring_frame_size(&rx_ring) <
786 hdr->tp_h.tp_snaplen)) {
787 skipped++;
788 goto next;
790 if (mode->dump) {
791 struct pcap_pkthdr phdr;
792 tpacket_hdr_to_pcap_pkthdr(&hdr->tp_h, &phdr);
793 ret = pcap_ops[mode->pcap]->write_pcap_pkt(fd, &phdr,
794 packet, phdr.len);
795 if (unlikely(ret != sizeof(phdr) + phdr.len))
796 panic("Write error to pcap!\n");
799 show_frame_hdr(hdr, mode->print_mode, RING_MODE_INGRESS);
800 dissector_entry_point(packet, hdr->tp_h.tp_snaplen,
801 mode->link_type, mode->print_mode);
803 if (frame_cnt_max != 0 && fcnt >= frame_cnt_max) {
804 sigint = 1;
805 break;
807 next:
808 kernel_may_pull_from_rx(&hdr->tp_h);
809 next_slot_prerd(&it, &rx_ring);
811 if (unlikely(sigint == 1))
812 break;
813 if (mode->dump && next_dump) {
814 struct tpacket_stats kstats;
815 socklen_t slen = sizeof(kstats);
816 fmemset(&kstats, 0, sizeof(kstats));
817 getsockopt(sock, SOL_PACKET, PACKET_STATISTICS,
818 &kstats, &slen);
819 fd = next_multi_pcap_file(mode, fd);
820 next_dump = false;
821 if (mode->print_mode == FNTTYPE_PRINT_NONE) {
822 printf(".(+%lu/-%lu)",
823 1UL * kstats.tp_packets -
824 kstats.tp_drops -
825 skipped, 1UL * kstats.tp_drops +
826 skipped);
827 fflush(stdout);
832 poll(&rx_poll, 1, -1);
833 poll_error_maybe_die(sock, &rx_poll);
836 bug_on(gettimeofday(&end, NULL));
837 diff = tv_subtract(end, start);
839 if (!(mode->dump_dir && mode->print_mode == FNTTYPE_PRINT_NONE)) {
840 sock_print_net_stats(sock, skipped);
841 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec,
842 diff.tv_usec);
843 } else {
844 printf("\n\n");
845 fflush(stdout);
848 bpf_release(&bpf_ops);
849 dissector_cleanup_all();
850 destroy_rx_ring(sock, &rx_ring);
852 if (mode->promiscuous == true)
853 leave_promiscuous_mode(mode->device_in, ifflags);
855 if (mode->rfraw)
856 leave_rfmon_mac80211(mode->device_trans, mode->device_in);
858 close(sock);
860 if (mode->dump) {
861 if (mode->dump_dir)
862 finish_multi_pcap_file(mode, fd);
863 else
864 finish_single_pcap_file(mode, fd);
868 static void help(void)
870 printf("\n%s %s, the packet sniffing beast\n",
871 PROGNAME_STRING, VERSION_STRING);
872 puts("http://www.netsniff-ng.org\n\n"
873 "Usage: netsniff-ng [options]\n"
874 "Options:\n"
875 " -i|-d|--dev|--in <dev|pcap> Input source as netdev or pcap\n"
876 " -o|--out <dev|pcap|dir|txf> Output sink as netdev, pcap, directory, txf file\n"
877 " -f|--filter <bpf-file> Use BPF filter file from bpfc\n"
878 " -t|--type <type> Only handle packets of defined type:\n"
879 " host|broadcast|multicast|others|outgoing\n"
880 " -F|--interval <uint> Dump interval in sec if -o is a directory where\n"
881 " pcap files should be stored (default: 60)\n"
882 " -J|--jumbo-support Support for 64KB Super Jumbo Frames\n"
883 " Default RX/TX slot: 2048Byte\n"
884 " -R|--rfraw Capture or inject raw 802.11 frames\n"
885 " -n|--num <uint> Number of packets until exit\n"
886 " `-- 0 Loop until interrupted (default)\n"
887 " `- n Send n packets and done\n"
888 "Options for printing:\n"
889 " -s|--silent Do not print captured packets\n"
890 " -q|--less Print less-verbose packet information\n"
891 " -X|--hex Print packet data in hex format\n"
892 " -l|--ascii Print human-readable packet data\n"
893 "Options, advanced:\n"
894 " -r|--rand Randomize packet forwarding order\n"
895 " -M|--no-promisc No promiscuous mode for netdev\n"
896 " -A|--no-sock-mem Don't tune core socket memory\n"
897 " -m|--mmap Mmap pcap file i.e., for replaying\n"
898 " -g|--sg Scatter/gather pcap file I/O\n"
899 " -c|--clrw Use slower read(2)/write(2) I/O\n"
900 " -S|--ring-size <size> Manually set ring size to <size>:\n"
901 " mmap space in KB/MB/GB, e.g. \'10MB\'\n"
902 " -k|--kernel-pull <uint> Kernel pull from user interval in us\n"
903 " Default is 10us where the TX_RING\n"
904 " is populated with payload from uspace\n"
905 " -b|--bind-cpu <cpu> Bind to specific CPU (or CPU-range)\n"
906 " -B|--unbind-cpu <cpu> Forbid to use specific CPU (or CPU-range)\n"
907 " -H|--prio-high Make this high priority process\n"
908 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
909 " -v|--version Show version\n"
910 " -h|--help Guess what?!\n\n"
911 "Examples:\n"
912 " netsniff-ng --in eth0 --out dump.pcap --silent --bind-cpu 0\n"
913 " netsniff-ng --in wlan0 --rfraw --out dump.pcap --silent --bind-cpu 0\n"
914 " netsniff-ng --in dump.pcap --mmap --out eth0 --silent --bind-cpu 0\n"
915 " netsniff-ng --in dump.pcap --out dump.txf --silent --bind-cpu 0\n"
916 " netsniff-ng --in eth0 --out eth1 --silent --bind-cpu 0 --type host\n"
917 " netsniff-ng --in eth1 --out /opt/probe1/ -s -m -J --interval 30 -b 0\n"
918 " netsniff-ng --in any --filter http.bpf --jumbo-support --ascii\n\n"
919 "Note:\n"
920 " This tool is targeted for network developers! You should\n"
921 " be aware of what you are doing and what these options above\n"
922 " mean! Use netsniff-ng's bpfc compiler for generating filter files.\n"
923 " Further, netsniff-ng automatically enables the kernel BPF JIT\n"
924 " if present. Txf file output is only possible if the input source\n"
925 " is a pcap file.\n\n"
926 "Please report bugs to <bugs@netsniff-ng.org>\n"
927 "Copyright (C) 2009-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n"
928 "Copyright (C) 2009-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n"
929 "Copyright (C) 2012 Markus Amend <markus@netsniff-ng.org>\n"
930 "License: GNU GPL version 2.0\n"
931 "This is free software: you are free to change and redistribute it.\n"
932 "There is NO WARRANTY, to the extent permitted by law.\n");
933 die();
936 static void version(void)
938 printf("\n%s %s, the packet sniffing beast\n",
939 PROGNAME_STRING, VERSION_STRING);
940 puts("http://www.netsniff-ng.org\n\n"
941 "Please report bugs to <bugs@netsniff-ng.org>\n"
942 "Copyright (C) 2009-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n"
943 "Copyright (C) 2009-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n"
944 "Copyright (C) 2012 Markus Amend <markus@netsniff-ng.org>\n"
945 "License: GNU GPL version 2.0\n"
946 "This is free software: you are free to change and redistribute it.\n"
947 "There is NO WARRANTY, to the extent permitted by law.\n");
948 die();
951 static void header(void)
953 printf("%s%s%s\n", colorize_start(bold), PROGNAME_STRING " "
954 VERSION_STRING, colorize_end());
957 int main(int argc, char **argv)
959 int c, i, j, opt_index, ops_touched = 0;
960 int vals[4] = {0};
961 char *ptr;
962 bool prio_high = false;
963 bool setsockmem = true;
964 struct mode mode;
965 void (*enter_mode)(struct mode *mode) = NULL;
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;