mausezahn: use getopt_long instead of getopt
[netsniff-ng.git] / netsniff-ng.c
blob263078dea9de6a63e99b9ec097145b2abed096b7
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>
26 #include <limits.h>
28 #include "ring_rx.h"
29 #include "ring_tx.h"
30 #include "mac80211.h"
31 #include "dev.h"
32 #include "built_in.h"
33 #include "pcap_io.h"
34 #include "privs.h"
35 #include "proc.h"
36 #include "bpf.h"
37 #include "ioops.h"
38 #include "die.h"
39 #include "irq.h"
40 #include "str.h"
41 #include "sig.h"
42 #include "config.h"
43 #include "sock.h"
44 #include "geoip.h"
45 #include "lockme.h"
46 #include "tprintf.h"
47 #include "timer.h"
48 #include "tstamping.h"
49 #include "dissector.h"
50 #include "xmalloc.h"
52 enum dump_mode {
53 DUMP_INTERVAL_TIME,
54 DUMP_INTERVAL_SIZE,
57 struct ctx {
58 char *device_in, *device_out, *device_trans, *filter, *prefix;
59 int cpu, rfraw, dump, print_mode, dump_dir, packet_type, lo_ifindex;
60 unsigned long kpull, dump_interval, tx_bytes, tx_packets;
61 size_t reserve_size;
62 bool randomize, promiscuous, enforce, jumbo, dump_bpf, hwtimestamp, verbose;
63 enum pcap_ops_groups pcap;
64 enum dump_mode dump_mode;
65 uid_t uid;
66 gid_t gid;
67 uint32_t link_type, magic;
68 uint32_t fanout_group, fanout_type;
69 uint64_t pkts_seen, pkts_recvd, pkts_drops;
70 uint64_t pkts_recvd_last, pkts_drops_last, pkts_skipd_last;
71 unsigned long overwrite_interval, file_number;
74 static volatile sig_atomic_t sigint = 0, sighup = 0;
75 static volatile bool next_dump = false;
76 static volatile sig_atomic_t sighup_time = 0;
78 static const char *short_options =
79 "d:i:o:rf:MNJt:S:k:n:b:HQmcsqXlvhF:RGAO:P:Vu:g:T:DBUC:K:L:w";
80 static const struct option long_options[] = {
81 {"dev", required_argument, NULL, 'd'},
82 {"in", required_argument, NULL, 'i'},
83 {"out", required_argument, NULL, 'o'},
84 {"filter", required_argument, NULL, 'f'},
85 {"num", required_argument, NULL, 'n'},
86 {"type", required_argument, NULL, 't'},
87 {"interval", required_argument, NULL, 'F'},
88 {"ring-size", required_argument, NULL, 'S'},
89 {"kernel-pull", required_argument, NULL, 'k'},
90 {"bind-cpu", required_argument, NULL, 'b'},
91 {"overwrite", required_argument, NULL, 'O'},
92 {"prefix", required_argument, NULL, 'P'},
93 {"user", required_argument, NULL, 'u'},
94 {"group", required_argument, NULL, 'g'},
95 {"magic", required_argument, NULL, 'T'},
96 {"fanout-group", required_argument, NULL, 'C'},
97 {"fanout-type", required_argument, NULL, 'K'},
98 {"fanout-opts", required_argument, NULL, 'L'},
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 {"no-hwtimestamp", no_argument, NULL, 'N'},
107 {"prio-high", no_argument, NULL, 'H'},
108 {"notouch-irq", no_argument, NULL, 'Q'},
109 {"dump-pcap-types", no_argument, NULL, 'D'},
110 {"dump-bpf", no_argument, NULL, 'B'},
111 {"silent", no_argument, NULL, 's'},
112 {"less", no_argument, NULL, 'q'},
113 {"hex", no_argument, NULL, 'X'},
114 {"ascii", no_argument, NULL, 'l'},
115 {"no-sock-mem", no_argument, NULL, 'A'},
116 {"update", no_argument, NULL, 'U'},
117 {"cooked", no_argument, NULL, 'w'},
118 {"verbose", no_argument, NULL, 'V'},
119 {"version", no_argument, NULL, 'v'},
120 {"help", no_argument, NULL, 'h'},
121 {NULL, 0, NULL, 0}
124 static const char *copyright =
125 "Please report bugs at https://github.com/netsniff-ng/netsniff-ng/issues\n"
126 "Copyright (C) 2009-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
127 "Copyright (C) 2009-2012 Emmanuel Roullit <emmanuel.roullit@gmail.com>\n"
128 "Copyright (C) 2012 Markus Amend <markus@netsniff-ng.org>\n"
129 "Swiss federal institute of technology (ETH Zurich)\n"
130 "License: GNU GPL version 2.0\n"
131 "This is free software: you are free to change and redistribute it.\n"
132 "There is NO WARRANTY, to the extent permitted by law.";
134 static int tx_sock;
135 static struct itimerval itimer;
136 static unsigned long frame_count_max = 0, interval = TX_KERNEL_PULL_INT;
137 static time_t start_time;
139 #define __pcap_io pcap_ops[ctx->pcap]
141 static void signal_handler(int number)
143 switch (number) {
144 case SIGINT:
145 case SIGQUIT:
146 case SIGTERM:
147 sigint = 1;
148 break;
149 case SIGHUP:
150 sighup = 1;
151 sighup_time = (sig_atomic_t)(time(NULL) - start_time);
152 break;
153 default:
154 break;
158 static void timer_elapsed(int unused __maybe_unused)
160 int ret;
162 set_itimer_interval_value(&itimer, 0, interval);
164 ret = pull_and_flush_tx_ring(tx_sock);
165 if (unlikely(ret < 0)) {
166 /* We could hit EBADF if the socket has been closed before
167 * the timer was triggered.
169 if (errno != EBADF && errno != ENOBUFS)
170 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
173 setitimer(ITIMER_REAL, &itimer, NULL);
176 static void timer_purge(void)
178 int ret;
180 ret = pull_and_flush_tx_ring_wait(tx_sock);
181 if (unlikely(ret < 0)) {
182 if (errno != EBADF && errno != ENOBUFS)
183 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
186 set_itimer_interval_value(&itimer, 0, 0);
187 setitimer(ITIMER_REAL, &itimer, NULL);
190 static void timer_next_dump(int unused __maybe_unused)
192 set_itimer_interval_value(&itimer, interval, 0);
193 next_dump = true;
194 setitimer(ITIMER_REAL, &itimer, NULL);
197 static inline bool dump_to_pcap(struct ctx *ctx)
199 return ctx->dump;
202 static void on_panic_del_rfmon(void *arg)
204 leave_rfmon_mac80211(arg);
207 static inline void setup_rfmon_mac80211_dev(struct ctx *ctx, char **rfmon_dev)
209 ctx->device_trans = xstrdup(*rfmon_dev);
210 xfree(*rfmon_dev);
212 enter_rfmon_mac80211(ctx->device_trans, rfmon_dev);
213 panic_handler_add(on_panic_del_rfmon, *rfmon_dev);
216 static int update_rx_stats(struct ctx *ctx, int sock, bool is_v3)
218 uint64_t packets, drops;
219 int ret;
221 ret = get_rx_net_stats(sock, &packets, &drops, is_v3);
222 if (ret)
223 return ret;
225 drops += ctx->pkts_skipd_last;
226 ctx->pkts_seen += ctx->pkts_skipd_last;
227 ctx->pkts_recvd += packets;
228 ctx->pkts_drops += drops;
229 ctx->pkts_recvd_last = packets;
230 ctx->pkts_drops_last = drops;
231 ctx->pkts_skipd_last = 0;
233 return 0;
236 static void dump_rx_stats(struct ctx *ctx, int sock, bool is_v3)
238 if (update_rx_stats(ctx, sock, is_v3))
239 return;
241 FILE *fd = stdout;
242 // In case the out device is stdout redirect to stderr
243 if (ctx->device_out && !strncmp("-", ctx->device_out, strlen("-")))
244 fd = stderr;
246 fprintf(fd, "\r%12"PRIu64" packets incoming (%"PRIu64" unread on exit)\n",
247 is_v3 ? ctx->pkts_seen : ctx->pkts_recvd,
248 is_v3 ? ctx->pkts_recvd - ctx->pkts_seen : 0);
249 fprintf(fd, "\r%12"PRIu64" packets passed filter\n",
250 ctx->pkts_recvd - ctx->pkts_drops);
251 fprintf(fd, "\r%12"PRIu64" packets failed filter (out of space)\n",
252 ctx->pkts_drops);
254 if (ctx->pkts_recvd > 0)
255 fprintf(fd, "\r%12.4lf%% packet droprate\n",
256 (1.0 * ctx->pkts_drops / ctx->pkts_recvd) * 100.0);
259 static void pcap_to_xmit(struct ctx *ctx)
261 uint8_t *out = NULL;
262 int ifindex, fd = 0, ret;
263 size_t size;
264 unsigned int it = 0;
265 unsigned long trunced = 0;
266 struct ring tx_ring;
267 struct frame_map *hdr;
268 struct sock_fprog bpf_ops;
269 struct timeval start, end, diff;
270 pcap_pkthdr_t phdr;
272 if (!device_up_and_running(ctx->device_out) && !ctx->rfraw)
273 panic("Device not up and running!\n");
275 bug_on(!__pcap_io);
277 tx_sock = pf_socket();
279 if (!strncmp("-", ctx->device_in, strlen("-"))) {
280 fd = dup_or_die(fileno(stdin));
281 close(fileno(stdin));
282 if (ctx->pcap == PCAP_OPS_MM)
283 ctx->pcap = PCAP_OPS_SG;
284 } else {
285 fd = open_or_die(ctx->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
288 if (__pcap_io->init_once_pcap)
289 __pcap_io->init_once_pcap(true);
291 ret = __pcap_io->pull_fhdr_pcap(fd, &ctx->magic, &ctx->link_type);
292 if (ret)
293 panic("Error reading pcap header!\n");
295 if (__pcap_io->prepare_access_pcap) {
296 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_RD, ctx->jumbo);
297 if (ret)
298 panic("Error prepare reading pcap!\n");
301 if (ctx->rfraw) {
302 setup_rfmon_mac80211_dev(ctx, &ctx->device_out);
304 if (ctx->link_type != LINKTYPE_IEEE802_11 &&
305 ctx->link_type != LINKTYPE_IEEE802_11_RADIOTAP)
306 panic("Wrong linktype of pcap!\n");
309 ifindex = device_ifindex(ctx->device_out);
310 size = ring_size(ctx->device_out, ctx->reserve_size);
312 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
313 if (ctx->dump_bpf)
314 bpf_dump_all(&bpf_ops);
316 ring_tx_setup(&tx_ring, tx_sock, size, ifindex, ctx->jumbo, ctx->verbose);
318 dissector_init_all(ctx->print_mode);
320 if (ctx->cpu >= 0 && ifindex > 0) {
321 int irq = device_irq_number(ctx->device_out);
322 device_set_irq_affinity(irq, ctx->cpu);
324 if (ctx->verbose)
325 printf("IRQ: %s:%d > CPU%d\n",
326 ctx->device_out, irq, ctx->cpu);
329 if (ctx->kpull)
330 interval = ctx->kpull;
332 set_itimer_interval_value(&itimer, 0, interval);
333 setitimer(ITIMER_REAL, &itimer, NULL);
335 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
337 printf("Running! Hang up with ^C!\n\n");
338 fflush(stdout);
340 bug_on(gettimeofday(&start, NULL));
342 while (likely(sigint == 0)) {
343 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
344 hdr = tx_ring.frames[it].iov_base;
345 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
347 do {
348 ret = __pcap_io->read_pcap(fd, &phdr, ctx->magic, out,
349 ring_frame_size(&tx_ring));
350 if (unlikely(ret <= 0))
351 goto out;
353 if (ring_frame_size(&tx_ring) <
354 pcap_get_length(&phdr, ctx->magic)) {
355 pcap_set_length(&phdr, ctx->magic,
356 ring_frame_size(&tx_ring));
357 trunced++;
359 } while (ctx->filter &&
360 !bpf_run_filter(&bpf_ops, out,
361 pcap_get_length(&phdr, ctx->magic)));
363 pcap_pkthdr_to_tpacket_hdr(&phdr, ctx->magic, &hdr->tp_h, NULL);
365 ctx->tx_bytes += hdr->tp_h.tp_len;;
366 ctx->tx_packets++;
368 show_frame_hdr(out, hdr->tp_h.tp_snaplen,
369 ctx->link_type, hdr, ctx->print_mode,
370 ctx->tx_packets);
372 dissector_entry_point(out, hdr->tp_h.tp_snaplen,
373 ctx->link_type, ctx->print_mode,
374 &hdr->s_ll);
376 kernel_may_pull_from_tx(&hdr->tp_h);
378 it++;
379 if (it >= tx_ring.layout.tp_frame_nr)
380 it = 0;
382 if (unlikely(sigint == 1))
383 break;
385 if (frame_count_max != 0) {
386 if (ctx->tx_packets >= frame_count_max) {
387 sigint = 1;
388 break;
394 out:
395 bug_on(gettimeofday(&end, NULL));
396 timersub(&end, &start, &diff);
398 timer_purge();
400 bpf_release(&bpf_ops);
402 dissector_cleanup_all();
403 destroy_tx_ring(tx_sock, &tx_ring);
405 if (ctx->rfraw)
406 leave_rfmon_mac80211(ctx->device_out);
408 if (__pcap_io->prepare_close_pcap)
409 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_RD);
411 if (!strncmp("-", ctx->device_in, strlen("-")))
412 dup2(fd, fileno(stdin));
413 close(fd);
415 close(tx_sock);
417 fflush(stdout);
418 printf("\n");
419 printf("\r%12lu packets outgoing\n", ctx->tx_packets);
420 printf("\r%12lu packets truncated in file\n", trunced);
421 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
422 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
425 static inline bool __skip_packet(struct ctx *ctx, struct sockaddr_ll *sll)
427 if (ctx->packet_type != -1)
428 return ctx->packet_type != sll->sll_pkttype;
430 /* when receving from the loopback device, each packet is seen twice,
431 * so drop the outgoing ones to avoid duplicates
433 return (sll->sll_ifindex == ctx->lo_ifindex) &&
434 (sll->sll_pkttype == PACKET_OUTGOING);
437 static inline bool skip_packet(struct ctx *ctx, struct sockaddr_ll *sll)
439 bool skip = __skip_packet(ctx, sll);
441 if (skip)
442 ctx->pkts_skipd_last++;
443 return skip;
446 static void receive_to_xmit(struct ctx *ctx)
448 short ifflags = 0;
449 uint8_t *in, *out;
450 int rx_sock, ifindex_in, ifindex_out, ret;
451 size_t size_in, size_out;
452 unsigned int it_in = 0, it_out = 0;
453 struct frame_map *hdr_in, *hdr_out;
454 struct ring tx_ring, rx_ring;
455 struct pollfd rx_poll;
456 struct sock_fprog bpf_ops;
458 if (!strncmp(ctx->device_in, ctx->device_out, IFNAMSIZ))
459 panic("Ingress/egress devices must be different!\n");
460 if (!device_up_and_running(ctx->device_out))
461 panic("Egress device not up and running!\n");
463 rx_sock = pf_socket();
464 tx_sock = pf_socket();
466 ifindex_in = device_ifindex(ctx->device_in);
467 ifindex_out = device_ifindex(ctx->device_out);
469 size_in = ring_size(ctx->device_in, ctx->reserve_size);
470 size_out = ring_size(ctx->device_out, ctx->reserve_size);
472 enable_kernel_bpf_jit_compiler();
474 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
475 if (ctx->dump_bpf)
476 bpf_dump_all(&bpf_ops);
477 bpf_attach_to_sock(rx_sock, &bpf_ops);
479 ring_rx_setup(&rx_ring, rx_sock, size_in, ifindex_in, &rx_poll, false, ctx->jumbo,
480 ctx->verbose, ctx->fanout_group, ctx->fanout_type);
481 ring_tx_setup(&tx_ring, tx_sock, size_out, ifindex_out, ctx->jumbo, ctx->verbose);
483 dissector_init_all(ctx->print_mode);
485 if (ctx->promiscuous)
486 ifflags = device_enter_promiscuous_mode(ctx->device_in);
488 if (ctx->kpull)
489 interval = ctx->kpull;
491 set_itimer_interval_value(&itimer, 0, interval);
492 setitimer(ITIMER_REAL, &itimer, NULL);
494 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
496 printf("Running! Hang up with ^C!\n\n");
497 fflush(stdout);
499 while (likely(sigint == 0)) {
500 while (user_may_pull_from_rx(rx_ring.frames[it_in].iov_base)) {
501 hdr_in = rx_ring.frames[it_in].iov_base;
502 in = ((uint8_t *) hdr_in) + hdr_in->tp_h.tp_mac;
504 if (skip_packet(ctx, &hdr_in->s_ll))
505 goto next;
507 ctx->pkts_seen++;
509 hdr_out = tx_ring.frames[it_out].iov_base;
510 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
512 while (!user_may_pull_from_tx(tx_ring.frames[it_out].iov_base) &&
513 likely(!sigint)) {
514 if (ctx->randomize)
515 next_rnd_slot(&it_out, &tx_ring);
516 else {
517 it_out++;
518 if (it_out >= tx_ring.layout.tp_frame_nr)
519 it_out = 0;
522 hdr_out = tx_ring.frames[it_out].iov_base;
523 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
526 tpacket_hdr_clone(&hdr_out->tp_h, &hdr_in->tp_h);
527 memcpy(out, in, hdr_in->tp_h.tp_len);
529 kernel_may_pull_from_tx(&hdr_out->tp_h);
530 if (ctx->randomize)
531 next_rnd_slot(&it_out, &tx_ring);
532 else {
533 it_out++;
534 if (it_out >= tx_ring.layout.tp_frame_nr)
535 it_out = 0;
538 show_frame_hdr(in, hdr_in->tp_h.tp_snaplen,
539 ctx->link_type, hdr_in, ctx->print_mode,
540 ctx->pkts_seen);
542 dissector_entry_point(in, hdr_in->tp_h.tp_snaplen,
543 ctx->link_type, ctx->print_mode,
544 &hdr_in->s_ll);
546 if (frame_count_max != 0) {
547 if (ctx->pkts_seen >= frame_count_max) {
548 sigint = 1;
549 break;
553 next:
554 kernel_may_pull_from_rx(&hdr_in->tp_h);
556 it_in++;
557 if (it_in >= rx_ring.layout.tp_frame_nr)
558 it_in = 0;
560 if (unlikely(sigint == 1))
561 goto out;
564 ret = poll(&rx_poll, 1, -1);
565 if (unlikely(ret < 0)) {
566 if (errno != EINTR)
567 panic("Poll failed!\n");
571 out:
572 timer_purge();
574 dump_rx_stats(ctx, rx_sock, false);
576 bpf_release(&bpf_ops);
578 dissector_cleanup_all();
580 destroy_tx_ring(tx_sock, &tx_ring);
581 destroy_rx_ring(rx_sock, &rx_ring);
583 if (ctx->promiscuous)
584 device_leave_promiscuous_mode(ctx->device_in, ifflags);
586 close(tx_sock);
587 close(rx_sock);
590 static void translate_pcap_to_txf(int fdo, uint8_t *out, size_t len)
592 size_t bytes_done = 0;
593 char bout[80];
595 slprintf(bout, sizeof(bout), "{\n ");
596 write_or_die(fdo, bout, strlen(bout));
598 while (bytes_done < len) {
599 slprintf(bout, sizeof(bout), "0x%02x,", out[bytes_done]);
600 write_or_die(fdo, bout, strlen(bout));
602 bytes_done++;
604 if (bytes_done % 10 == 0) {
605 slprintf(bout, sizeof(bout), "\n");
606 write_or_die(fdo, bout, strlen(bout));
608 if (bytes_done < len) {
609 slprintf(bout, sizeof(bout), " ");
610 write_or_die(fdo, bout, strlen(bout));
612 } else if (bytes_done < len) {
613 slprintf(bout, sizeof(bout), " ");
614 write_or_die(fdo, bout, strlen(bout));
617 if (bytes_done % 10 != 0) {
618 slprintf(bout, sizeof(bout), "\n");
619 write_or_die(fdo, bout, strlen(bout));
622 slprintf(bout, sizeof(bout), "}\n\n");
623 write_or_die(fdo, bout, strlen(bout));
626 static void read_pcap(struct ctx *ctx)
628 uint8_t *out;
629 int ret, fd, fdo = 0;
630 unsigned long trunced = 0;
631 size_t out_len;
632 pcap_pkthdr_t phdr;
633 struct sock_fprog bpf_ops;
634 struct frame_map fm;
635 struct timeval start, end, diff;
636 bool is_out_pcap = ctx->device_out && strstr(ctx->device_out, ".pcap");
637 const struct pcap_file_ops *pcap_out_ops = pcap_ops[PCAP_OPS_RW];
639 bug_on(!__pcap_io);
641 if (!strncmp("-", ctx->device_in, strlen("-"))) {
642 fd = dup_or_die(fileno(stdin));
643 close(fileno(stdin));
644 if (ctx->pcap == PCAP_OPS_MM)
645 ctx->pcap = PCAP_OPS_SG;
646 } else {
647 /* O_NOATIME requires privileges, in case we don't have
648 * them, retry without them at a minor cost of updating
649 * atime in case the fs has been mounted as such.
651 fd = open(ctx->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
652 if (fd < 0 && errno == EPERM)
653 fd = open_or_die(ctx->device_in, O_RDONLY | O_LARGEFILE);
654 if (fd < 0)
655 panic("Cannot open file %s! %s.\n", ctx->device_in,
656 strerror(errno));
659 if (__pcap_io->init_once_pcap)
660 __pcap_io->init_once_pcap(false);
662 ret = __pcap_io->pull_fhdr_pcap(fd, &ctx->magic, &ctx->link_type);
663 if (ret)
664 panic("Error reading pcap header!\n");
666 if (__pcap_io->prepare_access_pcap) {
667 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_RD, ctx->jumbo);
668 if (ret)
669 panic("Error prepare reading pcap!\n");
672 memset(&fm, 0, sizeof(fm));
674 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
675 if (ctx->dump_bpf)
676 bpf_dump_all(&bpf_ops);
678 dissector_init_all(ctx->print_mode);
680 out_len = round_up(1024 * 1024, RUNTIME_PAGE_SIZE);
681 out = xmalloc_aligned(out_len, CO_CACHE_LINE_SIZE);
683 if (ctx->device_out) {
684 if (!strncmp("-", ctx->device_out, strlen("-"))) {
685 fdo = dup_or_die(fileno(stdout));
686 close(fileno(stdout));
687 } else {
688 fdo = open_or_die_m(ctx->device_out, O_RDWR | O_CREAT |
689 O_TRUNC | O_LARGEFILE, DEFFILEMODE);
693 if (is_out_pcap) {
694 ret = pcap_out_ops->push_fhdr_pcap(fdo, ctx->magic,
695 ctx->link_type);
696 if (ret)
697 panic("Error writing pcap header!\n");
700 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
702 printf("Running! Hang up with ^C!\n\n");
703 fflush(stdout);
705 bug_on(gettimeofday(&start, NULL));
707 while (likely(sigint == 0)) {
708 do {
709 ret = __pcap_io->read_pcap(fd, &phdr, ctx->magic,
710 out, out_len);
711 if (unlikely(ret < 0))
712 goto out;
714 if (unlikely(pcap_get_length(&phdr, ctx->magic) == 0)) {
715 trunced++;
716 continue;
719 if (unlikely(pcap_get_length(&phdr, ctx->magic) > out_len)) {
720 pcap_set_length(&phdr, ctx->magic, out_len);
721 trunced++;
723 } while (ctx->filter &&
724 !bpf_run_filter(&bpf_ops, out,
725 pcap_get_length(&phdr, ctx->magic)));
727 pcap_pkthdr_to_tpacket_hdr(&phdr, ctx->magic, &fm.tp_h, &fm.s_ll);
729 ctx->tx_bytes += fm.tp_h.tp_len;
730 ctx->tx_packets++;
732 show_frame_hdr(out, fm.tp_h.tp_snaplen, ctx->link_type, &fm,
733 ctx->print_mode, ctx->tx_packets);
735 dissector_entry_point(out, fm.tp_h.tp_snaplen,
736 ctx->link_type, ctx->print_mode,
737 &fm.s_ll);
739 if (is_out_pcap) {
740 size_t pcap_len = pcap_get_length(&phdr, ctx->magic);
741 int wlen = pcap_out_ops->write_pcap(fdo, &phdr,
742 ctx->magic, out,
743 pcap_len);
744 if (unlikely(wlen != (int)pcap_get_total_length(&phdr, ctx->magic)))
745 panic("Error writing to pcap!\n");
746 } else if (ctx->device_out) {
747 translate_pcap_to_txf(fdo, out, fm.tp_h.tp_snaplen);
750 if (frame_count_max != 0) {
751 if (ctx->tx_packets >= frame_count_max) {
752 sigint = 1;
753 break;
758 out:
759 bug_on(gettimeofday(&end, NULL));
760 timersub(&end, &start, &diff);
762 bpf_release(&bpf_ops);
764 dissector_cleanup_all();
766 if (__pcap_io->prepare_close_pcap)
767 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_RD);
769 xfree(out);
771 fflush(stdout);
772 printf("\n");
773 printf("\r%12lu packets outgoing\n", ctx->tx_packets);
774 printf("\r%12lu packets truncated in file\n", trunced);
775 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
776 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
778 if (!strncmp("-", ctx->device_in, strlen("-")))
779 dup2(fd, fileno(stdin));
780 close(fd);
782 if (ctx->device_out) {
783 if (!strncmp("-", ctx->device_out, strlen("-")))
784 dup2(fdo, fileno(stdout));
785 close(fdo);
789 static void generate_multi_pcap_filename(struct ctx *ctx, char *fname, size_t size, time_t ftime)
791 if (ctx->overwrite_interval > 0) {
792 slprintf(fname, size, "%s/%s%010lu.pcap", ctx->device_out,
793 ctx->prefix, ctx->file_number);
795 ctx->file_number++;
797 if (ctx->file_number >= ctx->overwrite_interval)
798 ctx->file_number = 0;
799 } else {
800 slprintf(fname, size, "%s/%s%lu.pcap", ctx->device_out,
801 ctx->prefix, ftime);
805 static void finish_multi_pcap_file(struct ctx *ctx, int fd)
807 __pcap_io->fsync_pcap(fd);
809 if (__pcap_io->prepare_close_pcap)
810 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
812 close(fd);
814 memset(&itimer, 0, sizeof(itimer));
815 setitimer(ITIMER_REAL, &itimer, NULL);
818 static int next_multi_pcap_file(struct ctx *ctx, int fd)
820 int ret;
821 char fname[PATH_MAX] = {0};
822 time_t ftime;
824 __pcap_io->fsync_pcap(fd);
826 if (__pcap_io->prepare_close_pcap)
827 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
829 close(fd);
831 if (sighup_time > 0) {
832 ftime = (time_t)(start_time + sighup_time);
833 sighup_time = 0;
834 } else
835 ftime = time(NULL);
837 generate_multi_pcap_filename(ctx, fname, sizeof(fname), ftime);
839 fd = open_or_die_m(fname, O_RDWR | O_CREAT | O_TRUNC |
840 O_LARGEFILE, DEFFILEMODE);
842 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
843 if (ret)
844 panic("Error writing pcap header!\n");
846 if (__pcap_io->prepare_access_pcap) {
847 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
848 if (ret)
849 panic("Error prepare writing pcap!\n");
852 return fd;
855 static void reset_interval(struct ctx *ctx)
857 if (ctx->dump_mode == DUMP_INTERVAL_TIME) {
858 interval = ctx->dump_interval;
860 set_itimer_interval_value(&itimer, interval, 0);
861 setitimer(ITIMER_REAL, &itimer, NULL);
862 } else {
863 interval = 0;
867 static int begin_multi_pcap_file(struct ctx *ctx)
869 int fd, ret;
870 char fname[PATH_MAX] = {0};
872 bug_on(!__pcap_io);
874 if (ctx->device_out[strlen(ctx->device_out) - 1] == '/')
875 ctx->device_out[strlen(ctx->device_out) - 1] = 0;
877 generate_multi_pcap_filename(ctx, fname, sizeof(fname), time(NULL));
879 fd = open_or_die_m(fname, O_RDWR | O_CREAT | O_TRUNC |
880 O_LARGEFILE, DEFFILEMODE);
882 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
883 if (ret)
884 panic("Error writing pcap header!\n");
886 if (__pcap_io->prepare_access_pcap) {
887 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
888 if (ret)
889 panic("Error prepare writing pcap!\n");
892 reset_interval(ctx);
894 return fd;
897 static void finish_single_pcap_file(struct ctx *ctx, int fd)
899 __pcap_io->fsync_pcap(fd);
901 if (__pcap_io->prepare_close_pcap)
902 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
904 if (strncmp("-", ctx->device_out, strlen("-")))
905 close(fd);
906 else
907 dup2(fd, fileno(stdout));
910 static int begin_single_pcap_file(struct ctx *ctx)
912 int fd, ret;
913 char fname[PATH_MAX];
915 bug_on(!__pcap_io);
917 if (!strncmp("-", ctx->device_out, strlen("-"))) {
918 fd = dup_or_die(fileno(stdout));
919 close(fileno(stdout));
920 if (ctx->pcap == PCAP_OPS_MM)
921 ctx->pcap = PCAP_OPS_SG;
922 } else {
923 time_t t;
924 struct tm *ltm;
926 t = time(NULL);
927 if (t == -1)
928 panic("time() failed\n");
930 ltm = localtime(&t);
931 if (ltm == NULL)
932 panic("localtime() failed\n");
934 strftime(fname, sizeof(fname), ctx->device_out, ltm);
936 fd = open_or_die_m(fname,
937 O_RDWR | O_CREAT | O_TRUNC |
938 O_LARGEFILE, DEFFILEMODE);
941 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
942 if (ret)
943 panic("Error writing pcap header!\n");
945 if (__pcap_io->prepare_access_pcap) {
946 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
947 if (ret)
948 panic("Error prepare writing pcap!\n");
951 return fd;
954 static void update_pcap_next_dump(struct ctx *ctx, unsigned long snaplen,
955 int *fd, int sock, bool is_v3)
957 if (!dump_to_pcap(ctx))
958 return;
960 if (ctx->dump_mode == DUMP_INTERVAL_SIZE) {
961 interval += snaplen;
962 if (interval > ctx->dump_interval) {
963 next_dump = true;
964 interval = 0;
968 if (sighup) {
969 if (ctx->verbose)
970 printf("SIGHUP received, prematurely rotating pcap\n");
971 sighup = 0;
972 next_dump = true;
973 reset_interval(ctx);
976 if (next_dump) {
977 *fd = next_multi_pcap_file(ctx, *fd);
978 next_dump = false;
980 if (update_rx_stats(ctx, sock, is_v3))
981 return;
983 if (ctx->verbose && ctx->print_mode == PRINT_NONE)
984 printf(".(+%"PRIu64"/-%"PRIu64")",
985 ctx->pkts_recvd_last - ctx->pkts_drops_last,
986 ctx->pkts_drops_last);
990 #ifdef HAVE_TPACKET3
991 static void walk_t3_block(struct block_desc *pbd, struct ctx *ctx,
992 int sock, int *fd)
994 int num_pkts = pbd->h1.num_pkts, i;
995 struct tpacket3_hdr *hdr;
996 struct sockaddr_ll *sll;
998 hdr = (void *) ((uint8_t *) pbd + pbd->h1.offset_to_first_pkt);
999 sll = (void *) ((uint8_t *) hdr + TPACKET_ALIGN(sizeof(*hdr)));
1001 for (i = 0; i < num_pkts && likely(sigint == 0); ++i) {
1002 uint8_t *packet = ((uint8_t *) hdr + hdr->tp_mac);
1003 pcap_pkthdr_t phdr;
1005 if (skip_packet(ctx, sll))
1006 goto next;
1008 ctx->pkts_seen++;
1010 if (dump_to_pcap(ctx)) {
1011 int ret;
1013 tpacket3_hdr_to_pcap_pkthdr(hdr, sll, &phdr, ctx->magic);
1015 ret = __pcap_io->write_pcap(*fd, &phdr, ctx->magic, packet,
1016 pcap_get_length(&phdr, ctx->magic));
1017 if (unlikely(ret != (int) pcap_get_total_length(&phdr, ctx->magic)))
1018 panic("Write error to pcap!\n");
1021 __show_frame_hdr(packet, hdr->tp_snaplen, ctx->link_type, sll,
1022 hdr, ctx->print_mode, true, ctx->pkts_seen);
1024 dissector_entry_point(packet, hdr->tp_snaplen, ctx->link_type,
1025 ctx->print_mode, sll);
1026 next:
1027 hdr = (void *) ((uint8_t *) hdr + hdr->tp_next_offset);
1028 sll = (void *) ((uint8_t *) hdr + TPACKET_ALIGN(sizeof(*hdr)));
1030 if (frame_count_max != 0) {
1031 if (unlikely(ctx->pkts_seen >= frame_count_max)) {
1032 sigint = 1;
1033 break;
1037 update_pcap_next_dump(ctx, hdr->tp_snaplen, fd, sock, true);
1040 #endif /* HAVE_TPACKET3 */
1042 static void recv_only_or_dump(struct ctx *ctx)
1044 short ifflags = 0;
1045 int sock, ifindex, fd = 0, ret;
1046 size_t size;
1047 unsigned int it = 0;
1048 struct ring rx_ring;
1049 struct pollfd rx_poll;
1050 struct sock_fprog bpf_ops;
1051 struct timeval start, end, diff;
1052 bool is_v3 = is_defined(HAVE_TPACKET3);
1054 sock = pf_socket_type(ctx->link_type);
1056 ifindex = device_ifindex(ctx->device_in);
1057 size = ring_size(ctx->device_in, ctx->reserve_size);
1059 enable_kernel_bpf_jit_compiler();
1061 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
1062 if (ctx->dump_bpf)
1063 bpf_dump_all(&bpf_ops);
1064 bpf_attach_to_sock(sock, &bpf_ops);
1066 if (ctx->hwtimestamp) {
1067 ret = set_sockopt_hwtimestamp(sock, ctx->device_in);
1068 if (ret == 0 && ctx->verbose)
1069 printf("HW timestamping enabled\n");
1072 ring_rx_setup(&rx_ring, sock, size, ifindex, &rx_poll, is_v3, true,
1073 ctx->verbose, ctx->fanout_group, ctx->fanout_type);
1075 dissector_init_all(ctx->print_mode);
1077 if (ctx->cpu >= 0 && ifindex > 0) {
1078 int irq = device_irq_number(ctx->device_in);
1079 device_set_irq_affinity(irq, ctx->cpu);
1081 if (ctx->verbose)
1082 printf("IRQ: %s:%d > CPU%d\n",
1083 ctx->device_in, irq, ctx->cpu);
1086 if (ctx->promiscuous)
1087 ifflags = device_enter_promiscuous_mode(ctx->device_in);
1089 if (dump_to_pcap(ctx) && __pcap_io->init_once_pcap)
1090 __pcap_io->init_once_pcap(true);
1092 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
1094 if (dump_to_pcap(ctx)) {
1095 struct stat stats;
1097 ret = stat(ctx->device_out, &stats);
1098 if (ret < 0)
1099 ctx->dump_dir = 0;
1100 else
1101 ctx->dump_dir = S_ISDIR(stats.st_mode);
1103 if (ctx->dump_dir)
1104 fd = begin_multi_pcap_file(ctx);
1105 else
1106 fd = begin_single_pcap_file(ctx);
1109 printf("Running! Hang up with ^C!\n\n");
1110 fflush(stdout);
1112 bug_on(gettimeofday(&start, NULL));
1114 while (likely(sigint == 0)) {
1115 #ifdef HAVE_TPACKET3
1116 struct block_desc *pbd;
1118 while (user_may_pull_from_rx_block((pbd = rx_ring.frames[it].iov_base))) {
1119 walk_t3_block(pbd, ctx, sock, &fd);
1121 kernel_may_pull_from_rx_block(pbd);
1122 it = (it + 1) % rx_ring.layout3.tp_block_nr;
1124 if (unlikely(sigint == 1))
1125 break;
1127 #else
1128 while (user_may_pull_from_rx(rx_ring.frames[it].iov_base)) {
1129 struct frame_map *hdr = rx_ring.frames[it].iov_base;
1130 uint8_t *packet = ((uint8_t *) hdr) + hdr->tp_h.tp_mac;
1131 pcap_pkthdr_t phdr;
1133 if (skip_packet(ctx, &hdr->s_ll))
1134 goto next;
1136 ctx->pkts_seen++;
1138 if (unlikely(ring_frame_size(&rx_ring) < hdr->tp_h.tp_snaplen)) {
1139 /* XXX: silently ignore for now. We used to
1140 * report them with dump_rx_stats() */
1141 goto next;
1144 if (dump_to_pcap(ctx)) {
1145 tpacket_hdr_to_pcap_pkthdr(&hdr->tp_h, &hdr->s_ll, &phdr, ctx->magic);
1147 ret = __pcap_io->write_pcap(fd, &phdr, ctx->magic, packet,
1148 pcap_get_length(&phdr, ctx->magic));
1149 if (unlikely(ret != (int) pcap_get_total_length(&phdr, ctx->magic)))
1150 panic("Write error to pcap!\n");
1153 show_frame_hdr(packet, hdr->tp_h.tp_snaplen,
1154 ctx->link_type, hdr, ctx->print_mode,
1155 ctx->pkts_seen);
1157 dissector_entry_point(packet, hdr->tp_h.tp_snaplen,
1158 ctx->link_type, ctx->print_mode,
1159 &hdr->s_ll);
1161 if (frame_count_max != 0) {
1162 if (unlikely(ctx->pkts_seen >= frame_count_max)) {
1163 sigint = 1;
1164 break;
1168 next:
1169 kernel_may_pull_from_rx(&hdr->tp_h);
1170 it = (it + 1) % rx_ring.layout.tp_frame_nr;
1172 if (unlikely(sigint == 1))
1173 break;
1175 update_pcap_next_dump(ctx, hdr->tp_h.tp_snaplen, &fd,
1176 sock, is_v3);
1178 #endif /* HAVE_TPACKET3 */
1180 ret = poll(&rx_poll, 1, -1);
1181 if (unlikely(ret < 0)) {
1182 if (errno != EINTR)
1183 panic("Poll failed!\n");
1187 bug_on(gettimeofday(&end, NULL));
1188 timersub(&end, &start, &diff);
1190 dump_rx_stats(ctx, sock, is_v3);
1191 printf("\r%12lu sec, %lu usec in total\n",
1192 diff.tv_sec, diff.tv_usec);
1194 bpf_release(&bpf_ops);
1195 dissector_cleanup_all();
1196 destroy_rx_ring(sock, &rx_ring);
1198 if (ctx->promiscuous)
1199 device_leave_promiscuous_mode(ctx->device_in, ifflags);
1201 if (ctx->rfraw)
1202 leave_rfmon_mac80211(ctx->device_in);
1204 if (dump_to_pcap(ctx)) {
1205 if (ctx->dump_dir)
1206 finish_multi_pcap_file(ctx, fd);
1207 else
1208 finish_single_pcap_file(ctx, fd);
1211 close(sock);
1214 static void init_ctx(struct ctx *ctx)
1216 memset(ctx, 0, sizeof(*ctx));
1218 ctx->uid = getuid();
1219 ctx->gid = getgid();
1221 ctx->cpu = -1;
1222 ctx->packet_type = -1;
1224 ctx->fanout_type = PACKET_FANOUT_ROLLOVER;
1226 ctx->magic = ORIGINAL_TCPDUMP_MAGIC;
1227 ctx->print_mode = PRINT_NORM;
1228 ctx->pcap = PCAP_OPS_SG;
1230 ctx->dump_mode = DUMP_INTERVAL_TIME;
1231 ctx->dump_interval = 60;
1233 ctx->promiscuous = true;
1234 ctx->randomize = false;
1235 ctx->hwtimestamp = true;
1238 static void destroy_ctx(struct ctx *ctx)
1240 free(ctx->device_in);
1241 free(ctx->device_out);
1242 free(ctx->device_trans);
1244 free(ctx->prefix);
1247 static void __noreturn help(void)
1249 printf("netsniff-ng %s, the packet sniffing beast\n", VERSION_STRING);
1250 puts("http://www.netsniff-ng.org\n\n"
1251 "Usage: netsniff-ng [options] [filter-expression]\n"
1252 "Options:\n"
1253 " -i|-d|--dev|--in <dev|pcap|-> Input source as netdev, pcap or pcap stdin\n"
1254 " -o|--out <dev|pcap|dir|cfg|-> Output sink as netdev, pcap, directory, trafgen, or stdout\n"
1255 " -C|--fanout-group <id> Join packet fanout group\n"
1256 " -K|--fanout-type <type> Apply fanout discipline: hash|lb|cpu|rnd|roll|qm\n"
1257 " -L|--fanout-opts <opts> Additional fanout options: defrag|roll\n"
1258 " -f|--filter <bpf-file|-|expr> Use BPF filter from bpfc file/stdin or tcpdump-like expression\n"
1259 " -t|--type <type> Filter for: host|broadcast|multicast|others|outgoing\n"
1260 " -F|--interval <size|time> Dump interval if -o is a dir: <num>KiB/MiB/GiB/s/sec/min/hrs\n"
1261 " -R|--rfraw Capture or inject raw 802.11 frames\n"
1262 " -n|--num <0|uint> Number of packets until exit (def: 0)\n"
1263 " -P|--prefix <name> Prefix for pcaps stored in directory\n"
1264 " -O|--overwrite <N> Limit the number of pcaps to N (file names use numbers 0 to N-1)\n"
1265 " -T|--magic <pcap-magic> Pcap magic number/pcap format to store, see -D\n"
1266 " -w|--cooked Use Linux \"cooked\" header instead of link header\n"
1267 " -D|--dump-pcap-types Dump pcap types and magic numbers and quit\n"
1268 " -B|--dump-bpf Dump generated BPF assembly\n"
1269 " -r|--rand Randomize packet forwarding order (dev->dev)\n"
1270 " -M|--no-promisc No promiscuous mode for netdev\n"
1271 " -A|--no-sock-mem Don't tune core socket memory\n"
1272 " -N|--no-hwtimestamp Disable hardware time stamping\n"
1273 " -m|--mmap Mmap(2) pcap file I/O, e.g. for replaying pcaps\n"
1274 " -G|--sg Scatter/gather pcap file I/O\n"
1275 " -c|--clrw Use slower read(2)/write(2) I/O\n"
1276 " -S|--ring-size <size> Specify ring size to: <num>KiB/MiB/GiB\n"
1277 " -k|--kernel-pull <uint> Kernel pull from user interval in us (def: 10us)\n"
1278 " -J|--jumbo-support Support replay/fwd 64KB Super Jumbo Frames (def: 2048B)\n"
1279 " -b|--bind-cpu <cpu> Bind to specific CPU\n"
1280 " -u|--user <userid> Drop privileges and change to userid\n"
1281 " -g|--group <groupid> Drop privileges and change to groupid\n"
1282 " -H|--prio-high Make this high priority process\n"
1283 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
1284 " -s|--silent Do not print captured packets\n"
1285 " -q|--less Print less-verbose packet information\n"
1286 " -X|--hex Print packet data in hex format\n"
1287 " -l|--ascii Print human-readable packet data\n"
1288 " -U|--update Update GeoIP databases\n"
1289 " -V|--verbose Be more verbose\n"
1290 " -v|--version Show version and exit\n"
1291 " -h|--help Guess what?!\n\n"
1292 "Examples:\n"
1293 " netsniff-ng --in eth0 --out dump.pcap -s -T 0xa1b2c3d4 --bind-cpu 0 tcp or udp\n"
1294 " netsniff-ng --in wlan0 --rfraw --out dump.pcap --silent --bind-cpu 0\n"
1295 " netsniff-ng --in dump.pcap --mmap --out eth0 -k1000 --silent --bind-cpu 0\n"
1296 " netsniff-ng --in dump.pcap --out dump.cfg --silent --bind-cpu 0\n"
1297 " netsniff-ng --in dump.pcap --out dump2.pcap --silent tcp\n"
1298 " netsniff-ng --in eth0 --out eth1 --silent --bind-cpu 0 -J --type host\n"
1299 " netsniff-ng --in eth1 --out /opt/probe/ -s -m --interval 100MiB -b 0\n"
1300 " netsniff-ng --in vlan0 --out dump.pcap -c -u `id -u bob` -g `id -g bob`\n"
1301 " netsniff-ng --in any --filter http.bpf --jumbo-support --ascii -V\n\n"
1302 "Note:\n"
1303 " For introducing bit errors, delays with random variation and more\n"
1304 " while replaying pcaps, make use of tc(8) with its disciplines (e.g. netem).\n");
1305 puts(copyright);
1306 die();
1309 static void __noreturn version(void)
1311 printf("netsniff-ng %s, Git id: %s\n", VERSION_LONG, GITVERSION);
1312 puts("the packet sniffing beast\n"
1313 "http://www.netsniff-ng.org\n");
1314 puts(copyright);
1315 die();
1318 int main(int argc, char **argv)
1320 char *ptr;
1321 int c, i, j, cpu_tmp, ops_touched = 0, vals[4] = {0};
1322 bool prio_high = false, setsockmem = true;
1323 void (*main_loop)(struct ctx *ctx) = NULL;
1324 struct ctx ctx;
1326 init_ctx(&ctx);
1327 start_time = time(NULL);
1328 srand(start_time);
1330 while ((c = getopt_long(argc, argv, short_options, long_options,
1331 NULL)) != EOF) {
1332 switch (c) {
1333 case 'd':
1334 case 'i':
1335 ctx.device_in = xstrdup(optarg);
1336 break;
1337 case 'o':
1338 ctx.device_out = xstrdup(optarg);
1339 break;
1340 case 'P':
1341 ctx.prefix = xstrdup(optarg);
1342 break;
1343 case 'O':
1344 ctx.overwrite_interval = strtoul(optarg, NULL, 0);
1345 break;
1346 case 'R':
1347 ctx.rfraw = 1;
1348 break;
1349 case 'r':
1350 ctx.randomize = true;
1351 break;
1352 case 'J':
1353 ctx.jumbo = true;
1354 break;
1355 case 'T':
1356 ctx.magic = (uint32_t) strtoul(optarg, NULL, 0);
1357 pcap_check_magic(ctx.magic);
1358 break;
1359 case 'f':
1360 ctx.filter = xstrdup(optarg);
1361 break;
1362 case 'M':
1363 ctx.promiscuous = false;
1364 break;
1365 case 'N':
1366 ctx.hwtimestamp = false;
1367 break;
1368 case 'A':
1369 setsockmem = false;
1370 break;
1371 case 'u':
1372 ctx.uid = strtoul(optarg, NULL, 0);
1373 ctx.enforce = true;
1374 break;
1375 case 'g':
1376 ctx.gid = strtoul(optarg, NULL, 0);
1377 ctx.enforce = true;
1378 break;
1379 case 'C':
1380 ctx.fanout_group = strtoul(optarg, NULL, 0);
1381 if (ctx.fanout_group == 0)
1382 panic("Non-zero fanout group id required!\n");
1383 break;
1384 case 'K':
1385 if (!strncmp(optarg, "hash", strlen("hash")))
1386 ctx.fanout_type = PACKET_FANOUT_HASH;
1387 else if (!strncmp(optarg, "lb", strlen("lb")) ||
1388 !strncmp(optarg, "rr", strlen("rr")))
1389 ctx.fanout_type = PACKET_FANOUT_LB;
1390 else if (!strncmp(optarg, "cpu", strlen("cpu")))
1391 ctx.fanout_type = PACKET_FANOUT_CPU;
1392 else if (!strncmp(optarg, "rnd", strlen("rnd")))
1393 ctx.fanout_type = PACKET_FANOUT_RND;
1394 else if (!strncmp(optarg, "roll", strlen("roll")))
1395 ctx.fanout_type = PACKET_FANOUT_ROLLOVER;
1396 else if (!strncmp(optarg, "qm", strlen("qm")))
1397 ctx.fanout_type = PACKET_FANOUT_QM;
1398 else
1399 panic("Unknown fanout type!\n");
1400 break;
1401 case 'L':
1402 if (!strncmp(optarg, "defrag", strlen("defrag")))
1403 ctx.fanout_type |= PACKET_FANOUT_FLAG_DEFRAG;
1404 else if (!strncmp(optarg, "roll", strlen("roll")))
1405 ctx.fanout_type |= PACKET_FANOUT_FLAG_ROLLOVER;
1406 else
1407 panic("Unknown fanout option!\n");
1408 break;
1409 case 't':
1410 if (!strncmp(optarg, "host", strlen("host")))
1411 ctx.packet_type = PACKET_HOST;
1412 else if (!strncmp(optarg, "broadcast", strlen("broadcast")))
1413 ctx.packet_type = PACKET_BROADCAST;
1414 else if (!strncmp(optarg, "multicast", strlen("multicast")))
1415 ctx.packet_type = PACKET_MULTICAST;
1416 else if (!strncmp(optarg, "others", strlen("others")))
1417 ctx.packet_type = PACKET_OTHERHOST;
1418 else if (!strncmp(optarg, "outgoing", strlen("outgoing")))
1419 ctx.packet_type = PACKET_OUTGOING;
1420 else
1421 ctx.packet_type = -1;
1422 break;
1423 case 'S':
1424 ptr = optarg;
1425 for (j = i = strlen(optarg); i > 0; --i) {
1426 if (!isdigit(optarg[j - i]))
1427 break;
1428 ptr++;
1431 if (!strncmp(ptr, "KiB", strlen("KiB")))
1432 ctx.reserve_size = 1 << 10;
1433 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1434 ctx.reserve_size = 1 << 20;
1435 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1436 ctx.reserve_size = 1 << 30;
1437 else
1438 panic("Syntax error in ring size param!\n");
1440 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1441 break;
1442 case 'b':
1443 cpu_tmp = strtol(optarg, NULL, 0);
1445 cpu_affinity(cpu_tmp);
1446 if (ctx.cpu != -2)
1447 ctx.cpu = cpu_tmp;
1448 break;
1449 case 'H':
1450 prio_high = true;
1451 break;
1452 case 'c':
1453 ctx.pcap = PCAP_OPS_RW;
1454 ops_touched = 1;
1455 break;
1456 case 'm':
1457 ctx.pcap = PCAP_OPS_MM;
1458 ops_touched = 1;
1459 break;
1460 case 'G':
1461 ctx.pcap = PCAP_OPS_SG;
1462 ops_touched = 1;
1463 break;
1464 case 'Q':
1465 ctx.cpu = -2;
1466 break;
1467 case 's':
1468 ctx.print_mode = PRINT_NONE;
1469 break;
1470 case 'q':
1471 ctx.print_mode = PRINT_LESS;
1472 break;
1473 case 'X':
1474 ctx.print_mode =
1475 (ctx.print_mode == PRINT_ASCII) ?
1476 PRINT_HEX_ASCII : PRINT_HEX;
1477 break;
1478 case 'l':
1479 ctx.print_mode =
1480 (ctx.print_mode == PRINT_HEX) ?
1481 PRINT_HEX_ASCII : PRINT_ASCII;
1482 break;
1483 case 'k':
1484 ctx.kpull = strtoul(optarg, NULL, 0);
1485 break;
1486 case 'n':
1487 frame_count_max = strtoul(optarg, NULL, 0);
1488 break;
1489 case 'F':
1490 ptr = optarg;
1491 for (j = i = strlen(optarg); i > 0; --i) {
1492 if (!isdigit(optarg[j - i]))
1493 break;
1494 ptr++;
1497 if (!strncmp(ptr, "KiB", strlen("KiB"))) {
1498 ctx.dump_interval = 1 << 10;
1499 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1500 } else if (!strncmp(ptr, "MiB", strlen("MiB"))) {
1501 ctx.dump_interval = 1 << 20;
1502 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1503 } else if (!strncmp(ptr, "GiB", strlen("GiB"))) {
1504 ctx.dump_interval = 1 << 30;
1505 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1506 } else if (!strncmp(ptr, "sec", strlen("sec"))) {
1507 ctx.dump_interval = 1;
1508 ctx.dump_mode = DUMP_INTERVAL_TIME;
1509 } else if (!strncmp(ptr, "min", strlen("min"))) {
1510 ctx.dump_interval = 60;
1511 ctx.dump_mode = DUMP_INTERVAL_TIME;
1512 } else if (!strncmp(ptr, "hrs", strlen("hrs"))) {
1513 ctx.dump_interval = 60 * 60;
1514 ctx.dump_mode = DUMP_INTERVAL_TIME;
1515 } else if (!strncmp(ptr, "s", strlen("s"))) {
1516 ctx.dump_interval = 1;
1517 ctx.dump_mode = DUMP_INTERVAL_TIME;
1518 } else {
1519 panic("Syntax error in time/size param!\n");
1522 ctx.dump_interval *= strtoul(optarg, NULL, 0);
1523 break;
1524 case 'V':
1525 ctx.verbose = true;
1526 break;
1527 case 'B':
1528 ctx.dump_bpf = true;
1529 break;
1530 case 'D':
1531 pcap_dump_type_features();
1532 die();
1533 break;
1534 case 'U':
1535 update_geoip();
1536 die();
1537 break;
1538 case 'w':
1539 ctx.link_type = LINKTYPE_LINUX_SLL;
1540 break;
1541 case 'v':
1542 version();
1543 break;
1544 case 'h':
1545 help();
1546 break;
1547 case '?':
1548 switch (optopt) {
1549 case 'd':
1550 case 'i':
1551 case 'o':
1552 case 'f':
1553 case 't':
1554 case 'P':
1555 case 'O':
1556 case 'F':
1557 case 'n':
1558 case 'S':
1559 case 'b':
1560 case 'k':
1561 case 'T':
1562 case 'u':
1563 case 'g':
1564 case 'e':
1565 panic("Option -%c requires an argument!\n",
1566 optopt);
1567 default:
1568 if (isprint(optopt))
1569 printf("Unknown option character `0x%X\'!\n", optopt);
1570 die();
1572 default:
1573 break;
1577 if (!ctx.filter && optind != argc)
1578 ctx.filter = argv2str(optind, argc, argv);
1580 if (!ctx.device_in)
1581 ctx.device_in = xstrdup("any");
1583 if (!strcmp(ctx.device_in, "any") || !strcmp(ctx.device_in, "lo"))
1584 ctx.lo_ifindex = device_ifindex("lo");
1586 if (!ctx.prefix)
1587 ctx.prefix = xstrdup("dump-");
1589 register_signal(SIGINT, signal_handler);
1590 register_signal(SIGQUIT, signal_handler);
1591 register_signal(SIGTERM, signal_handler);
1592 register_signal(SIGHUP, signal_handler);
1594 tprintf_init();
1596 if (prio_high) {
1597 set_proc_prio(-20);
1598 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1601 if (device_mtu(ctx.device_in) || !strncmp("any", ctx.device_in, strlen(ctx.device_in))) {
1602 if (ctx.rfraw)
1603 setup_rfmon_mac80211_dev(&ctx, &ctx.device_in);
1605 if (!ctx.link_type)
1606 ctx.link_type = pcap_dev_to_linktype(ctx.device_in);
1607 if (link_has_sll_hdr(ctx.link_type)) {
1608 switch (ctx.magic) {
1609 case ORIGINAL_TCPDUMP_MAGIC:
1610 ctx.magic = ORIGINAL_TCPDUMP_MAGIC_LL;
1611 break;
1612 case NSEC_TCPDUMP_MAGIC:
1613 ctx.magic = NSEC_TCPDUMP_MAGIC_LL;
1614 break;
1615 case ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC):
1616 ctx.magic = ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC_LL);
1617 break;
1618 case ___constant_swab32(NSEC_TCPDUMP_MAGIC):
1619 ctx.magic = ___constant_swab32(NSEC_TCPDUMP_MAGIC_LL);
1620 break;
1625 if (!ctx.device_out) {
1626 ctx.dump = 0;
1627 main_loop = recv_only_or_dump;
1628 } else if (device_mtu(ctx.device_out)) {
1629 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1630 main_loop = receive_to_xmit;
1631 } else {
1632 ctx.dump = 1;
1633 register_signal_f(SIGALRM, timer_next_dump, SA_SIGINFO);
1634 main_loop = recv_only_or_dump;
1635 if (!ops_touched)
1636 ctx.pcap = PCAP_OPS_SG;
1638 } else {
1639 if (ctx.device_out && device_mtu(ctx.device_out)) {
1640 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1641 main_loop = pcap_to_xmit;
1642 if (!ops_touched)
1643 ctx.pcap = PCAP_OPS_MM;
1644 } else {
1645 setsockmem = false;
1646 main_loop = read_pcap;
1647 if (!ops_touched)
1648 ctx.pcap = PCAP_OPS_SG;
1652 bug_on(!main_loop);
1654 init_geoip(0);
1655 if (setsockmem)
1656 set_system_socket_memory(vals, array_size(vals));
1657 if (!ctx.enforce)
1658 xlockme();
1660 if (ctx.verbose)
1661 printf("pcap file I/O method: %s\n", pcap_ops_group_to_str[ctx.pcap]);
1663 main_loop(&ctx);
1665 if (!ctx.enforce)
1666 xunlockme();
1667 if (setsockmem)
1668 reset_system_socket_memory(vals, array_size(vals));
1669 destroy_geoip();
1671 device_restore_irq_affinity_list();
1672 tprintf_cleanup();
1674 destroy_ctx(&ctx);
1675 return 0;