AUTHORS: Add Paolo Abeni for his contribution
[netsniff-ng.git] / netsniff-ng.c
blob4cfabc1046b823fef294f4eb50586266e690b7ef
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2009-2013 Daniel Borkmann.
4 * Copyright 2010 Emmanuel Roullit.
5 * Subject to the GPL, version 2.
6 */
8 #define _GNU_SOURCE
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <signal.h>
12 #include <getopt.h>
13 #include <ctype.h>
14 #include <time.h>
15 #include <string.h>
16 #include <sys/socket.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <sys/time.h>
20 #include <sys/fsuid.h>
21 #include <unistd.h>
22 #include <stdbool.h>
23 #include <pthread.h>
24 #include <fcntl.h>
25 #include <inttypes.h>
27 #include "ring_rx.h"
28 #include "ring_tx.h"
29 #include "mac80211.h"
30 #include "dev.h"
31 #include "built_in.h"
32 #include "pcap_io.h"
33 #include "privs.h"
34 #include "proc.h"
35 #include "bpf.h"
36 #include "ioops.h"
37 #include "die.h"
38 #include "irq.h"
39 #include "str.h"
40 #include "sig.h"
41 #include "config.h"
42 #include "sock.h"
43 #include "geoip.h"
44 #include "lockme.h"
45 #include "tprintf.h"
46 #include "timer.h"
47 #include "tstamping.h"
48 #include "dissector.h"
49 #include "xmalloc.h"
51 enum dump_mode {
52 DUMP_INTERVAL_TIME,
53 DUMP_INTERVAL_SIZE,
56 struct ctx {
57 char *device_in, *device_out, *device_trans, *filter, *prefix;
58 int cpu, rfraw, dump, print_mode, dump_dir, packet_type, lo_ifindex;
59 unsigned long kpull, dump_interval, tx_bytes, tx_packets;
60 size_t reserve_size;
61 bool randomize, promiscuous, enforce, jumbo, dump_bpf, hwtimestamp, verbose;
62 enum pcap_ops_groups pcap;
63 enum dump_mode dump_mode;
64 uid_t uid;
65 gid_t gid;
66 uint32_t link_type, magic;
67 uint32_t fanout_group, fanout_type;
68 uint64_t pkts_seen, pkts_recvd, pkts_drops;
69 uint64_t pkts_recvd_last, pkts_drops_last;
72 static volatile sig_atomic_t sigint = 0, sighup = 0;
73 static volatile bool next_dump = false;
74 static volatile sig_atomic_t sighup_time = 0;
76 static const char *short_options =
77 "d:i:o:rf:MNJt:S:k:n:b:HQmcsqXlvhF:RGAP:Vu:g:T:DBUC:K:L:w";
78 static const struct option long_options[] = {
79 {"dev", required_argument, NULL, 'd'},
80 {"in", required_argument, NULL, 'i'},
81 {"out", required_argument, NULL, 'o'},
82 {"filter", required_argument, NULL, 'f'},
83 {"num", required_argument, NULL, 'n'},
84 {"type", required_argument, NULL, 't'},
85 {"interval", required_argument, NULL, 'F'},
86 {"ring-size", required_argument, NULL, 'S'},
87 {"kernel-pull", required_argument, NULL, 'k'},
88 {"bind-cpu", required_argument, NULL, 'b'},
89 {"prefix", required_argument, NULL, 'P'},
90 {"user", required_argument, NULL, 'u'},
91 {"group", required_argument, NULL, 'g'},
92 {"magic", required_argument, NULL, 'T'},
93 {"fanout-group", required_argument, NULL, 'C'},
94 {"fanout-type", required_argument, NULL, 'K'},
95 {"fanout-opts", required_argument, NULL, 'L'},
96 {"rand", no_argument, NULL, 'r'},
97 {"rfraw", no_argument, NULL, 'R'},
98 {"mmap", no_argument, NULL, 'm'},
99 {"sg", no_argument, NULL, 'G'},
100 {"clrw", no_argument, NULL, 'c'},
101 {"jumbo-support", no_argument, NULL, 'J'},
102 {"no-promisc", no_argument, NULL, 'M'},
103 {"no-hwtimestamp", no_argument, NULL, 'N'},
104 {"prio-high", no_argument, NULL, 'H'},
105 {"notouch-irq", no_argument, NULL, 'Q'},
106 {"dump-pcap-types", no_argument, NULL, 'D'},
107 {"dump-bpf", no_argument, NULL, 'B'},
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 {"update", no_argument, NULL, 'U'},
114 {"cooked", no_argument, NULL, 'w'},
115 {"verbose", no_argument, NULL, 'V'},
116 {"version", no_argument, NULL, 'v'},
117 {"help", no_argument, NULL, 'h'},
118 {NULL, 0, NULL, 0}
121 static const char *copyright = "Please report bugs to <netsniff-ng@googlegroups.com>\n"
122 "Copyright (C) 2009-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
123 "Copyright (C) 2009-2012 Emmanuel Roullit <emmanuel.roullit@gmail.com>\n"
124 "Copyright (C) 2012 Markus Amend <markus@netsniff-ng.org>\n"
125 "Swiss federal institute of technology (ETH Zurich)\n"
126 "License: GNU GPL version 2.0\n"
127 "This is free software: you are free to change and redistribute it.\n"
128 "There is NO WARRANTY, to the extent permitted by law.";
130 static int tx_sock;
131 static struct itimerval itimer;
132 static unsigned long frame_count_max = 0, interval = TX_KERNEL_PULL_INT;
133 static time_t start_time;
135 #define __pcap_io pcap_ops[ctx->pcap]
137 static void signal_handler(int number)
139 switch (number) {
140 case SIGINT:
141 case SIGQUIT:
142 case SIGTERM:
143 sigint = 1;
144 break;
145 case SIGHUP:
146 sighup = 1;
147 sighup_time = (sig_atomic_t)(time(NULL) - start_time);
148 break;
149 default:
150 break;
154 static void timer_elapsed(int unused __maybe_unused)
156 int ret;
158 set_itimer_interval_value(&itimer, 0, interval);
160 ret = pull_and_flush_tx_ring(tx_sock);
161 if (unlikely(ret < 0)) {
162 /* We could hit EBADF if the socket has been closed before
163 * the timer was triggered.
165 if (errno != EBADF && errno != ENOBUFS)
166 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
169 setitimer(ITIMER_REAL, &itimer, NULL);
172 static void timer_purge(void)
174 int ret;
176 ret = pull_and_flush_tx_ring_wait(tx_sock);
177 if (unlikely(ret < 0)) {
178 if (errno != EBADF && errno != ENOBUFS)
179 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
182 set_itimer_interval_value(&itimer, 0, 0);
183 setitimer(ITIMER_REAL, &itimer, NULL);
186 static void timer_next_dump(int unused __maybe_unused)
188 set_itimer_interval_value(&itimer, interval, 0);
189 next_dump = true;
190 setitimer(ITIMER_REAL, &itimer, NULL);
193 static inline bool dump_to_pcap(struct ctx *ctx)
195 return ctx->dump;
198 static void on_panic_del_rfmon(void *arg)
200 leave_rfmon_mac80211(arg);
203 static inline void setup_rfmon_mac80211_dev(struct ctx *ctx, char **rfmon_dev)
205 ctx->device_trans = xstrdup(*rfmon_dev);
206 xfree(*rfmon_dev);
208 enter_rfmon_mac80211(ctx->device_trans, rfmon_dev);
209 panic_handler_add(on_panic_del_rfmon, *rfmon_dev);
212 static int update_rx_stats(struct ctx *ctx, int sock, bool is_v3)
214 uint64_t packets, drops;
215 int ret;
217 ret = get_rx_net_stats(sock, &packets, &drops, is_v3);
218 if (ret)
219 return ret;
221 ctx->pkts_recvd += packets;
222 ctx->pkts_drops += drops;
223 ctx->pkts_recvd_last = packets;
224 ctx->pkts_drops_last = drops;
226 return 0;
229 static void dump_rx_stats(struct ctx *ctx, int sock, bool is_v3)
231 if (update_rx_stats(ctx, sock, is_v3))
232 return;
234 printf("\r%12"PRIu64" packets incoming (%"PRIu64" unread on exit)\n",
235 is_v3 ? ctx->pkts_seen : ctx->pkts_recvd,
236 is_v3 ? ctx->pkts_recvd - ctx->pkts_seen : 0);
237 printf("\r%12"PRIu64" packets passed filter\n",
238 ctx->pkts_recvd - ctx->pkts_drops);
239 printf("\r%12"PRIu64" packets failed filter (out of space)\n",
240 ctx->pkts_drops);
242 if (ctx->pkts_recvd > 0)
243 printf("\r%12.4lf%% packet droprate\n",
244 (1.0 * ctx->pkts_drops / ctx->pkts_recvd) * 100.0);
247 static void pcap_to_xmit(struct ctx *ctx)
249 uint8_t *out = NULL;
250 int ifindex, fd = 0, ret;
251 size_t size;
252 unsigned int it = 0;
253 unsigned long trunced = 0;
254 struct ring tx_ring;
255 struct frame_map *hdr;
256 struct sock_fprog bpf_ops;
257 struct timeval start, end, diff;
258 pcap_pkthdr_t phdr;
260 if (!device_up_and_running(ctx->device_out) && !ctx->rfraw)
261 panic("Device not up and running!\n");
263 bug_on(!__pcap_io);
265 tx_sock = pf_socket();
267 if (!strncmp("-", ctx->device_in, strlen("-"))) {
268 fd = dup_or_die(fileno(stdin));
269 close(fileno(stdin));
270 if (ctx->pcap == PCAP_OPS_MM)
271 ctx->pcap = PCAP_OPS_SG;
272 } else {
273 fd = open_or_die(ctx->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
276 if (__pcap_io->init_once_pcap)
277 __pcap_io->init_once_pcap(true);
279 ret = __pcap_io->pull_fhdr_pcap(fd, &ctx->magic, &ctx->link_type);
280 if (ret)
281 panic("Error reading pcap header!\n");
283 if (__pcap_io->prepare_access_pcap) {
284 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_RD, ctx->jumbo);
285 if (ret)
286 panic("Error prepare reading pcap!\n");
289 if (ctx->rfraw) {
290 setup_rfmon_mac80211_dev(ctx, &ctx->device_out);
292 if (ctx->link_type != LINKTYPE_IEEE802_11 &&
293 ctx->link_type != LINKTYPE_IEEE802_11_RADIOTAP)
294 panic("Wrong linktype of pcap!\n");
297 ifindex = device_ifindex(ctx->device_out);
298 size = ring_size(ctx->device_out, ctx->reserve_size);
300 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
301 if (ctx->dump_bpf)
302 bpf_dump_all(&bpf_ops);
304 ring_tx_setup(&tx_ring, tx_sock, size, ifindex, ctx->jumbo, ctx->verbose);
306 dissector_init_all(ctx->print_mode);
308 if (ctx->cpu >= 0 && ifindex > 0) {
309 int irq = device_irq_number(ctx->device_out);
310 device_set_irq_affinity(irq, ctx->cpu);
312 if (ctx->verbose)
313 printf("IRQ: %s:%d > CPU%d\n",
314 ctx->device_out, irq, ctx->cpu);
317 if (ctx->kpull)
318 interval = ctx->kpull;
320 set_itimer_interval_value(&itimer, 0, interval);
321 setitimer(ITIMER_REAL, &itimer, NULL);
323 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
325 printf("Running! Hang up with ^C!\n\n");
326 fflush(stdout);
328 bug_on(gettimeofday(&start, NULL));
330 while (likely(sigint == 0)) {
331 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
332 hdr = tx_ring.frames[it].iov_base;
333 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
335 do {
336 ret = __pcap_io->read_pcap(fd, &phdr, ctx->magic, out,
337 ring_frame_size(&tx_ring));
338 if (unlikely(ret <= 0))
339 goto out;
341 if (ring_frame_size(&tx_ring) <
342 pcap_get_length(&phdr, ctx->magic)) {
343 pcap_set_length(&phdr, ctx->magic,
344 ring_frame_size(&tx_ring));
345 trunced++;
347 } while (ctx->filter &&
348 !bpf_run_filter(&bpf_ops, out,
349 pcap_get_length(&phdr, ctx->magic)));
351 pcap_pkthdr_to_tpacket_hdr(&phdr, ctx->magic, &hdr->tp_h, NULL);
353 ctx->tx_bytes += hdr->tp_h.tp_len;;
354 ctx->tx_packets++;
356 show_frame_hdr(out, hdr->tp_h.tp_snaplen,
357 ctx->link_type, hdr, ctx->print_mode,
358 ctx->tx_packets);
360 dissector_entry_point(out, hdr->tp_h.tp_snaplen,
361 ctx->link_type, ctx->print_mode,
362 &hdr->s_ll);
364 kernel_may_pull_from_tx(&hdr->tp_h);
366 it++;
367 if (it >= tx_ring.layout.tp_frame_nr)
368 it = 0;
370 if (unlikely(sigint == 1))
371 break;
373 if (frame_count_max != 0) {
374 if (ctx->tx_packets >= frame_count_max) {
375 sigint = 1;
376 break;
382 out:
383 bug_on(gettimeofday(&end, NULL));
384 timersub(&end, &start, &diff);
386 timer_purge();
388 bpf_release(&bpf_ops);
390 dissector_cleanup_all();
391 destroy_tx_ring(tx_sock, &tx_ring);
393 if (ctx->rfraw)
394 leave_rfmon_mac80211(ctx->device_out);
396 if (__pcap_io->prepare_close_pcap)
397 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_RD);
399 if (!strncmp("-", ctx->device_in, strlen("-")))
400 dup2(fd, fileno(stdin));
401 close(fd);
403 close(tx_sock);
405 fflush(stdout);
406 printf("\n");
407 printf("\r%12lu packets outgoing\n", ctx->tx_packets);
408 printf("\r%12lu packets truncated in file\n", trunced);
409 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
410 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
413 static inline bool skip_packet(struct ctx *ctx, struct sockaddr_ll *sll)
415 if (ctx->packet_type != -1)
416 return ctx->packet_type != sll->sll_pkttype;
418 /* when receving from the loopback device, each packet is seen twice,
419 * so drop the outgoing ones to avoid duplicates
421 return (sll->sll_ifindex == ctx->lo_ifindex) &&
422 (sll->sll_pkttype == PACKET_OUTGOING);
425 static void receive_to_xmit(struct ctx *ctx)
427 short ifflags = 0;
428 uint8_t *in, *out;
429 int rx_sock, ifindex_in, ifindex_out, ret;
430 size_t size_in, size_out;
431 unsigned int it_in = 0, it_out = 0;
432 struct frame_map *hdr_in, *hdr_out;
433 struct ring tx_ring, rx_ring;
434 struct pollfd rx_poll;
435 struct sock_fprog bpf_ops;
437 if (!strncmp(ctx->device_in, ctx->device_out, IFNAMSIZ))
438 panic("Ingress/egress devices must be different!\n");
439 if (!device_up_and_running(ctx->device_out))
440 panic("Egress device not up and running!\n");
442 rx_sock = pf_socket();
443 tx_sock = pf_socket();
445 ifindex_in = device_ifindex(ctx->device_in);
446 ifindex_out = device_ifindex(ctx->device_out);
448 size_in = ring_size(ctx->device_in, ctx->reserve_size);
449 size_out = ring_size(ctx->device_out, ctx->reserve_size);
451 enable_kernel_bpf_jit_compiler();
453 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
454 if (ctx->dump_bpf)
455 bpf_dump_all(&bpf_ops);
456 bpf_attach_to_sock(rx_sock, &bpf_ops);
458 ring_rx_setup(&rx_ring, rx_sock, size_in, ifindex_in, &rx_poll, false, ctx->jumbo,
459 ctx->verbose, ctx->fanout_group, ctx->fanout_type);
460 ring_tx_setup(&tx_ring, tx_sock, size_out, ifindex_out, ctx->jumbo, ctx->verbose);
462 dissector_init_all(ctx->print_mode);
464 if (ctx->promiscuous)
465 ifflags = device_enter_promiscuous_mode(ctx->device_in);
467 if (ctx->kpull)
468 interval = ctx->kpull;
470 set_itimer_interval_value(&itimer, 0, interval);
471 setitimer(ITIMER_REAL, &itimer, NULL);
473 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
475 printf("Running! Hang up with ^C!\n\n");
476 fflush(stdout);
478 while (likely(sigint == 0)) {
479 while (user_may_pull_from_rx(rx_ring.frames[it_in].iov_base)) {
480 hdr_in = rx_ring.frames[it_in].iov_base;
481 in = ((uint8_t *) hdr_in) + hdr_in->tp_h.tp_mac;
483 ctx->pkts_seen++;
485 if (skip_packet(ctx, &hdr_in->s_ll))
486 goto next;
488 hdr_out = tx_ring.frames[it_out].iov_base;
489 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
491 while (!user_may_pull_from_tx(tx_ring.frames[it_out].iov_base) &&
492 likely(!sigint)) {
493 if (ctx->randomize)
494 next_rnd_slot(&it_out, &tx_ring);
495 else {
496 it_out++;
497 if (it_out >= tx_ring.layout.tp_frame_nr)
498 it_out = 0;
501 hdr_out = tx_ring.frames[it_out].iov_base;
502 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
505 tpacket_hdr_clone(&hdr_out->tp_h, &hdr_in->tp_h);
506 fmemcpy(out, in, hdr_in->tp_h.tp_len);
508 kernel_may_pull_from_tx(&hdr_out->tp_h);
509 if (ctx->randomize)
510 next_rnd_slot(&it_out, &tx_ring);
511 else {
512 it_out++;
513 if (it_out >= tx_ring.layout.tp_frame_nr)
514 it_out = 0;
517 show_frame_hdr(in, hdr_in->tp_h.tp_snaplen,
518 ctx->link_type, hdr_in, ctx->print_mode,
519 ctx->pkts_seen);
521 dissector_entry_point(in, hdr_in->tp_h.tp_snaplen,
522 ctx->link_type, ctx->print_mode,
523 &hdr_in->s_ll);
525 if (frame_count_max != 0) {
526 if (ctx->pkts_seen >= frame_count_max) {
527 sigint = 1;
528 break;
532 next:
533 kernel_may_pull_from_rx(&hdr_in->tp_h);
535 it_in++;
536 if (it_in >= rx_ring.layout.tp_frame_nr)
537 it_in = 0;
539 if (unlikely(sigint == 1))
540 goto out;
543 ret = poll(&rx_poll, 1, -1);
544 if (unlikely(ret < 0)) {
545 if (errno != EINTR)
546 panic("Poll failed!\n");
550 out:
551 timer_purge();
553 dump_rx_stats(ctx, rx_sock, false);
555 bpf_release(&bpf_ops);
557 dissector_cleanup_all();
559 destroy_tx_ring(tx_sock, &tx_ring);
560 destroy_rx_ring(rx_sock, &rx_ring);
562 if (ctx->promiscuous)
563 device_leave_promiscuous_mode(ctx->device_in, ifflags);
565 close(tx_sock);
566 close(rx_sock);
569 static void translate_pcap_to_txf(int fdo, uint8_t *out, size_t len)
571 size_t bytes_done = 0;
572 char bout[80];
574 slprintf(bout, sizeof(bout), "{\n ");
575 write_or_die(fdo, bout, strlen(bout));
577 while (bytes_done < len) {
578 slprintf(bout, sizeof(bout), "0x%02x,", out[bytes_done]);
579 write_or_die(fdo, bout, strlen(bout));
581 bytes_done++;
583 if (bytes_done % 10 == 0) {
584 slprintf(bout, sizeof(bout), "\n");
585 write_or_die(fdo, bout, strlen(bout));
587 if (bytes_done < len) {
588 slprintf(bout, sizeof(bout), " ");
589 write_or_die(fdo, bout, strlen(bout));
591 } else if (bytes_done < len) {
592 slprintf(bout, sizeof(bout), " ");
593 write_or_die(fdo, bout, strlen(bout));
596 if (bytes_done % 10 != 0) {
597 slprintf(bout, sizeof(bout), "\n");
598 write_or_die(fdo, bout, strlen(bout));
601 slprintf(bout, sizeof(bout), "}\n\n");
602 write_or_die(fdo, bout, strlen(bout));
605 static void read_pcap(struct ctx *ctx)
607 uint8_t *out;
608 int ret, fd, fdo = 0;
609 unsigned long trunced = 0;
610 size_t out_len;
611 pcap_pkthdr_t phdr;
612 struct sock_fprog bpf_ops;
613 struct frame_map fm;
614 struct timeval start, end, diff;
615 bool is_out_pcap = ctx->device_out && strstr(ctx->device_out, ".pcap");
616 const struct pcap_file_ops *pcap_out_ops = pcap_ops[PCAP_OPS_RW];
618 bug_on(!__pcap_io);
620 if (!strncmp("-", ctx->device_in, strlen("-"))) {
621 fd = dup_or_die(fileno(stdin));
622 close(fileno(stdin));
623 if (ctx->pcap == PCAP_OPS_MM)
624 ctx->pcap = PCAP_OPS_SG;
625 } else {
626 /* O_NOATIME requires privileges, in case we don't have
627 * them, retry without them at a minor cost of updating
628 * atime in case the fs has been mounted as such.
630 fd = open(ctx->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
631 if (fd < 0 && errno == EPERM)
632 fd = open_or_die(ctx->device_in, O_RDONLY | O_LARGEFILE);
633 if (fd < 0)
634 panic("Cannot open file %s! %s.\n", ctx->device_in,
635 strerror(errno));
638 if (__pcap_io->init_once_pcap)
639 __pcap_io->init_once_pcap(false);
641 ret = __pcap_io->pull_fhdr_pcap(fd, &ctx->magic, &ctx->link_type);
642 if (ret)
643 panic("Error reading pcap header!\n");
645 if (__pcap_io->prepare_access_pcap) {
646 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_RD, ctx->jumbo);
647 if (ret)
648 panic("Error prepare reading pcap!\n");
651 fmemset(&fm, 0, sizeof(fm));
653 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
654 if (ctx->dump_bpf)
655 bpf_dump_all(&bpf_ops);
657 dissector_init_all(ctx->print_mode);
659 out_len = round_up(1024 * 1024, RUNTIME_PAGE_SIZE);
660 out = xmalloc_aligned(out_len, CO_CACHE_LINE_SIZE);
662 if (ctx->device_out) {
663 if (!strncmp("-", ctx->device_out, strlen("-"))) {
664 fdo = dup_or_die(fileno(stdout));
665 close(fileno(stdout));
666 } else {
667 fdo = open_or_die_m(ctx->device_out, O_RDWR | O_CREAT |
668 O_TRUNC | O_LARGEFILE, DEFFILEMODE);
672 if (is_out_pcap) {
673 ret = pcap_out_ops->push_fhdr_pcap(fdo, ctx->magic,
674 ctx->link_type);
675 if (ret)
676 panic("Error writing pcap header!\n");
679 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
681 printf("Running! Hang up with ^C!\n\n");
682 fflush(stdout);
684 bug_on(gettimeofday(&start, NULL));
686 while (likely(sigint == 0)) {
687 do {
688 ret = __pcap_io->read_pcap(fd, &phdr, ctx->magic,
689 out, out_len);
690 if (unlikely(ret < 0))
691 goto out;
693 if (unlikely(pcap_get_length(&phdr, ctx->magic) == 0)) {
694 trunced++;
695 continue;
698 if (unlikely(pcap_get_length(&phdr, ctx->magic) > out_len)) {
699 pcap_set_length(&phdr, ctx->magic, out_len);
700 trunced++;
702 } while (ctx->filter &&
703 !bpf_run_filter(&bpf_ops, out,
704 pcap_get_length(&phdr, ctx->magic)));
706 pcap_pkthdr_to_tpacket_hdr(&phdr, ctx->magic, &fm.tp_h, &fm.s_ll);
708 ctx->tx_bytes += fm.tp_h.tp_len;
709 ctx->tx_packets++;
711 show_frame_hdr(out, fm.tp_h.tp_snaplen, ctx->link_type, &fm,
712 ctx->print_mode, ctx->tx_packets);
714 dissector_entry_point(out, fm.tp_h.tp_snaplen,
715 ctx->link_type, ctx->print_mode,
716 &fm.s_ll);
718 if (is_out_pcap) {
719 size_t pcap_len = pcap_get_length(&phdr, ctx->magic);
720 int wlen = pcap_out_ops->write_pcap(fdo, &phdr,
721 ctx->magic, out,
722 pcap_len);
723 if (unlikely(wlen != (int)pcap_get_total_length(&phdr, ctx->magic)))
724 panic("Error writing to pcap!\n");
725 } else if (ctx->device_out) {
726 translate_pcap_to_txf(fdo, out, fm.tp_h.tp_snaplen);
729 if (frame_count_max != 0) {
730 if (ctx->tx_packets >= frame_count_max) {
731 sigint = 1;
732 break;
737 out:
738 bug_on(gettimeofday(&end, NULL));
739 timersub(&end, &start, &diff);
741 bpf_release(&bpf_ops);
743 dissector_cleanup_all();
745 if (__pcap_io->prepare_close_pcap)
746 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_RD);
748 xfree(out);
750 fflush(stdout);
751 printf("\n");
752 printf("\r%12lu packets outgoing\n", ctx->tx_packets);
753 printf("\r%12lu packets truncated in file\n", trunced);
754 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
755 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
757 if (!strncmp("-", ctx->device_in, strlen("-")))
758 dup2(fd, fileno(stdin));
759 close(fd);
761 if (ctx->device_out) {
762 if (!strncmp("-", ctx->device_out, strlen("-")))
763 dup2(fdo, fileno(stdout));
764 close(fdo);
768 static void finish_multi_pcap_file(struct ctx *ctx, int fd)
770 __pcap_io->fsync_pcap(fd);
772 if (__pcap_io->prepare_close_pcap)
773 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
775 close(fd);
777 fmemset(&itimer, 0, sizeof(itimer));
778 setitimer(ITIMER_REAL, &itimer, NULL);
781 static int next_multi_pcap_file(struct ctx *ctx, int fd)
783 int ret;
784 char fname[512];
785 time_t ftime;
787 __pcap_io->fsync_pcap(fd);
789 if (__pcap_io->prepare_close_pcap)
790 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
792 close(fd);
794 if (sighup_time > 0) {
795 ftime = (time_t)(start_time + sighup_time);
796 sighup_time = 0;
797 } else
798 ftime = time(NULL);
800 slprintf(fname, sizeof(fname), "%s/%s%lu.pcap", ctx->device_out,
801 ctx->prefix ? : "dump-", ftime);
803 fd = open_or_die_m(fname, O_RDWR | O_CREAT | O_TRUNC |
804 O_LARGEFILE, DEFFILEMODE);
806 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
807 if (ret)
808 panic("Error writing pcap header!\n");
810 if (__pcap_io->prepare_access_pcap) {
811 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
812 if (ret)
813 panic("Error prepare writing pcap!\n");
816 return fd;
819 static void reset_interval(struct ctx *ctx)
821 if (ctx->dump_mode == DUMP_INTERVAL_TIME) {
822 interval = ctx->dump_interval;
824 set_itimer_interval_value(&itimer, interval, 0);
825 setitimer(ITIMER_REAL, &itimer, NULL);
826 } else {
827 interval = 0;
831 static int begin_multi_pcap_file(struct ctx *ctx)
833 int fd, ret;
834 char fname[256];
836 bug_on(!__pcap_io);
838 if (ctx->device_out[strlen(ctx->device_out) - 1] == '/')
839 ctx->device_out[strlen(ctx->device_out) - 1] = 0;
841 slprintf(fname, sizeof(fname), "%s/%s%lu.pcap", ctx->device_out,
842 ctx->prefix ? : "dump-", time(NULL));
844 fd = open_or_die_m(fname, O_RDWR | O_CREAT | O_TRUNC |
845 O_LARGEFILE, DEFFILEMODE);
847 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
848 if (ret)
849 panic("Error writing pcap header!\n");
851 if (__pcap_io->prepare_access_pcap) {
852 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
853 if (ret)
854 panic("Error prepare writing pcap!\n");
857 reset_interval(ctx);
859 return fd;
862 static void finish_single_pcap_file(struct ctx *ctx, int fd)
864 __pcap_io->fsync_pcap(fd);
866 if (__pcap_io->prepare_close_pcap)
867 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
869 if (strncmp("-", ctx->device_out, strlen("-")))
870 close(fd);
871 else
872 dup2(fd, fileno(stdout));
875 static int begin_single_pcap_file(struct ctx *ctx)
877 int fd, ret;
879 bug_on(!__pcap_io);
881 if (!strncmp("-", ctx->device_out, strlen("-"))) {
882 fd = dup_or_die(fileno(stdout));
883 close(fileno(stdout));
884 if (ctx->pcap == PCAP_OPS_MM)
885 ctx->pcap = PCAP_OPS_SG;
886 } else {
887 fd = open_or_die_m(ctx->device_out,
888 O_RDWR | O_CREAT | O_TRUNC |
889 O_LARGEFILE, DEFFILEMODE);
892 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
893 if (ret)
894 panic("Error writing pcap header!\n");
896 if (__pcap_io->prepare_access_pcap) {
897 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
898 if (ret)
899 panic("Error prepare writing pcap!\n");
902 return fd;
905 static void update_pcap_next_dump(struct ctx *ctx, unsigned long snaplen,
906 int *fd, int sock, bool is_v3)
908 if (!dump_to_pcap(ctx))
909 return;
911 if (ctx->dump_mode == DUMP_INTERVAL_SIZE) {
912 interval += snaplen;
913 if (interval > ctx->dump_interval) {
914 next_dump = true;
915 interval = 0;
919 if (sighup) {
920 if (ctx->verbose)
921 printf("SIGHUP received, prematurely rotating pcap\n");
922 sighup = 0;
923 next_dump = true;
924 reset_interval(ctx);
927 if (next_dump) {
928 *fd = next_multi_pcap_file(ctx, *fd);
929 next_dump = false;
931 if (update_rx_stats(ctx, sock, is_v3))
932 return;
934 if (ctx->verbose && ctx->print_mode == PRINT_NONE)
935 printf(".(+%"PRIu64"/-%"PRIu64")",
936 ctx->pkts_recvd_last - ctx->pkts_drops_last,
937 ctx->pkts_drops_last);
941 #ifdef HAVE_TPACKET3
942 static void walk_t3_block(struct block_desc *pbd, struct ctx *ctx,
943 int sock, int *fd)
945 int num_pkts = pbd->h1.num_pkts, i;
946 struct tpacket3_hdr *hdr;
947 struct sockaddr_ll *sll;
949 hdr = (void *) ((uint8_t *) pbd + pbd->h1.offset_to_first_pkt);
950 sll = (void *) ((uint8_t *) hdr + TPACKET_ALIGN(sizeof(*hdr)));
952 for (i = 0; i < num_pkts && likely(sigint == 0); ++i) {
953 uint8_t *packet = ((uint8_t *) hdr + hdr->tp_mac);
954 pcap_pkthdr_t phdr;
956 if (skip_packet(ctx, sll))
957 goto next;
959 ctx->pkts_seen++;
961 if (dump_to_pcap(ctx)) {
962 int ret;
964 tpacket3_hdr_to_pcap_pkthdr(hdr, sll, &phdr, ctx->magic);
966 ret = __pcap_io->write_pcap(*fd, &phdr, ctx->magic, packet,
967 pcap_get_length(&phdr, ctx->magic));
968 if (unlikely(ret != (int) pcap_get_total_length(&phdr, ctx->magic)))
969 panic("Write error to pcap!\n");
972 __show_frame_hdr(packet, hdr->tp_snaplen, ctx->link_type, sll,
973 hdr, ctx->print_mode, true, ctx->pkts_seen);
975 dissector_entry_point(packet, hdr->tp_snaplen, ctx->link_type,
976 ctx->print_mode, sll);
977 next:
978 hdr = (void *) ((uint8_t *) hdr + hdr->tp_next_offset);
979 sll = (void *) ((uint8_t *) hdr + TPACKET_ALIGN(sizeof(*hdr)));
981 if (frame_count_max != 0) {
982 if (unlikely(ctx->pkts_seen >= frame_count_max)) {
983 sigint = 1;
984 break;
988 update_pcap_next_dump(ctx, hdr->tp_snaplen, fd, sock, true);
991 #endif /* HAVE_TPACKET3 */
993 static void recv_only_or_dump(struct ctx *ctx)
995 short ifflags = 0;
996 int sock, ifindex, fd = 0, ret;
997 size_t size;
998 unsigned int it = 0;
999 struct ring rx_ring;
1000 struct pollfd rx_poll;
1001 struct sock_fprog bpf_ops;
1002 struct timeval start, end, diff;
1003 bool is_v3 = is_defined(HAVE_TPACKET3);
1005 sock = pf_socket_type(ctx->link_type);
1007 ifindex = device_ifindex(ctx->device_in);
1008 size = ring_size(ctx->device_in, ctx->reserve_size);
1010 enable_kernel_bpf_jit_compiler();
1012 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
1013 if (ctx->dump_bpf)
1014 bpf_dump_all(&bpf_ops);
1015 bpf_attach_to_sock(sock, &bpf_ops);
1017 if (ctx->hwtimestamp) {
1018 ret = set_sockopt_hwtimestamp(sock, ctx->device_in);
1019 if (ret == 0 && ctx->verbose)
1020 printf("HW timestamping enabled\n");
1023 ring_rx_setup(&rx_ring, sock, size, ifindex, &rx_poll, is_v3, true,
1024 ctx->verbose, ctx->fanout_group, ctx->fanout_type);
1026 dissector_init_all(ctx->print_mode);
1028 if (ctx->cpu >= 0 && ifindex > 0) {
1029 int irq = device_irq_number(ctx->device_in);
1030 device_set_irq_affinity(irq, ctx->cpu);
1032 if (ctx->verbose)
1033 printf("IRQ: %s:%d > CPU%d\n",
1034 ctx->device_in, irq, ctx->cpu);
1037 if (ctx->promiscuous)
1038 ifflags = device_enter_promiscuous_mode(ctx->device_in);
1040 if (dump_to_pcap(ctx) && __pcap_io->init_once_pcap)
1041 __pcap_io->init_once_pcap(true);
1043 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
1045 if (dump_to_pcap(ctx)) {
1046 struct stat stats;
1048 ret = stat(ctx->device_out, &stats);
1049 if (ret < 0)
1050 ctx->dump_dir = 0;
1051 else
1052 ctx->dump_dir = S_ISDIR(stats.st_mode);
1054 if (ctx->dump_dir)
1055 fd = begin_multi_pcap_file(ctx);
1056 else
1057 fd = begin_single_pcap_file(ctx);
1060 printf("Running! Hang up with ^C!\n\n");
1061 fflush(stdout);
1063 bug_on(gettimeofday(&start, NULL));
1065 while (likely(sigint == 0)) {
1066 #ifdef HAVE_TPACKET3
1067 struct block_desc *pbd;
1069 while (user_may_pull_from_rx_block((pbd = rx_ring.frames[it].iov_base))) {
1070 walk_t3_block(pbd, ctx, sock, &fd);
1072 kernel_may_pull_from_rx_block(pbd);
1073 it = (it + 1) % rx_ring.layout3.tp_block_nr;
1075 if (unlikely(sigint == 1))
1076 break;
1078 #else
1079 while (user_may_pull_from_rx(rx_ring.frames[it].iov_base)) {
1080 struct frame_map *hdr = rx_ring.frames[it].iov_base;
1081 uint8_t *packet = ((uint8_t *) hdr) + hdr->tp_h.tp_mac;
1082 pcap_pkthdr_t phdr;
1084 if (skip_packet(ctx, &hdr->s_ll))
1085 goto next;
1087 ctx->pkts_seen++;
1089 if (unlikely(ring_frame_size(&rx_ring) < hdr->tp_h.tp_snaplen)) {
1090 /* XXX: silently ignore for now. We used to
1091 * report them with dump_rx_stats() */
1092 goto next;
1095 if (dump_to_pcap(ctx)) {
1096 tpacket_hdr_to_pcap_pkthdr(&hdr->tp_h, &hdr->s_ll, &phdr, ctx->magic);
1098 ret = __pcap_io->write_pcap(fd, &phdr, ctx->magic, packet,
1099 pcap_get_length(&phdr, ctx->magic));
1100 if (unlikely(ret != (int) pcap_get_total_length(&phdr, ctx->magic)))
1101 panic("Write error to pcap!\n");
1104 show_frame_hdr(packet, hdr->tp_h.tp_snaplen,
1105 ctx->link_type, hdr, ctx->print_mode,
1106 ctx->pkts_seen);
1108 dissector_entry_point(packet, hdr->tp_h.tp_snaplen,
1109 ctx->link_type, ctx->print_mode,
1110 &hdr->s_ll);
1112 if (frame_count_max != 0) {
1113 if (unlikely(ctx->pkts_seen >= frame_count_max)) {
1114 sigint = 1;
1115 break;
1119 next:
1120 kernel_may_pull_from_rx(&hdr->tp_h);
1121 it = (it + 1) % rx_ring.layout.tp_frame_nr;
1123 if (unlikely(sigint == 1))
1124 break;
1126 update_pcap_next_dump(ctx, hdr->tp_h.tp_snaplen, &fd,
1127 sock, is_v3);
1129 #endif /* HAVE_TPACKET3 */
1131 ret = poll(&rx_poll, 1, -1);
1132 if (unlikely(ret < 0)) {
1133 if (errno != EINTR)
1134 panic("Poll failed!\n");
1138 bug_on(gettimeofday(&end, NULL));
1139 timersub(&end, &start, &diff);
1141 dump_rx_stats(ctx, sock, is_v3);
1142 printf("\r%12lu sec, %lu usec in total\n",
1143 diff.tv_sec, diff.tv_usec);
1145 bpf_release(&bpf_ops);
1146 dissector_cleanup_all();
1147 destroy_rx_ring(sock, &rx_ring);
1149 if (ctx->promiscuous)
1150 device_leave_promiscuous_mode(ctx->device_in, ifflags);
1152 if (ctx->rfraw)
1153 leave_rfmon_mac80211(ctx->device_in);
1155 if (dump_to_pcap(ctx)) {
1156 if (ctx->dump_dir)
1157 finish_multi_pcap_file(ctx, fd);
1158 else
1159 finish_single_pcap_file(ctx, fd);
1162 close(sock);
1165 static void init_ctx(struct ctx *ctx)
1167 memset(ctx, 0, sizeof(*ctx));
1169 ctx->uid = getuid();
1170 ctx->gid = getgid();
1172 ctx->cpu = -1;
1173 ctx->packet_type = -1;
1175 ctx->fanout_type = PACKET_FANOUT_ROLLOVER;
1177 ctx->magic = ORIGINAL_TCPDUMP_MAGIC;
1178 ctx->print_mode = PRINT_NORM;
1179 ctx->pcap = PCAP_OPS_SG;
1181 ctx->dump_mode = DUMP_INTERVAL_TIME;
1182 ctx->dump_interval = 60;
1184 ctx->promiscuous = true;
1185 ctx->randomize = false;
1186 ctx->hwtimestamp = true;
1188 ctx->pkts_recvd = 0;
1189 ctx->pkts_seen = 0;
1190 ctx->pkts_drops = 0;
1191 ctx->pkts_recvd_last = 0;
1192 ctx->pkts_drops_last = 0;
1195 static void destroy_ctx(struct ctx *ctx)
1197 free(ctx->device_in);
1198 free(ctx->device_out);
1199 free(ctx->device_trans);
1201 free(ctx->prefix);
1204 static void __noreturn help(void)
1206 printf("netsniff-ng %s, the packet sniffing beast\n", VERSION_STRING);
1207 puts("http://www.netsniff-ng.org\n\n"
1208 "Usage: netsniff-ng [options] [filter-expression]\n"
1209 "Options:\n"
1210 " -i|-d|--dev|--in <dev|pcap|-> Input source as netdev, pcap or pcap stdin\n"
1211 " -o|--out <dev|pcap|dir|cfg|-> Output sink as netdev, pcap, directory, trafgen, or stdout\n"
1212 " -C|--fanout-group <id> Join packet fanout group\n"
1213 " -K|--fanout-type <type> Apply fanout discipline: hash|lb|cpu|rnd|roll|qm\n"
1214 " -L|--fanout-opts <opts> Additional fanout options: defrag|roll\n"
1215 " -f|--filter <bpf-file|-|expr> Use BPF filter from bpfc file/stdin or tcpdump-like expression\n"
1216 " -t|--type <type> Filter for: host|broadcast|multicast|others|outgoing\n"
1217 " -F|--interval <size|time> Dump interval if -o is a dir: <num>KiB/MiB/GiB/s/sec/min/hrs\n"
1218 " -R|--rfraw Capture or inject raw 802.11 frames\n"
1219 " -n|--num <0|uint> Number of packets until exit (def: 0)\n"
1220 " -P|--prefix <name> Prefix for pcaps stored in directory\n"
1221 " -T|--magic <pcap-magic> Pcap magic number/pcap format to store, see -D\n"
1222 " -w|--cooked Use Linux \"cooked\" header instead of link header\n"
1223 " -D|--dump-pcap-types Dump pcap types and magic numbers and quit\n"
1224 " -B|--dump-bpf Dump generated BPF assembly\n"
1225 " -r|--rand Randomize packet forwarding order (dev->dev)\n"
1226 " -M|--no-promisc No promiscuous mode for netdev\n"
1227 " -A|--no-sock-mem Don't tune core socket memory\n"
1228 " -N|--no-hwtimestamp Disable hardware time stamping\n"
1229 " -m|--mmap Mmap(2) pcap file I/O, e.g. for replaying pcaps\n"
1230 " -G|--sg Scatter/gather pcap file I/O\n"
1231 " -c|--clrw Use slower read(2)/write(2) I/O\n"
1232 " -S|--ring-size <size> Specify ring size to: <num>KiB/MiB/GiB\n"
1233 " -k|--kernel-pull <uint> Kernel pull from user interval in us (def: 10us)\n"
1234 " -J|--jumbo-support Support replay/fwd 64KB Super Jumbo Frames (def: 2048B)\n"
1235 " -b|--bind-cpu <cpu> Bind to specific CPU\n"
1236 " -u|--user <userid> Drop privileges and change to userid\n"
1237 " -g|--group <groupid> Drop privileges and change to groupid\n"
1238 " -H|--prio-high Make this high priority process\n"
1239 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
1240 " -s|--silent Do not print captured packets\n"
1241 " -q|--less Print less-verbose packet information\n"
1242 " -X|--hex Print packet data in hex format\n"
1243 " -l|--ascii Print human-readable packet data\n"
1244 " -U|--update Update GeoIP databases\n"
1245 " -V|--verbose Be more verbose\n"
1246 " -v|--version Show version and exit\n"
1247 " -h|--help Guess what?!\n\n"
1248 "Examples:\n"
1249 " netsniff-ng --in eth0 --out dump.pcap -s -T 0xa1b2c3d4 --b 0 tcp or udp\n"
1250 " netsniff-ng --in wlan0 --rfraw --out dump.pcap --silent --bind-cpu 0\n"
1251 " netsniff-ng --in dump.pcap --mmap --out eth0 -k1000 --silent --bind-cpu 0\n"
1252 " netsniff-ng --in dump.pcap --out dump.cfg --silent --bind-cpu 0\n"
1253 " netsniff-ng --in dump.pcap --out dump2.pcap --silent tcp\n"
1254 " netsniff-ng --in eth0 --out eth1 --silent --bind-cpu 0 -J --type host\n"
1255 " netsniff-ng --in eth1 --out /opt/probe/ -s -m --interval 100MiB -b 0\n"
1256 " netsniff-ng --in vlan0 --out dump.pcap -c -u `id -u bob` -g `id -g bob`\n"
1257 " netsniff-ng --in any --filter http.bpf --jumbo-support --ascii -V\n\n"
1258 "Note:\n"
1259 " For introducing bit errors, delays with random variation and more\n"
1260 " while replaying pcaps, make use of tc(8) with its disciplines (e.g. netem).\n");
1261 puts(copyright);
1262 die();
1265 static void __noreturn version(void)
1267 printf("netsniff-ng %s, Git id: %s\n", VERSION_LONG, GITVERSION);
1268 puts("the packet sniffing beast\n"
1269 "http://www.netsniff-ng.org\n");
1270 puts(copyright);
1271 die();
1274 int main(int argc, char **argv)
1276 char *ptr;
1277 int c, i, j, cpu_tmp, opt_index, ops_touched = 0, vals[4] = {0};
1278 bool prio_high = false, setsockmem = true;
1279 void (*main_loop)(struct ctx *ctx) = NULL;
1280 struct ctx ctx;
1282 init_ctx(&ctx);
1283 start_time = time(NULL);
1284 srand(start_time);
1286 while ((c = getopt_long(argc, argv, short_options, long_options,
1287 &opt_index)) != EOF) {
1288 switch (c) {
1289 case 'd':
1290 case 'i':
1291 ctx.device_in = xstrdup(optarg);
1292 break;
1293 case 'o':
1294 ctx.device_out = xstrdup(optarg);
1295 break;
1296 case 'P':
1297 ctx.prefix = xstrdup(optarg);
1298 break;
1299 case 'R':
1300 ctx.rfraw = 1;
1301 break;
1302 case 'r':
1303 ctx.randomize = true;
1304 break;
1305 case 'J':
1306 ctx.jumbo = true;
1307 break;
1308 case 'T':
1309 ctx.magic = (uint32_t) strtoul(optarg, NULL, 0);
1310 pcap_check_magic(ctx.magic);
1311 break;
1312 case 'f':
1313 ctx.filter = xstrdup(optarg);
1314 break;
1315 case 'M':
1316 ctx.promiscuous = false;
1317 break;
1318 case 'N':
1319 ctx.hwtimestamp = false;
1320 break;
1321 case 'A':
1322 setsockmem = false;
1323 break;
1324 case 'u':
1325 ctx.uid = strtoul(optarg, NULL, 0);
1326 ctx.enforce = true;
1327 break;
1328 case 'g':
1329 ctx.gid = strtoul(optarg, NULL, 0);
1330 ctx.enforce = true;
1331 break;
1332 case 'C':
1333 ctx.fanout_group = strtoul(optarg, NULL, 0);
1334 if (ctx.fanout_group == 0)
1335 panic("Non-zero fanout group id required!\n");
1336 break;
1337 case 'K':
1338 if (!strncmp(optarg, "hash", strlen("hash")))
1339 ctx.fanout_type = PACKET_FANOUT_HASH;
1340 else if (!strncmp(optarg, "lb", strlen("lb")) ||
1341 !strncmp(optarg, "rr", strlen("rr")))
1342 ctx.fanout_type = PACKET_FANOUT_LB;
1343 else if (!strncmp(optarg, "cpu", strlen("cpu")))
1344 ctx.fanout_type = PACKET_FANOUT_CPU;
1345 else if (!strncmp(optarg, "rnd", strlen("rnd")))
1346 ctx.fanout_type = PACKET_FANOUT_RND;
1347 else if (!strncmp(optarg, "roll", strlen("roll")))
1348 ctx.fanout_type = PACKET_FANOUT_ROLLOVER;
1349 else if (!strncmp(optarg, "qm", strlen("qm")))
1350 ctx.fanout_type = PACKET_FANOUT_QM;
1351 else
1352 panic("Unknown fanout type!\n");
1353 break;
1354 case 'L':
1355 if (!strncmp(optarg, "defrag", strlen("defrag")))
1356 ctx.fanout_type |= PACKET_FANOUT_FLAG_DEFRAG;
1357 else if (!strncmp(optarg, "roll", strlen("roll")))
1358 ctx.fanout_type |= PACKET_FANOUT_FLAG_ROLLOVER;
1359 else
1360 panic("Unknown fanout option!\n");
1361 break;
1362 case 't':
1363 if (!strncmp(optarg, "host", strlen("host")))
1364 ctx.packet_type = PACKET_HOST;
1365 else if (!strncmp(optarg, "broadcast", strlen("broadcast")))
1366 ctx.packet_type = PACKET_BROADCAST;
1367 else if (!strncmp(optarg, "multicast", strlen("multicast")))
1368 ctx.packet_type = PACKET_MULTICAST;
1369 else if (!strncmp(optarg, "others", strlen("others")))
1370 ctx.packet_type = PACKET_OTHERHOST;
1371 else if (!strncmp(optarg, "outgoing", strlen("outgoing")))
1372 ctx.packet_type = PACKET_OUTGOING;
1373 else
1374 ctx.packet_type = -1;
1375 break;
1376 case 'S':
1377 ptr = optarg;
1378 for (j = i = strlen(optarg); i > 0; --i) {
1379 if (!isdigit(optarg[j - i]))
1380 break;
1381 ptr++;
1384 if (!strncmp(ptr, "KiB", strlen("KiB")))
1385 ctx.reserve_size = 1 << 10;
1386 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1387 ctx.reserve_size = 1 << 20;
1388 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1389 ctx.reserve_size = 1 << 30;
1390 else
1391 panic("Syntax error in ring size param!\n");
1393 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1394 break;
1395 case 'b':
1396 cpu_tmp = strtol(optarg, NULL, 0);
1398 cpu_affinity(cpu_tmp);
1399 if (ctx.cpu != -2)
1400 ctx.cpu = cpu_tmp;
1401 break;
1402 case 'H':
1403 prio_high = true;
1404 break;
1405 case 'c':
1406 ctx.pcap = PCAP_OPS_RW;
1407 ops_touched = 1;
1408 break;
1409 case 'm':
1410 ctx.pcap = PCAP_OPS_MM;
1411 ops_touched = 1;
1412 break;
1413 case 'G':
1414 ctx.pcap = PCAP_OPS_SG;
1415 ops_touched = 1;
1416 break;
1417 case 'Q':
1418 ctx.cpu = -2;
1419 break;
1420 case 's':
1421 ctx.print_mode = PRINT_NONE;
1422 break;
1423 case 'q':
1424 ctx.print_mode = PRINT_LESS;
1425 break;
1426 case 'X':
1427 ctx.print_mode =
1428 (ctx.print_mode == PRINT_ASCII) ?
1429 PRINT_HEX_ASCII : PRINT_HEX;
1430 break;
1431 case 'l':
1432 ctx.print_mode =
1433 (ctx.print_mode == PRINT_HEX) ?
1434 PRINT_HEX_ASCII : PRINT_ASCII;
1435 break;
1436 case 'k':
1437 ctx.kpull = strtoul(optarg, NULL, 0);
1438 break;
1439 case 'n':
1440 frame_count_max = strtoul(optarg, NULL, 0);
1441 break;
1442 case 'F':
1443 ptr = optarg;
1444 for (j = i = strlen(optarg); i > 0; --i) {
1445 if (!isdigit(optarg[j - i]))
1446 break;
1447 ptr++;
1450 if (!strncmp(ptr, "KiB", strlen("KiB"))) {
1451 ctx.dump_interval = 1 << 10;
1452 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1453 } else if (!strncmp(ptr, "MiB", strlen("MiB"))) {
1454 ctx.dump_interval = 1 << 20;
1455 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1456 } else if (!strncmp(ptr, "GiB", strlen("GiB"))) {
1457 ctx.dump_interval = 1 << 30;
1458 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1459 } else if (!strncmp(ptr, "sec", strlen("sec"))) {
1460 ctx.dump_interval = 1;
1461 ctx.dump_mode = DUMP_INTERVAL_TIME;
1462 } else if (!strncmp(ptr, "min", strlen("min"))) {
1463 ctx.dump_interval = 60;
1464 ctx.dump_mode = DUMP_INTERVAL_TIME;
1465 } else if (!strncmp(ptr, "hrs", strlen("hrs"))) {
1466 ctx.dump_interval = 60 * 60;
1467 ctx.dump_mode = DUMP_INTERVAL_TIME;
1468 } else if (!strncmp(ptr, "s", strlen("s"))) {
1469 ctx.dump_interval = 1;
1470 ctx.dump_mode = DUMP_INTERVAL_TIME;
1471 } else {
1472 panic("Syntax error in time/size param!\n");
1475 ctx.dump_interval *= strtoul(optarg, NULL, 0);
1476 break;
1477 case 'V':
1478 ctx.verbose = true;
1479 break;
1480 case 'B':
1481 ctx.dump_bpf = true;
1482 break;
1483 case 'D':
1484 pcap_dump_type_features();
1485 die();
1486 break;
1487 case 'U':
1488 update_geoip();
1489 die();
1490 break;
1491 case 'w':
1492 ctx.link_type = LINKTYPE_LINUX_SLL;
1493 break;
1494 case 'v':
1495 version();
1496 break;
1497 case 'h':
1498 help();
1499 break;
1500 case '?':
1501 switch (optopt) {
1502 case 'd':
1503 case 'i':
1504 case 'o':
1505 case 'f':
1506 case 't':
1507 case 'P':
1508 case 'F':
1509 case 'n':
1510 case 'S':
1511 case 'b':
1512 case 'k':
1513 case 'T':
1514 case 'u':
1515 case 'g':
1516 case 'e':
1517 panic("Option -%c requires an argument!\n",
1518 optopt);
1519 default:
1520 if (isprint(optopt))
1521 printf("Unknown option character `0x%X\'!\n", optopt);
1522 die();
1524 default:
1525 break;
1529 if (!ctx.filter && optind != argc)
1530 ctx.filter = argv2str(optind, argc, argv);
1532 if (!ctx.device_in)
1533 ctx.device_in = xstrdup("any");
1535 if (!strcmp(ctx.device_in, "any") || !strcmp(ctx.device_in, "lo"))
1536 ctx.lo_ifindex = device_ifindex("lo");
1538 register_signal(SIGINT, signal_handler);
1539 register_signal(SIGQUIT, signal_handler);
1540 register_signal(SIGTERM, signal_handler);
1541 register_signal(SIGHUP, signal_handler);
1543 tprintf_init();
1545 if (prio_high) {
1546 set_proc_prio(-20);
1547 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1550 if (device_mtu(ctx.device_in) || !strncmp("any", ctx.device_in, strlen(ctx.device_in))) {
1551 if (ctx.rfraw)
1552 setup_rfmon_mac80211_dev(&ctx, &ctx.device_in);
1554 if (!ctx.link_type)
1555 ctx.link_type = pcap_dev_to_linktype(ctx.device_in);
1556 if (link_has_sll_hdr(ctx.link_type)) {
1557 switch (ctx.magic) {
1558 case ORIGINAL_TCPDUMP_MAGIC:
1559 ctx.magic = ORIGINAL_TCPDUMP_MAGIC_LL;
1560 break;
1561 case NSEC_TCPDUMP_MAGIC:
1562 ctx.magic = NSEC_TCPDUMP_MAGIC_LL;
1563 break;
1564 case ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC):
1565 ctx.magic = ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC_LL);
1566 break;
1567 case ___constant_swab32(NSEC_TCPDUMP_MAGIC):
1568 ctx.magic = ___constant_swab32(NSEC_TCPDUMP_MAGIC_LL);
1569 break;
1574 if (!ctx.device_out) {
1575 ctx.dump = 0;
1576 main_loop = recv_only_or_dump;
1577 } else if (device_mtu(ctx.device_out)) {
1578 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1579 main_loop = receive_to_xmit;
1580 } else {
1581 ctx.dump = 1;
1582 register_signal_f(SIGALRM, timer_next_dump, SA_SIGINFO);
1583 main_loop = recv_only_or_dump;
1584 if (!ops_touched)
1585 ctx.pcap = PCAP_OPS_SG;
1587 } else {
1588 if (ctx.device_out && device_mtu(ctx.device_out)) {
1589 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1590 main_loop = pcap_to_xmit;
1591 if (!ops_touched)
1592 ctx.pcap = PCAP_OPS_MM;
1593 } else {
1594 setsockmem = false;
1595 main_loop = read_pcap;
1596 if (!ops_touched)
1597 ctx.pcap = PCAP_OPS_SG;
1601 bug_on(!main_loop);
1603 init_geoip(0);
1604 if (setsockmem)
1605 set_system_socket_memory(vals, array_size(vals));
1606 if (!ctx.enforce)
1607 xlockme();
1609 if (ctx.verbose)
1610 printf("pcap file I/O method: %s\n", pcap_ops_group_to_str[ctx.pcap]);
1612 main_loop(&ctx);
1614 if (!ctx.enforce)
1615 xunlockme();
1616 if (setsockmem)
1617 reset_system_socket_memory(vals, array_size(vals));
1618 destroy_geoip();
1620 device_restore_irq_affinity_list();
1621 tprintf_cleanup();
1623 destroy_ctx(&ctx);
1624 return 0;