docs: add Sibir as author
[netsniff-ng.git] / src / netsniff-ng.c
blob23b4091fbc1f1c97810a131f0333c8345f986531
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 DUMP_INTERVAL_DEF 60
55 enum dump_mode {
56 DUMP_INTERVAL_TIME,
57 DUMP_INTERVAL_SIZE,
60 struct mode {
61 char *device_in, *device_out, *device_trans, *filter, *prefix;
62 #define CPU_UNKNOWN -1
63 #define CPU_NOTOUCH -2
64 int cpu, rfraw, dump, print_mode, dump_dir, jumbo_support;
65 #define PACKET_ALL -1
66 int packet_type;
67 uint32_t link_type;
68 bool randomize, promiscuous;
69 enum pcap_ops_groups pcap;
70 unsigned long kpull, dump_interval, reserve_size;
71 enum dump_mode dump_mode;
74 struct tx_stats {
75 unsigned long tx_bytes;
76 unsigned long tx_packets;
79 volatile sig_atomic_t sigint = 0;
80 static int tx_sock;
81 static unsigned long frame_cnt_max = 0, interval = TX_KERNEL_PULL_INT;
82 static struct itimerval itimer;
83 static volatile bool next_dump = false;
85 static const char *short_options = "d:i:o:rf:MJt:S:k:n:b:B:HQmcsqXlvhF:RgAP:";
86 static const struct option long_options[] = {
87 {"dev", required_argument, NULL, 'd'},
88 {"in", required_argument, NULL, 'i'},
89 {"out", required_argument, NULL, 'o'},
90 {"filter", required_argument, NULL, 'f'},
91 {"num", required_argument, NULL, 'n'},
92 {"type", required_argument, NULL, 't'},
93 {"interval", required_argument, NULL, 'F'},
94 {"ring-size", required_argument, NULL, 'S'},
95 {"kernel-pull", required_argument, NULL, 'k'},
96 {"bind-cpu", required_argument, NULL, 'b'},
97 {"unbind-cpu", required_argument, NULL, 'B'},
98 {"prefix", required_argument, NULL, 'P'},
99 {"rand", no_argument, NULL, 'r'},
100 {"rfraw", no_argument, NULL, 'R'},
101 {"mmap", no_argument, NULL, 'm'},
102 {"sg", no_argument, NULL, 'g'},
103 {"clrw", no_argument, NULL, 'c'},
104 {"jumbo-support", no_argument, NULL, 'J'},
105 {"no-promisc", no_argument, NULL, 'M'},
106 {"prio-high", no_argument, NULL, 'H'},
107 {"notouch-irq", no_argument, NULL, 'Q'},
108 {"silent", no_argument, NULL, 's'},
109 {"less", no_argument, NULL, 'q'},
110 {"hex", no_argument, NULL, 'X'},
111 {"ascii", no_argument, NULL, 'l'},
112 {"no-sock-mem", no_argument, NULL, 'A'},
113 {"version", no_argument, NULL, 'v'},
114 {"help", no_argument, NULL, 'h'},
115 {NULL, 0, NULL, 0}
118 static void signal_handler(int number)
120 switch (number) {
121 case SIGINT:
122 sigint = 1;
123 break;
124 case SIGHUP:
125 break;
126 default:
127 break;
131 static void timer_elapsed(int number)
133 itimer.it_interval.tv_sec = 0;
134 itimer.it_interval.tv_usec = interval;
135 itimer.it_value.tv_sec = 0;
136 itimer.it_value.tv_usec = interval;
138 pull_and_flush_tx_ring(tx_sock);
139 setitimer(ITIMER_REAL, &itimer, NULL);
142 static void timer_next_dump(int number)
144 itimer.it_interval.tv_sec = interval;
145 itimer.it_interval.tv_usec = 0;
146 itimer.it_value.tv_sec = interval;
147 itimer.it_value.tv_usec = 0;
149 next_dump = true;
150 setitimer(ITIMER_REAL, &itimer, NULL);
153 static void enter_mode_pcap_to_tx(struct mode *mode)
155 int irq, ifindex, fd = 0, ret;
156 unsigned int size, it = 0;
157 struct ring tx_ring;
158 struct frame_map *hdr;
159 struct sock_fprog bpf_ops;
160 struct tx_stats stats;
161 uint8_t *out = NULL;
162 unsigned long trunced = 0;
163 struct timeval start, end, diff;
165 if (!device_up_and_running(mode->device_out) &&
166 !mode->rfraw)
167 panic("Device not up and running!\n");
169 tx_sock = pf_socket();
171 if (!pcap_ops[mode->pcap])
172 panic("pcap group not supported!\n");
173 fd = open_or_die(mode->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
174 ret = pcap_ops[mode->pcap]->pull_file_header(fd, &mode->link_type);
175 if (ret)
176 panic("error reading pcap header!\n");
177 if (pcap_ops[mode->pcap]->prepare_reading_pcap) {
178 ret = pcap_ops[mode->pcap]->prepare_reading_pcap(fd);
179 if (ret)
180 panic("error prepare reading pcap!\n");
183 fmemset(&tx_ring, 0, sizeof(tx_ring));
184 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
185 fmemset(&stats, 0, sizeof(stats));
187 if (mode->rfraw) {
188 mode->device_trans = xstrdup(mode->device_out);
189 xfree(mode->device_out);
191 enter_rfmon_mac80211(mode->device_trans, &mode->device_out);
192 if (mode->link_type != LINKTYPE_IEEE802_11)
193 panic("Wrong linktype of pcap!\n");
196 ifindex = device_ifindex(mode->device_out);
197 size = ring_size(mode->device_out, mode->reserve_size);
199 bpf_parse_rules(mode->filter, &bpf_ops);
201 set_packet_loss_discard(tx_sock);
202 set_sockopt_hwtimestamp(tx_sock, mode->device_out);
203 setup_tx_ring_layout(tx_sock, &tx_ring, size, mode->jumbo_support);
204 create_tx_ring(tx_sock, &tx_ring);
205 mmap_tx_ring(tx_sock, &tx_ring);
206 alloc_tx_ring_frames(&tx_ring);
207 bind_tx_ring(tx_sock, &tx_ring, ifindex);
209 dissector_init_all(mode->print_mode);
211 if (mode->cpu >= 0 && ifindex > 0) {
212 irq = device_irq_number(mode->device_out);
213 device_bind_irq_to_cpu(mode->cpu, irq);
214 printf("IRQ: %s:%d > CPU%d\n", mode->device_out, irq,
215 mode->cpu);
218 if (mode->kpull)
219 interval = mode->kpull;
221 itimer.it_interval.tv_sec = 0;
222 itimer.it_interval.tv_usec = interval;
223 itimer.it_value.tv_sec = 0;
224 itimer.it_value.tv_usec = interval;
225 setitimer(ITIMER_REAL, &itimer, NULL);
227 printf("BPF:\n");
228 bpf_dump_all(&bpf_ops);
229 printf("MD: TX %luus %s ", interval, pcap_ops[mode->pcap]->name);
230 if (mode->rfraw)
231 printf("802.11 raw via %s ", mode->device_out);
232 #ifdef _LARGEFILE64_SOURCE
233 printf("lf64 ");
234 #endif
235 ioprio_print();
236 printf("\n");
238 bug_on(gettimeofday(&start, NULL));
240 while (likely(sigint == 0)) {
241 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
242 struct pcap_pkthdr phdr;
243 hdr = tx_ring.frames[it].iov_base;
244 /* Kernel assumes: data = ph.raw + po->tp_hdrlen -
245 * sizeof(struct sockaddr_ll); */
246 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN -
247 sizeof(struct sockaddr_ll);
249 do {
250 memset(&phdr, 0, sizeof(phdr));
251 ret = pcap_ops[mode->pcap]->read_pcap_pkt(fd, &phdr,
252 out, ring_frame_size(&tx_ring));
253 if (unlikely(ret <= 0))
254 goto out;
255 if (ring_frame_size(&tx_ring) < phdr.len) {
256 phdr.len = ring_frame_size(&tx_ring);
257 trunced++;
259 } while (mode->filter && !bpf_run_filter(&bpf_ops, out, phdr.len));
260 pcap_pkthdr_to_tpacket_hdr(&phdr, &hdr->tp_h);
262 stats.tx_bytes += hdr->tp_h.tp_len;;
263 stats.tx_packets++;
265 show_frame_hdr(hdr, mode->print_mode, RING_MODE_EGRESS);
266 dissector_entry_point(out, hdr->tp_h.tp_snaplen,
267 mode->link_type, mode->print_mode);
269 kernel_may_pull_from_tx(&hdr->tp_h);
270 next_slot_prewr(&it, &tx_ring);
272 if (unlikely(sigint == 1))
273 break;
274 if (frame_cnt_max != 0 &&
275 stats.tx_packets >= frame_cnt_max) {
276 sigint = 1;
277 break;
281 out:
282 bug_on(gettimeofday(&end, NULL));
283 diff = tv_subtract(end, start);
285 fflush(stdout);
286 printf("\n");
287 printf("\r%12lu frames outgoing\n", stats.tx_packets);
288 printf("\r%12lu frames truncated (larger than frame)\n", trunced);
289 printf("\r%12lu bytes outgoing\n", stats.tx_bytes);
290 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
292 bpf_release(&bpf_ops);
293 dissector_cleanup_all();
294 destroy_tx_ring(tx_sock, &tx_ring);
296 if (mode->rfraw)
297 leave_rfmon_mac80211(mode->device_trans, mode->device_out);
299 close(tx_sock);
300 if (pcap_ops[mode->pcap]->prepare_close_pcap)
301 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_READ);
302 close(fd);
305 static void enter_mode_rx_to_tx(struct mode *mode)
307 int rx_sock, ifindex_in, ifindex_out;
308 unsigned int size_in, size_out, it_in = 0, it_out = 0;
309 unsigned long fcnt = 0;
310 uint8_t *in, *out;
311 short ifflags = 0;
312 struct frame_map *hdr_in, *hdr_out;
313 struct ring tx_ring;
314 struct ring rx_ring;
315 struct pollfd rx_poll;
316 struct sock_fprog bpf_ops;
318 if (!strncmp(mode->device_in, mode->device_out,
319 strlen(mode->device_in)))
320 panic("Ingress/egress devices must be different!\n");
321 if (!device_up_and_running(mode->device_out))
322 panic("Egress device not up and running!\n");
323 if (!device_up_and_running(mode->device_in))
324 panic("Ingress device not up and running!\n");
326 rx_sock = pf_socket();
327 tx_sock = pf_socket();
329 fmemset(&tx_ring, 0, sizeof(tx_ring));
330 fmemset(&rx_ring, 0, sizeof(rx_ring));
331 fmemset(&rx_poll, 0, sizeof(rx_poll));
332 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
334 ifindex_in = device_ifindex(mode->device_in);
335 size_in = ring_size(mode->device_in, mode->reserve_size);
337 ifindex_out = device_ifindex(mode->device_out);
338 size_out = ring_size(mode->device_out, mode->reserve_size);
340 enable_kernel_bpf_jit_compiler();
341 bpf_parse_rules(mode->filter, &bpf_ops);
342 bpf_attach_to_sock(rx_sock, &bpf_ops);
344 setup_rx_ring_layout(rx_sock, &rx_ring, size_in, mode->jumbo_support);
345 create_rx_ring(rx_sock, &rx_ring);
346 mmap_rx_ring(rx_sock, &rx_ring);
347 alloc_rx_ring_frames(&rx_ring);
348 bind_rx_ring(rx_sock, &rx_ring, ifindex_in);
349 prepare_polling(rx_sock, &rx_poll);
351 set_packet_loss_discard(tx_sock);
352 setup_tx_ring_layout(tx_sock, &tx_ring, size_out, mode->jumbo_support);
353 create_tx_ring(tx_sock, &tx_ring);
354 mmap_tx_ring(tx_sock, &tx_ring);
355 alloc_tx_ring_frames(&tx_ring);
356 bind_tx_ring(tx_sock, &tx_ring, ifindex_out);
358 mt_init_by_seed_time();
359 dissector_init_all(mode->print_mode);
361 if (mode->promiscuous == true) {
362 ifflags = enter_promiscuous_mode(mode->device_in);
363 printf("PROMISC\n");
366 if (mode->kpull)
367 interval = mode->kpull;
369 itimer.it_interval.tv_sec = 0;
370 itimer.it_interval.tv_usec = interval;
371 itimer.it_value.tv_sec = 0;
372 itimer.it_value.tv_usec = interval;
373 setitimer(ITIMER_REAL, &itimer, NULL);
375 printf("BPF:\n");
376 bpf_dump_all(&bpf_ops);
377 printf("MD: RXTX %luus\n\n", interval);
378 printf("Running! Hang up with ^C!\n\n");
380 while (likely(sigint == 0)) {
381 while (user_may_pull_from_rx(rx_ring.frames[it_in].iov_base)) {
382 hdr_in = rx_ring.frames[it_in].iov_base;
383 in = ((uint8_t *) hdr_in) + hdr_in->tp_h.tp_mac;
384 fcnt++;
385 if (mode->packet_type != PACKET_ALL)
386 if (mode->packet_type != hdr_in->s_ll.sll_pkttype)
387 goto next;
389 hdr_out = tx_ring.frames[it_out].iov_base;
390 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN -
391 sizeof(struct sockaddr_ll);
393 for (; !user_may_pull_from_tx(tx_ring.frames[it_out].iov_base) &&
394 likely(!sigint);) {
395 if (mode->randomize)
396 next_rnd_slot(&it_out, &tx_ring);
397 else
398 next_slot(&it_out, &tx_ring);
399 hdr_out = tx_ring.frames[it_out].iov_base;
400 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN -
401 sizeof(struct sockaddr_ll);
404 tpacket_hdr_clone(&hdr_out->tp_h, &hdr_in->tp_h);
405 fmemcpy(out, in, hdr_in->tp_h.tp_len);
407 kernel_may_pull_from_tx(&hdr_out->tp_h);
408 if (mode->randomize)
409 next_rnd_slot(&it_out, &tx_ring);
410 else
411 next_slot(&it_out, &tx_ring);
413 show_frame_hdr(hdr_in, mode->print_mode, RING_MODE_INGRESS);
414 dissector_entry_point(in, hdr_in->tp_h.tp_snaplen,
415 mode->link_type, mode->print_mode);
417 if (frame_cnt_max != 0 && fcnt >= frame_cnt_max) {
418 sigint = 1;
419 break;
421 next:
422 kernel_may_pull_from_rx(&hdr_in->tp_h);
423 next_slot(&it_in, &rx_ring);
425 if (unlikely(sigint == 1))
426 goto out;
429 poll(&rx_poll, 1, -1);
430 poll_error_maybe_die(rx_sock, &rx_poll);
432 out:
433 sock_print_net_stats(rx_sock, 0);
435 bpf_release(&bpf_ops);
436 dissector_cleanup_all();
437 destroy_tx_ring(tx_sock, &tx_ring);
438 destroy_rx_ring(rx_sock, &rx_ring);
440 if (mode->promiscuous == true)
441 leave_promiscuous_mode(mode->device_in, ifflags);
443 close(tx_sock);
444 close(rx_sock);
447 static void enter_mode_read_pcap(struct mode *mode)
449 int ret, fd, fdo = 0;
450 struct pcap_pkthdr phdr;
451 struct sock_fprog bpf_ops;
452 struct tx_stats stats;
453 struct frame_map fm;
454 uint8_t *out;
455 size_t out_len;
456 unsigned long trunced = 0;
457 struct timeval start, end, diff;
459 if (!pcap_ops[mode->pcap])
460 panic("pcap group not supported!\n");
461 fd = open_or_die(mode->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
462 ret = pcap_ops[mode->pcap]->pull_file_header(fd, &mode->link_type);
463 if (ret)
464 panic("error reading pcap header!\n");
465 if (pcap_ops[mode->pcap]->prepare_reading_pcap) {
466 ret = pcap_ops[mode->pcap]->prepare_reading_pcap(fd);
467 if (ret)
468 panic("error prepare reading pcap!\n");
471 fmemset(&fm, 0, sizeof(fm));
472 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
473 fmemset(&stats, 0, sizeof(stats));
475 bpf_parse_rules(mode->filter, &bpf_ops);
476 dissector_init_all(mode->print_mode);
478 out_len = 64 * 1024;
479 out = xmalloc_aligned(out_len, CO_CACHE_LINE_SIZE);
481 printf("BPF:\n");
482 bpf_dump_all(&bpf_ops);
483 printf("MD: RD %s ", pcap_ops[mode->pcap]->name);
484 #ifdef _LARGEFILE64_SOURCE
485 printf("lf64 ");
486 #endif
487 ioprio_print();
488 printf("\n");
490 if (mode->device_out) {
491 fdo = open_or_die_m(mode->device_out, O_RDWR | O_CREAT |
492 O_TRUNC | O_LARGEFILE, DEFFILEMODE);
495 bug_on(gettimeofday(&start, NULL));
497 while (likely(sigint == 0)) {
498 do {
499 memset(&phdr, 0, sizeof(phdr));
500 ret = pcap_ops[mode->pcap]->read_pcap_pkt(fd, &phdr,
501 out, out_len);
502 if (unlikely(ret < 0))
503 goto out;
504 if (unlikely(phdr.len == 0)) {
505 trunced++;
506 continue;
508 if (unlikely(phdr.len > out_len)) {
509 phdr.len = out_len;
510 trunced++;
512 } while (mode->filter &&
513 !bpf_run_filter(&bpf_ops, out, phdr.len));
515 pcap_pkthdr_to_tpacket_hdr(&phdr, &fm.tp_h);
517 stats.tx_bytes += fm.tp_h.tp_len;
518 stats.tx_packets++;
520 show_frame_hdr(&fm, mode->print_mode, RING_MODE_EGRESS);
521 dissector_entry_point(out, fm.tp_h.tp_snaplen,
522 mode->link_type, mode->print_mode);
524 if (mode->device_out) {
525 int i = 0;
526 char bout[80];
527 slprintf(bout, sizeof(bout), "{\n ");
528 write_or_die(fdo, bout, strlen(bout));
530 while (i < fm.tp_h.tp_snaplen) {
531 slprintf(bout, sizeof(bout), "0x%02x, ", out[i]);
532 write_or_die(fdo, bout, strlen(bout));
533 i++;
534 if (i % 10 == 0) {
535 slprintf(bout, sizeof(bout), "\n", out[i]);
536 write_or_die(fdo, bout, strlen(bout));
537 if (i < fm.tp_h.tp_snaplen) {
538 slprintf(bout, sizeof(bout), " ", out[i]);
539 write_or_die(fdo, bout, strlen(bout));
543 if (i % 10 != 0) {
544 slprintf(bout, sizeof(bout), "\n");
545 write_or_die(fdo, bout, strlen(bout));
547 slprintf(bout, sizeof(bout), "}\n\n");
548 write_or_die(fdo, bout, strlen(bout));
551 if (frame_cnt_max != 0 &&
552 stats.tx_packets >= frame_cnt_max) {
553 sigint = 1;
554 break;
557 out:
558 bug_on(gettimeofday(&end, NULL));
559 diff = tv_subtract(end, start);
561 fflush(stdout);
562 printf("\n");
563 printf("\r%12lu frames outgoing\n", stats.tx_packets);
564 printf("\r%12lu frames truncated (larger than mtu)\n", trunced);
565 printf("\r%12lu bytes outgoing\n", stats.tx_bytes);
566 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
568 xfree(out);
570 bpf_release(&bpf_ops);
571 dissector_cleanup_all();
572 if (pcap_ops[mode->pcap]->prepare_close_pcap)
573 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_READ);
574 close(fd);
576 if (mode->device_out)
577 close(fdo);
580 static void finish_multi_pcap_file(struct mode *mode, int fd)
582 pcap_ops[mode->pcap]->fsync_pcap(fd);
583 if (pcap_ops[mode->pcap]->prepare_close_pcap)
584 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_WRITE);
585 close(fd);
587 fmemset(&itimer, 0, sizeof(itimer));
588 setitimer(ITIMER_REAL, &itimer, NULL);
591 static int next_multi_pcap_file(struct mode *mode, int fd)
593 int ret;
594 char tmp[512];
596 pcap_ops[mode->pcap]->fsync_pcap(fd);
597 if (pcap_ops[mode->pcap]->prepare_close_pcap)
598 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_WRITE);
599 close(fd);
601 slprintf(tmp, sizeof(tmp), "%s/%s%lu.pcap",
602 mode->device_out, mode->prefix ? : "dump-", time(0));
604 fd = open_or_die_m(tmp, O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE,
605 DEFFILEMODE);
606 ret = pcap_ops[mode->pcap]->push_file_header(fd, mode->link_type);
607 if (ret)
608 panic("error writing pcap header!\n");
609 if (pcap_ops[mode->pcap]->prepare_writing_pcap) {
610 ret = pcap_ops[mode->pcap]->prepare_writing_pcap(fd);
611 if (ret)
612 panic("error prepare writing pcap!\n");
615 return fd;
618 static int begin_multi_pcap_file(struct mode *mode)
620 int fd, ret;
621 char tmp[512];
623 if (!pcap_ops[mode->pcap])
624 panic("pcap group not supported!\n");
625 if (mode->device_out[strlen(mode->device_out) - 1] == '/')
626 mode->device_out[strlen(mode->device_out) - 1] = 0;
628 slprintf(tmp, sizeof(tmp), "%s/%s%lu.pcap",
629 mode->device_out, mode->prefix ? : "dump-", time(0));
631 fd = open_or_die_m(tmp, O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE,
632 DEFFILEMODE);
633 ret = pcap_ops[mode->pcap]->push_file_header(fd, mode->link_type);
634 if (ret)
635 panic("error writing pcap header!\n");
636 if (pcap_ops[mode->pcap]->prepare_writing_pcap) {
637 ret = pcap_ops[mode->pcap]->prepare_writing_pcap(fd);
638 if (ret)
639 panic("error prepare writing pcap!\n");
642 if (mode->dump_mode == DUMP_INTERVAL_TIME) {
643 interval = mode->dump_interval;
645 itimer.it_interval.tv_sec = interval;
646 itimer.it_interval.tv_usec = 0;
647 itimer.it_value.tv_sec = interval;
648 itimer.it_value.tv_usec = 0;
650 setitimer(ITIMER_REAL, &itimer, NULL);
651 } else {
652 interval = 0;
655 return fd;
658 static void finish_single_pcap_file(struct mode *mode, int fd)
660 pcap_ops[mode->pcap]->fsync_pcap(fd);
661 if (pcap_ops[mode->pcap]->prepare_close_pcap)
662 pcap_ops[mode->pcap]->prepare_close_pcap(fd, PCAP_MODE_WRITE);
663 close(fd);
666 static int begin_single_pcap_file(struct mode *mode)
668 int fd, ret;
670 if (!pcap_ops[mode->pcap])
671 panic("pcap group not supported!\n");
672 fd = open_or_die_m(mode->device_out,
673 O_RDWR | O_CREAT | O_TRUNC | O_LARGEFILE,
674 DEFFILEMODE);
675 ret = pcap_ops[mode->pcap]->push_file_header(fd, mode->link_type);
676 if (ret)
677 panic("error writing pcap header!\n");
678 if (pcap_ops[mode->pcap]->prepare_writing_pcap) {
679 ret = pcap_ops[mode->pcap]->prepare_writing_pcap(fd);
680 if (ret)
681 panic("error prepare writing pcap!\n");
684 return fd;
687 static void enter_mode_rx_only_or_dump(struct mode *mode)
689 int sock, irq, ifindex, fd = 0, ret;
690 unsigned int size, it = 0;
691 unsigned long fcnt = 0, skipped = 0;
692 short ifflags = 0;
693 uint8_t *packet;
694 struct ring rx_ring;
695 struct pollfd rx_poll;
696 struct frame_map *hdr;
697 struct sock_fprog bpf_ops;
698 struct timeval start, end, diff;
700 if (!device_up_and_running(mode->device_in) &&
701 !mode->rfraw)
702 panic("Device not up and running!\n");
704 sock = pf_socket();
706 if (mode->rfraw) {
707 mode->device_trans = xstrdup(mode->device_in);
708 xfree(mode->device_in);
710 enter_rfmon_mac80211(mode->device_trans, &mode->device_in);
711 mode->link_type = LINKTYPE_IEEE802_11;
714 if (mode->dump) {
715 struct stat tmp;
716 fmemset(&tmp, 0, sizeof(tmp));
717 ret = stat(mode->device_out, &tmp);
718 if (ret < 0) {
719 mode->dump_dir = 0;
720 goto try_file;
722 mode->dump_dir = !!S_ISDIR(tmp.st_mode);
723 if (mode->dump_dir) {
724 fd = begin_multi_pcap_file(mode);
725 } else {
726 try_file:
727 fd = begin_single_pcap_file(mode);
731 fmemset(&rx_ring, 0, sizeof(rx_ring));
732 fmemset(&rx_poll, 0, sizeof(rx_poll));
733 fmemset(&bpf_ops, 0, sizeof(bpf_ops));
735 ifindex = device_ifindex(mode->device_in);
736 size = ring_size(mode->device_in, mode->reserve_size);
738 enable_kernel_bpf_jit_compiler();
739 bpf_parse_rules(mode->filter, &bpf_ops);
740 bpf_attach_to_sock(sock, &bpf_ops);
742 set_sockopt_hwtimestamp(sock, mode->device_in);
743 setup_rx_ring_layout(sock, &rx_ring, size, mode->jumbo_support);
744 create_rx_ring(sock, &rx_ring);
745 mmap_rx_ring(sock, &rx_ring);
746 alloc_rx_ring_frames(&rx_ring);
747 bind_rx_ring(sock, &rx_ring, ifindex);
749 prepare_polling(sock, &rx_poll);
750 dissector_init_all(mode->print_mode);
752 if (mode->cpu >= 0 && ifindex > 0) {
753 irq = device_irq_number(mode->device_in);
754 device_bind_irq_to_cpu(mode->cpu, irq);
755 printf("IRQ: %s:%d > CPU%d\n", mode->device_in, irq,
756 mode->cpu);
759 if (mode->promiscuous == true) {
760 ifflags = enter_promiscuous_mode(mode->device_in);
761 printf("PROMISC\n");
764 printf("BPF:\n");
765 bpf_dump_all(&bpf_ops);
766 printf("MD: RX %s ", mode->dump ? pcap_ops[mode->pcap]->name : "");
767 if (mode->rfraw)
768 printf("802.11 raw via %s ", mode->device_in);
769 #ifdef _LARGEFILE64_SOURCE
770 printf("lf64 ");
771 #endif
772 ioprio_print();
773 printf("\n");
775 bug_on(gettimeofday(&start, NULL));
777 while (likely(sigint == 0)) {
778 while (user_may_pull_from_rx(rx_ring.frames[it].iov_base)) {
779 hdr = rx_ring.frames[it].iov_base;
780 packet = ((uint8_t *) hdr) + hdr->tp_h.tp_mac;
781 fcnt++;
783 if (mode->packet_type != PACKET_ALL)
784 if (mode->packet_type != hdr->s_ll.sll_pkttype)
785 goto next;
786 if (unlikely(ring_frame_size(&rx_ring) <
787 hdr->tp_h.tp_snaplen)) {
788 skipped++;
789 goto next;
791 if (mode->dump) {
792 struct pcap_pkthdr phdr;
793 tpacket_hdr_to_pcap_pkthdr(&hdr->tp_h, &phdr);
794 ret = pcap_ops[mode->pcap]->write_pcap_pkt(fd, &phdr,
795 packet, phdr.len);
796 if (unlikely(ret != sizeof(phdr) + phdr.len))
797 panic("Write error to pcap!\n");
800 show_frame_hdr(hdr, mode->print_mode, RING_MODE_INGRESS);
801 dissector_entry_point(packet, hdr->tp_h.tp_snaplen,
802 mode->link_type, mode->print_mode);
804 if (frame_cnt_max != 0 && fcnt >= frame_cnt_max) {
805 sigint = 1;
806 break;
808 next:
809 kernel_may_pull_from_rx(&hdr->tp_h);
810 next_slot_prerd(&it, &rx_ring);
812 if (unlikely(sigint == 1))
813 break;
815 if (mode->dump) {
816 if (mode->dump_mode == DUMP_INTERVAL_SIZE) {
817 interval += hdr->tp_h.tp_snaplen;
818 if (interval > mode->dump_interval) {
819 next_dump = true;
820 interval = 0;
824 if (next_dump) {
825 struct tpacket_stats kstats;
826 socklen_t slen = sizeof(kstats);
828 fmemset(&kstats, 0, sizeof(kstats));
829 getsockopt(sock, SOL_PACKET, PACKET_STATISTICS,
830 &kstats, &slen);
832 fd = next_multi_pcap_file(mode, fd);
833 next_dump = false;
835 if (mode->print_mode == FNTTYPE_PRINT_NONE) {
836 printf(".(+%lu/-%lu)",
837 1UL * kstats.tp_packets -
838 kstats.tp_drops -
839 skipped, 1UL * kstats.tp_drops +
840 skipped);
841 fflush(stdout);
847 poll(&rx_poll, 1, -1);
848 poll_error_maybe_die(sock, &rx_poll);
851 bug_on(gettimeofday(&end, NULL));
852 diff = tv_subtract(end, start);
854 if (!(mode->dump_dir && mode->print_mode == FNTTYPE_PRINT_NONE)) {
855 sock_print_net_stats(sock, skipped);
856 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec,
857 diff.tv_usec);
858 } else {
859 printf("\n\n");
860 fflush(stdout);
863 bpf_release(&bpf_ops);
864 dissector_cleanup_all();
865 destroy_rx_ring(sock, &rx_ring);
867 if (mode->promiscuous == true)
868 leave_promiscuous_mode(mode->device_in, ifflags);
870 if (mode->rfraw)
871 leave_rfmon_mac80211(mode->device_trans, mode->device_in);
873 close(sock);
875 if (mode->dump) {
876 if (mode->dump_dir)
877 finish_multi_pcap_file(mode, fd);
878 else
879 finish_single_pcap_file(mode, fd);
883 static void help(void)
885 printf("\nnetsniff-ng %s, the packet sniffing beast\n", VERSION_STRING);
886 puts("http://www.netsniff-ng.org\n\n"
887 "Usage: netsniff-ng [options]\n"
888 "Options:\n"
889 " -i|-d|--dev|--in <dev|pcap> Input source as netdev or pcap\n"
890 " -o|--out <dev|pcap|dir|txf> Output sink as netdev, pcap, directory, txf file\n"
891 " -f|--filter <bpf-file> Use BPF filter file from bpfc\n"
892 " -t|--type <type> Only handle packets of defined type:\n"
893 " host|broadcast|multicast|others|outgoing\n"
894 " -F|--interval <size/time> Dump interval in time or size if -o is a directory\n"
895 " pcap swap spec: <num>KiB/MiB/GiB/s/sec/min/hrs\n"
896 " -J|--jumbo-support Support for 64KB Super Jumbo Frames\n"
897 " Default RX/TX slot: 2048Byte\n"
898 " -R|--rfraw Capture or inject raw 802.11 frames\n"
899 " -n|--num <uint> Number of packets until exit\n"
900 " `-- 0 Loop until interrupted (default)\n"
901 " `- n Send n packets and done\n"
902 "Options for printing:\n"
903 " -s|--silent Do not print captured packets\n"
904 " -q|--less Print less-verbose packet information\n"
905 " -X|--hex Print packet data in hex format\n"
906 " -l|--ascii Print human-readable packet data\n"
907 "Options, advanced:\n"
908 " -P|--prefix <name> Prefix for pcaps stored in directory\n"
909 " -r|--rand Randomize packet forwarding order\n"
910 " -M|--no-promisc No promiscuous mode for netdev\n"
911 " -A|--no-sock-mem Don't tune core socket memory\n"
912 " -m|--mmap Mmap pcap file i.e., for replaying\n"
913 " -g|--sg Scatter/gather pcap file I/O\n"
914 " -c|--clrw Use slower read(2)/write(2) I/O\n"
915 " -S|--ring-size <size> Manually set ring size to <size>:\n"
916 " mmap space in KiB/MiB/GiB, e.g. \'10MiB\'\n"
917 " -k|--kernel-pull <uint> Kernel pull from user interval in us\n"
918 " Default is 10us where the TX_RING\n"
919 " is populated with payload from uspace\n"
920 " -b|--bind-cpu <cpu> Bind to specific CPU (or CPU-range)\n"
921 " -B|--unbind-cpu <cpu> Forbid to use specific CPU (or CPU-range)\n"
922 " -H|--prio-high Make this high priority process\n"
923 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
924 " -v|--version Show version\n"
925 " -h|--help Guess what?!\n\n"
926 "Examples:\n"
927 " netsniff-ng --in eth0 --out dump.pcap --silent --bind-cpu 0\n"
928 " netsniff-ng --in wlan0 --rfraw --out dump.pcap --silent --bind-cpu 0\n"
929 " netsniff-ng --in dump.pcap --mmap --out eth0 --silent --bind-cpu 0\n"
930 " netsniff-ng --in dump.pcap --out dump.txf --silent --bind-cpu 0\n"
931 " netsniff-ng --in eth0 --out eth1 --silent --bind-cpu 0 --type host\n"
932 " netsniff-ng --in eth1 --out /opt/probe/ -s -m -J --interval 100MiB -b 0\n"
933 " netsniff-ng --in any --filter http.bpf --jumbo-support --ascii\n\n"
934 "Note:\n"
935 " This tool is targeted for network developers! You should\n"
936 " be aware of what you are doing and what these options above\n"
937 " mean! Use netsniff-ng's bpfc compiler for generating filter files.\n"
938 " Further, netsniff-ng automatically enables the kernel BPF JIT\n"
939 " if present. Txf file output is only possible if the input source\n"
940 " is a pcap file.\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 version(void)
953 printf("\nnetsniff-ng %s, the packet sniffing beast\n", VERSION_STRING);
954 puts("http://www.netsniff-ng.org\n\n"
955 "Please report bugs to <bugs@netsniff-ng.org>\n"
956 "Copyright (C) 2009-2012 Daniel Borkmann <daniel@netsniff-ng.org>\n"
957 "Copyright (C) 2009-2012 Emmanuel Roullit <emmanuel@netsniff-ng.org>\n"
958 "Copyright (C) 2012 Markus Amend <markus@netsniff-ng.org>\n"
959 "License: GNU GPL version 2.0\n"
960 "This is free software: you are free to change and redistribute it.\n"
961 "There is NO WARRANTY, to the extent permitted by law.\n");
962 die();
965 static void header(void)
967 printf("%s%s%s\n",
968 colorize_start(bold),
969 "netsniff-ng " VERSION_STRING,
970 colorize_end());
973 int main(int argc, char **argv)
975 int c, i, j, opt_index, ops_touched = 0;
976 int vals[4] = {0};
977 char *ptr;
978 bool prio_high = false;
979 bool setsockmem = true;
980 struct mode mode;
981 void (*enter_mode)(struct mode *mode) = NULL;
983 fmemset(&mode, 0, sizeof(mode));
984 mode.link_type = LINKTYPE_EN10MB;
985 mode.print_mode = FNTTYPE_PRINT_NORM;
986 mode.cpu = CPU_UNKNOWN;
987 mode.packet_type = PACKET_ALL;
988 mode.promiscuous = true;
989 mode.randomize = false;
990 mode.pcap = PCAP_OPS_SG;
991 mode.dump_interval = DUMP_INTERVAL_DEF;
992 mode.dump_mode = DUMP_INTERVAL_TIME;
994 while ((c = getopt_long(argc, argv, short_options, long_options,
995 &opt_index)) != EOF) {
996 switch (c) {
997 case 'd':
998 case 'i':
999 mode.device_in = xstrdup(optarg);
1000 break;
1001 case 'o':
1002 mode.device_out = xstrdup(optarg);
1003 break;
1004 case 'P':
1005 mode.prefix = xstrdup(optarg);
1006 break;
1007 case 'R':
1008 mode.link_type = LINKTYPE_IEEE802_11;
1009 mode.rfraw = 1;
1010 break;
1011 case 'r':
1012 mode.randomize = true;
1013 break;
1014 case 'J':
1015 mode.jumbo_support = 1;
1016 break;
1017 case 'f':
1018 mode.filter = xstrdup(optarg);
1019 break;
1020 case 'M':
1021 mode.promiscuous = false;
1022 break;
1023 case 'A':
1024 setsockmem = false;
1025 break;
1026 case 't':
1027 if (!strncmp(optarg, "host", strlen("host")))
1028 mode.packet_type = PACKET_HOST;
1029 else if (!strncmp(optarg, "broadcast", strlen("broadcast")))
1030 mode.packet_type = PACKET_BROADCAST;
1031 else if (!strncmp(optarg, "multicast", strlen("multicast")))
1032 mode.packet_type = PACKET_MULTICAST;
1033 else if (!strncmp(optarg, "others", strlen("others")))
1034 mode.packet_type = PACKET_OTHERHOST;
1035 else if (!strncmp(optarg, "outgoing", strlen("outgoing")))
1036 mode.packet_type = PACKET_OUTGOING;
1037 else
1038 mode.packet_type = PACKET_ALL;
1039 break;
1040 case 'S':
1041 ptr = optarg;
1042 mode.reserve_size = 0;
1044 for (j = i = strlen(optarg); i > 0; --i) {
1045 if (!isdigit(optarg[j - i]))
1046 break;
1047 ptr++;
1050 if (!strncmp(ptr, "KiB", strlen("KiB")))
1051 mode.reserve_size = 1 << 10;
1052 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1053 mode.reserve_size = 1 << 20;
1054 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1055 mode.reserve_size = 1 << 30;
1056 else
1057 panic("Syntax error in ring size param!\n");
1059 *ptr = 0;
1060 mode.reserve_size *= atoi(optarg);
1061 break;
1062 case 'b':
1063 set_cpu_affinity(optarg, 0);
1064 if (mode.cpu != CPU_NOTOUCH)
1065 mode.cpu = atoi(optarg);
1066 break;
1067 case 'B':
1068 set_cpu_affinity(optarg, 1);
1069 break;
1070 case 'H':
1071 prio_high = true;
1072 break;
1073 case 'c':
1074 mode.pcap = PCAP_OPS_RW;
1075 ops_touched = 1;
1076 break;
1077 case 'm':
1078 mode.pcap = PCAP_OPS_MMAP;
1079 ops_touched = 1;
1080 break;
1081 case 'g':
1082 mode.pcap = PCAP_OPS_SG;
1083 ops_touched = 1;
1084 break;
1085 case 'Q':
1086 mode.cpu = CPU_NOTOUCH;
1087 break;
1088 case 's':
1089 mode.print_mode = FNTTYPE_PRINT_NONE;
1090 break;
1091 case 'q':
1092 mode.print_mode = FNTTYPE_PRINT_LESS;
1093 break;
1094 case 'X':
1095 mode.print_mode = (mode.print_mode == FNTTYPE_PRINT_ASCII) ?
1096 FNTTYPE_PRINT_HEX_ASCII : FNTTYPE_PRINT_HEX;
1097 break;
1098 case 'l':
1099 mode.print_mode = (mode.print_mode == FNTTYPE_PRINT_HEX) ?
1100 FNTTYPE_PRINT_HEX_ASCII : FNTTYPE_PRINT_ASCII;
1101 break;
1102 case 'k':
1103 mode.kpull = (unsigned long) atol(optarg);
1104 break;
1105 case 'n':
1106 frame_cnt_max = (unsigned long) atol(optarg);
1107 break;
1108 case 'F':
1109 ptr = optarg;
1110 mode.dump_interval = 0;
1112 for (j = i = strlen(optarg); i > 0; --i) {
1113 if (!isdigit(optarg[j - i]))
1114 break;
1115 ptr++;
1118 if (!strncmp(ptr, "KiB", strlen("KiB"))) {
1119 mode.dump_interval = 1 << 10;
1120 mode.dump_mode = DUMP_INTERVAL_SIZE;
1121 } else if (!strncmp(ptr, "MiB", strlen("MiB"))) {
1122 mode.dump_interval = 1 << 20;
1123 mode.dump_mode = DUMP_INTERVAL_SIZE;
1124 } else if (!strncmp(ptr, "GiB", strlen("GiB"))) {
1125 mode.dump_interval = 1 << 30;
1126 mode.dump_mode = DUMP_INTERVAL_SIZE;
1127 } else if (!strncmp(ptr, "sec", strlen("sec"))) {
1128 mode.dump_interval = 1;
1129 mode.dump_mode = DUMP_INTERVAL_TIME;
1130 } else if (!strncmp(ptr, "min", strlen("min"))) {
1131 mode.dump_interval = 60;
1132 mode.dump_mode = DUMP_INTERVAL_TIME;
1133 } else if (!strncmp(ptr, "hrs", strlen("hrs"))) {
1134 mode.dump_interval = 60 * 60;
1135 mode.dump_mode = DUMP_INTERVAL_TIME;
1136 } else if (!strncmp(ptr, "s", strlen("s"))) {
1137 mode.dump_interval = 1;
1138 mode.dump_mode = DUMP_INTERVAL_TIME;
1139 } else {
1140 panic("Syntax error in time/size param!\n");
1143 *ptr = 0;
1144 mode.dump_interval *= (unsigned long) atoi(optarg);
1145 break;
1146 case 'v':
1147 version();
1148 break;
1149 case 'h':
1150 help();
1151 break;
1152 case '?':
1153 switch (optopt) {
1154 case 'd':
1155 case 'i':
1156 case 'o':
1157 case 'f':
1158 case 't':
1159 case 'P':
1160 case 'F':
1161 case 'n':
1162 case 'S':
1163 case 'b':
1164 case 'k':
1165 case 'B':
1166 case 'e':
1167 panic("Option -%c requires an argument!\n",
1168 optopt);
1169 default:
1170 if (isprint(optopt))
1171 whine("Unknown option character "
1172 "`0x%X\'!\n", optopt);
1173 die();
1175 default:
1176 break;
1180 if (!mode.device_in)
1181 mode.device_in = xstrdup("any");
1183 register_signal(SIGINT, signal_handler);
1184 register_signal(SIGHUP, signal_handler);
1186 init_pcap(mode.jumbo_support);
1187 tprintf_init();
1188 header();
1190 if (prio_high == true) {
1191 set_proc_prio(get_default_proc_prio());
1192 set_sched_status(get_default_sched_policy(),
1193 get_default_sched_prio());
1196 if (setsockmem == true) {
1197 if ((vals[0] = get_system_socket_mem(sock_rmem_max)) < SMEM_SUG_MAX)
1198 set_system_socket_mem(sock_rmem_max, SMEM_SUG_MAX);
1199 if ((vals[1] = get_system_socket_mem(sock_rmem_def)) < SMEM_SUG_DEF)
1200 set_system_socket_mem(sock_rmem_def, SMEM_SUG_DEF);
1201 if ((vals[2] = get_system_socket_mem(sock_wmem_max)) < SMEM_SUG_MAX)
1202 set_system_socket_mem(sock_wmem_max, SMEM_SUG_MAX);
1203 if ((vals[3] = get_system_socket_mem(sock_wmem_def)) < SMEM_SUG_DEF)
1204 set_system_socket_mem(sock_wmem_def, SMEM_SUG_DEF);
1207 if (mode.device_in && (device_mtu(mode.device_in) ||
1208 !strncmp("any", mode.device_in, strlen(mode.device_in)))) {
1209 if (!mode.device_out) {
1210 mode.dump = 0;
1211 enter_mode = enter_mode_rx_only_or_dump;
1212 } else if (device_mtu(mode.device_out)) {
1213 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1214 enter_mode = enter_mode_rx_to_tx;
1215 } else {
1216 mode.dump = 1;
1217 register_signal_f(SIGALRM, timer_next_dump, SA_SIGINFO);
1218 enter_mode = enter_mode_rx_only_or_dump;
1219 if (!ops_touched)
1220 mode.pcap = PCAP_OPS_SG;
1222 } else {
1223 if (mode.device_out && device_mtu(mode.device_out)) {
1224 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1225 enter_mode = enter_mode_pcap_to_tx;
1226 if (!ops_touched)
1227 mode.pcap = PCAP_OPS_MMAP;
1228 } else {
1229 enter_mode = enter_mode_read_pcap;
1230 if (!ops_touched)
1231 mode.pcap = PCAP_OPS_SG;
1235 if (!enter_mode)
1236 panic("Selection not supported!\n");
1237 enter_mode(&mode);
1239 tprintf_cleanup();
1240 cleanup_pcap();
1242 if (setsockmem == true) {
1243 set_system_socket_mem(sock_rmem_max, vals[0]);
1244 set_system_socket_mem(sock_rmem_def, vals[1]);
1245 set_system_socket_mem(sock_wmem_max, vals[2]);
1246 set_system_socket_mem(sock_wmem_def, vals[3]);
1249 free(mode.device_in);
1250 free(mode.device_out);
1251 free(mode.device_trans);
1252 free(mode.prefix);
1254 return 0;