curvetun: Don't attempt to close negative file descriptor
[netsniff-ng.git] / netsniff-ng.c
blob3b69c8f6e2983a64a957315fc4208143672df9df
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;
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;
75 static const char *short_options =
76 "d:i:o:rf:MNJt:S:k:n:b:HQmcsqXlvhF:RGAP:Vu:g:T:DBUC:K:L:w";
77 static const struct option long_options[] = {
78 {"dev", required_argument, NULL, 'd'},
79 {"in", required_argument, NULL, 'i'},
80 {"out", required_argument, NULL, 'o'},
81 {"filter", required_argument, NULL, 'f'},
82 {"num", required_argument, NULL, 'n'},
83 {"type", required_argument, NULL, 't'},
84 {"interval", required_argument, NULL, 'F'},
85 {"ring-size", required_argument, NULL, 'S'},
86 {"kernel-pull", required_argument, NULL, 'k'},
87 {"bind-cpu", required_argument, NULL, 'b'},
88 {"prefix", required_argument, NULL, 'P'},
89 {"user", required_argument, NULL, 'u'},
90 {"group", required_argument, NULL, 'g'},
91 {"magic", required_argument, NULL, 'T'},
92 {"fanout-group", required_argument, NULL, 'C'},
93 {"fanout-type", required_argument, NULL, 'K'},
94 {"fanout-opts", required_argument, NULL, 'L'},
95 {"rand", no_argument, NULL, 'r'},
96 {"rfraw", no_argument, NULL, 'R'},
97 {"mmap", no_argument, NULL, 'm'},
98 {"sg", no_argument, NULL, 'G'},
99 {"clrw", no_argument, NULL, 'c'},
100 {"jumbo-support", no_argument, NULL, 'J'},
101 {"no-promisc", no_argument, NULL, 'M'},
102 {"no-hwtimestamp", no_argument, NULL, 'N'},
103 {"prio-high", no_argument, NULL, 'H'},
104 {"notouch-irq", no_argument, NULL, 'Q'},
105 {"dump-pcap-types", no_argument, NULL, 'D'},
106 {"dump-bpf", no_argument, NULL, 'B'},
107 {"silent", no_argument, NULL, 's'},
108 {"less", no_argument, NULL, 'q'},
109 {"hex", no_argument, NULL, 'X'},
110 {"ascii", no_argument, NULL, 'l'},
111 {"no-sock-mem", no_argument, NULL, 'A'},
112 {"update", no_argument, NULL, 'U'},
113 {"cooked", no_argument, NULL, 'w'},
114 {"verbose", no_argument, NULL, 'V'},
115 {"version", no_argument, NULL, 'v'},
116 {"help", no_argument, NULL, 'h'},
117 {NULL, 0, NULL, 0}
120 static const char *copyright = "Please report bugs to <bugs@netsniff-ng.org>\n"
121 "Copyright (C) 2009-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
122 "Copyright (C) 2009-2012 Emmanuel Roullit <emmanuel.roullit@gmail.com>\n"
123 "Copyright (C) 2012 Markus Amend <markus@netsniff-ng.org>\n"
124 "Swiss federal institute of technology (ETH Zurich)\n"
125 "License: GNU GPL version 2.0\n"
126 "This is free software: you are free to change and redistribute it.\n"
127 "There is NO WARRANTY, to the extent permitted by law.";
129 static int tx_sock;
130 static struct itimerval itimer;
131 static unsigned long frame_count_max = 0, interval = TX_KERNEL_PULL_INT;
133 #define __pcap_io pcap_ops[ctx->pcap]
135 static void signal_handler(int number)
137 switch (number) {
138 case SIGINT:
139 case SIGQUIT:
140 case SIGTERM:
141 sigint = 1;
142 break;
143 case SIGHUP:
144 sighup = 1;
145 break;
146 default:
147 break;
151 static void timer_elapsed(int unused __maybe_unused)
153 int ret;
155 set_itimer_interval_value(&itimer, 0, interval);
157 ret = pull_and_flush_tx_ring(tx_sock);
158 if (unlikely(ret < 0)) {
159 /* We could hit EBADF if the socket has been closed before
160 * the timer was triggered.
162 if (errno != EBADF && errno != ENOBUFS)
163 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
166 setitimer(ITIMER_REAL, &itimer, NULL);
169 static void timer_purge(void)
171 int ret;
173 ret = pull_and_flush_tx_ring_wait(tx_sock);
174 if (unlikely(ret < 0)) {
175 if (errno != EBADF && errno != ENOBUFS)
176 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
179 set_itimer_interval_value(&itimer, 0, 0);
180 setitimer(ITIMER_REAL, &itimer, NULL);
183 static void timer_next_dump(int unused __maybe_unused)
185 set_itimer_interval_value(&itimer, interval, 0);
186 next_dump = true;
187 setitimer(ITIMER_REAL, &itimer, NULL);
190 static inline bool dump_to_pcap(struct ctx *ctx)
192 return ctx->dump;
195 static void on_panic_del_rfmon(void *arg)
197 leave_rfmon_mac80211(arg);
200 static inline void setup_rfmon_mac80211_dev(struct ctx *ctx, char **rfmon_dev)
202 ctx->device_trans = xstrdup(*rfmon_dev);
203 xfree(*rfmon_dev);
205 enter_rfmon_mac80211(ctx->device_trans, rfmon_dev);
206 panic_handler_add(on_panic_del_rfmon, *rfmon_dev);
209 static int update_rx_stats(struct ctx *ctx, int sock, bool is_v3)
211 uint64_t packets, drops;
212 int ret;
214 ret = get_rx_net_stats(sock, &packets, &drops, is_v3);
215 if (ret)
216 return ret;
218 ctx->pkts_recvd += packets;
219 ctx->pkts_drops += drops;
220 ctx->pkts_recvd_last = packets;
221 ctx->pkts_drops_last = drops;
223 return 0;
226 static void dump_rx_stats(struct ctx *ctx, int sock, bool is_v3)
228 if (update_rx_stats(ctx, sock, is_v3))
229 return;
231 printf("\r%12"PRIu64" packets incoming (%"PRIu64" unread on exit)\n",
232 is_v3 ? ctx->pkts_seen : ctx->pkts_recvd,
233 is_v3 ? ctx->pkts_recvd - ctx->pkts_seen : 0);
234 printf("\r%12"PRIu64" packets passed filter\n",
235 ctx->pkts_recvd - ctx->pkts_drops);
236 printf("\r%12"PRIu64" packets failed filter (out of space)\n",
237 ctx->pkts_drops);
239 if (ctx->pkts_recvd > 0)
240 printf("\r%12.4lf%% packet droprate\n",
241 (1.0 * ctx->pkts_drops / ctx->pkts_recvd) * 100.0);
244 static void pcap_to_xmit(struct ctx *ctx)
246 uint8_t *out = NULL;
247 int ifindex, fd = 0, ret;
248 size_t size;
249 unsigned int it = 0;
250 unsigned long trunced = 0;
251 struct ring tx_ring;
252 struct frame_map *hdr;
253 struct sock_fprog bpf_ops;
254 struct timeval start, end, diff;
255 pcap_pkthdr_t phdr;
257 if (!device_up_and_running(ctx->device_out) && !ctx->rfraw)
258 panic("Device not up and running!\n");
260 bug_on(!__pcap_io);
262 tx_sock = pf_socket();
264 if (!strncmp("-", ctx->device_in, strlen("-"))) {
265 fd = dup_or_die(fileno(stdin));
266 close(fileno(stdin));
267 if (ctx->pcap == PCAP_OPS_MM)
268 ctx->pcap = PCAP_OPS_SG;
269 } else {
270 fd = open_or_die(ctx->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
273 if (__pcap_io->init_once_pcap)
274 __pcap_io->init_once_pcap(true);
276 ret = __pcap_io->pull_fhdr_pcap(fd, &ctx->magic, &ctx->link_type);
277 if (ret)
278 panic("Error reading pcap header!\n");
280 if (__pcap_io->prepare_access_pcap) {
281 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_RD, ctx->jumbo);
282 if (ret)
283 panic("Error prepare reading pcap!\n");
286 if (ctx->rfraw) {
287 setup_rfmon_mac80211_dev(ctx, &ctx->device_out);
289 if (ctx->link_type != LINKTYPE_IEEE802_11 &&
290 ctx->link_type != LINKTYPE_IEEE802_11_RADIOTAP)
291 panic("Wrong linktype of pcap!\n");
294 ifindex = device_ifindex(ctx->device_out);
295 size = ring_size(ctx->device_out, ctx->reserve_size);
297 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
298 if (ctx->dump_bpf)
299 bpf_dump_all(&bpf_ops);
301 ring_tx_setup(&tx_ring, tx_sock, size, ifindex, ctx->jumbo, ctx->verbose);
303 dissector_init_all(ctx->print_mode);
305 if (ctx->cpu >= 0 && ifindex > 0) {
306 int irq = device_irq_number(ctx->device_out);
307 device_set_irq_affinity(irq, ctx->cpu);
309 if (ctx->verbose)
310 printf("IRQ: %s:%d > CPU%d\n",
311 ctx->device_out, irq, ctx->cpu);
314 if (ctx->kpull)
315 interval = ctx->kpull;
317 set_itimer_interval_value(&itimer, 0, interval);
318 setitimer(ITIMER_REAL, &itimer, NULL);
320 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
322 printf("Running! Hang up with ^C!\n\n");
323 fflush(stdout);
325 bug_on(gettimeofday(&start, NULL));
327 while (likely(sigint == 0)) {
328 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
329 hdr = tx_ring.frames[it].iov_base;
330 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
332 do {
333 ret = __pcap_io->read_pcap(fd, &phdr, ctx->magic, out,
334 ring_frame_size(&tx_ring));
335 if (unlikely(ret <= 0))
336 goto out;
338 if (ring_frame_size(&tx_ring) <
339 pcap_get_length(&phdr, ctx->magic)) {
340 pcap_set_length(&phdr, ctx->magic,
341 ring_frame_size(&tx_ring));
342 trunced++;
344 } while (ctx->filter &&
345 !bpf_run_filter(&bpf_ops, out,
346 pcap_get_length(&phdr, ctx->magic)));
348 pcap_pkthdr_to_tpacket_hdr(&phdr, ctx->magic, &hdr->tp_h, NULL);
350 ctx->tx_bytes += hdr->tp_h.tp_len;;
351 ctx->tx_packets++;
353 show_frame_hdr(out, hdr->tp_h.tp_snaplen,
354 ctx->link_type, hdr, ctx->print_mode,
355 ctx->tx_packets);
357 dissector_entry_point(out, hdr->tp_h.tp_snaplen,
358 ctx->link_type, ctx->print_mode,
359 &hdr->s_ll);
361 kernel_may_pull_from_tx(&hdr->tp_h);
363 it++;
364 if (it >= tx_ring.layout.tp_frame_nr)
365 it = 0;
367 if (unlikely(sigint == 1))
368 break;
370 if (frame_count_max != 0) {
371 if (ctx->tx_packets >= frame_count_max) {
372 sigint = 1;
373 break;
379 out:
380 bug_on(gettimeofday(&end, NULL));
381 timersub(&end, &start, &diff);
383 timer_purge();
385 bpf_release(&bpf_ops);
387 dissector_cleanup_all();
388 destroy_tx_ring(tx_sock, &tx_ring);
390 if (ctx->rfraw)
391 leave_rfmon_mac80211(ctx->device_out);
393 if (__pcap_io->prepare_close_pcap)
394 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_RD);
396 if (!strncmp("-", ctx->device_in, strlen("-")))
397 dup2(fd, fileno(stdin));
398 close(fd);
400 close(tx_sock);
402 fflush(stdout);
403 printf("\n");
404 printf("\r%12lu packets outgoing\n", ctx->tx_packets);
405 printf("\r%12lu packets truncated in file\n", trunced);
406 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
407 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
410 static void receive_to_xmit(struct ctx *ctx)
412 short ifflags = 0;
413 uint8_t *in, *out;
414 int rx_sock, ifindex_in, ifindex_out, ret;
415 size_t size_in, size_out;
416 unsigned int it_in = 0, it_out = 0;
417 struct frame_map *hdr_in, *hdr_out;
418 struct ring tx_ring, rx_ring;
419 struct pollfd rx_poll;
420 struct sock_fprog bpf_ops;
422 if (!strncmp(ctx->device_in, ctx->device_out, IFNAMSIZ))
423 panic("Ingress/egress devices must be different!\n");
424 if (!device_up_and_running(ctx->device_out))
425 panic("Egress device not up and running!\n");
427 rx_sock = pf_socket();
428 tx_sock = pf_socket();
430 ifindex_in = device_ifindex(ctx->device_in);
431 ifindex_out = device_ifindex(ctx->device_out);
433 size_in = ring_size(ctx->device_in, ctx->reserve_size);
434 size_out = ring_size(ctx->device_out, ctx->reserve_size);
436 enable_kernel_bpf_jit_compiler();
438 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
439 if (ctx->dump_bpf)
440 bpf_dump_all(&bpf_ops);
441 bpf_attach_to_sock(rx_sock, &bpf_ops);
443 ring_rx_setup(&rx_ring, rx_sock, size_in, ifindex_in, &rx_poll, false, ctx->jumbo,
444 ctx->verbose, ctx->fanout_group, ctx->fanout_type);
445 ring_tx_setup(&tx_ring, tx_sock, size_out, ifindex_out, ctx->jumbo, ctx->verbose);
447 dissector_init_all(ctx->print_mode);
449 if (ctx->promiscuous)
450 ifflags = device_enter_promiscuous_mode(ctx->device_in);
452 if (ctx->kpull)
453 interval = ctx->kpull;
455 set_itimer_interval_value(&itimer, 0, interval);
456 setitimer(ITIMER_REAL, &itimer, NULL);
458 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
460 printf("Running! Hang up with ^C!\n\n");
461 fflush(stdout);
463 while (likely(sigint == 0)) {
464 while (user_may_pull_from_rx(rx_ring.frames[it_in].iov_base)) {
465 hdr_in = rx_ring.frames[it_in].iov_base;
466 in = ((uint8_t *) hdr_in) + hdr_in->tp_h.tp_mac;
468 ctx->pkts_seen++;
470 if (ctx->packet_type != -1)
471 if (ctx->packet_type != hdr_in->s_ll.sll_pkttype)
472 goto next;
474 hdr_out = tx_ring.frames[it_out].iov_base;
475 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
477 while (!user_may_pull_from_tx(tx_ring.frames[it_out].iov_base) &&
478 likely(!sigint)) {
479 if (ctx->randomize)
480 next_rnd_slot(&it_out, &tx_ring);
481 else {
482 it_out++;
483 if (it_out >= tx_ring.layout.tp_frame_nr)
484 it_out = 0;
487 hdr_out = tx_ring.frames[it_out].iov_base;
488 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
491 tpacket_hdr_clone(&hdr_out->tp_h, &hdr_in->tp_h);
492 fmemcpy(out, in, hdr_in->tp_h.tp_len);
494 kernel_may_pull_from_tx(&hdr_out->tp_h);
495 if (ctx->randomize)
496 next_rnd_slot(&it_out, &tx_ring);
497 else {
498 it_out++;
499 if (it_out >= tx_ring.layout.tp_frame_nr)
500 it_out = 0;
503 show_frame_hdr(in, hdr_in->tp_h.tp_snaplen,
504 ctx->link_type, hdr_in, ctx->print_mode,
505 ctx->pkts_seen);
507 dissector_entry_point(in, hdr_in->tp_h.tp_snaplen,
508 ctx->link_type, ctx->print_mode,
509 &hdr_in->s_ll);
511 if (frame_count_max != 0) {
512 if (ctx->pkts_seen >= frame_count_max) {
513 sigint = 1;
514 break;
518 next:
519 kernel_may_pull_from_rx(&hdr_in->tp_h);
521 it_in++;
522 if (it_in >= rx_ring.layout.tp_frame_nr)
523 it_in = 0;
525 if (unlikely(sigint == 1))
526 goto out;
529 ret = poll(&rx_poll, 1, -1);
530 if (unlikely(ret < 0)) {
531 if (errno != EINTR)
532 panic("Poll failed!\n");
536 out:
537 timer_purge();
539 dump_rx_stats(ctx, rx_sock, false);
541 bpf_release(&bpf_ops);
543 dissector_cleanup_all();
545 destroy_tx_ring(tx_sock, &tx_ring);
546 destroy_rx_ring(rx_sock, &rx_ring);
548 if (ctx->promiscuous)
549 device_leave_promiscuous_mode(ctx->device_in, ifflags);
551 close(tx_sock);
552 close(rx_sock);
555 static void translate_pcap_to_txf(int fdo, uint8_t *out, size_t len)
557 size_t bytes_done = 0;
558 char bout[80];
560 slprintf(bout, sizeof(bout), "{\n ");
561 write_or_die(fdo, bout, strlen(bout));
563 while (bytes_done < len) {
564 slprintf(bout, sizeof(bout), "0x%02x,", out[bytes_done]);
565 write_or_die(fdo, bout, strlen(bout));
567 bytes_done++;
569 if (bytes_done % 10 == 0) {
570 slprintf(bout, sizeof(bout), "\n");
571 write_or_die(fdo, bout, strlen(bout));
573 if (bytes_done < len) {
574 slprintf(bout, sizeof(bout), " ");
575 write_or_die(fdo, bout, strlen(bout));
577 } else if (bytes_done < len) {
578 slprintf(bout, sizeof(bout), " ");
579 write_or_die(fdo, bout, strlen(bout));
582 if (bytes_done % 10 != 0) {
583 slprintf(bout, sizeof(bout), "\n");
584 write_or_die(fdo, bout, strlen(bout));
587 slprintf(bout, sizeof(bout), "}\n\n");
588 write_or_die(fdo, bout, strlen(bout));
591 static void read_pcap(struct ctx *ctx)
593 uint8_t *out;
594 int ret, fd, fdo = 0;
595 unsigned long trunced = 0;
596 size_t out_len;
597 pcap_pkthdr_t phdr;
598 struct sock_fprog bpf_ops;
599 struct frame_map fm;
600 struct timeval start, end, diff;
601 bool is_out_pcap = ctx->device_out && strstr(ctx->device_out, ".pcap");
602 const struct pcap_file_ops *pcap_out_ops = pcap_ops[PCAP_OPS_RW];
604 bug_on(!__pcap_io);
606 if (!strncmp("-", ctx->device_in, strlen("-"))) {
607 fd = dup_or_die(fileno(stdin));
608 close(fileno(stdin));
609 if (ctx->pcap == PCAP_OPS_MM)
610 ctx->pcap = PCAP_OPS_SG;
611 } else {
612 /* O_NOATIME requires privileges, in case we don't have
613 * them, retry without them at a minor cost of updating
614 * atime in case the fs has been mounted as such.
616 fd = open(ctx->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
617 if (fd < 0 && errno == EPERM)
618 fd = open_or_die(ctx->device_in, O_RDONLY | O_LARGEFILE);
619 if (fd < 0)
620 panic("Cannot open file %s! %s.\n", ctx->device_in,
621 strerror(errno));
624 if (__pcap_io->init_once_pcap)
625 __pcap_io->init_once_pcap(false);
627 ret = __pcap_io->pull_fhdr_pcap(fd, &ctx->magic, &ctx->link_type);
628 if (ret)
629 panic("Error reading pcap header!\n");
631 if (__pcap_io->prepare_access_pcap) {
632 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_RD, ctx->jumbo);
633 if (ret)
634 panic("Error prepare reading pcap!\n");
637 fmemset(&fm, 0, sizeof(fm));
639 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
640 if (ctx->dump_bpf)
641 bpf_dump_all(&bpf_ops);
643 dissector_init_all(ctx->print_mode);
645 out_len = round_up(1024 * 1024, RUNTIME_PAGE_SIZE);
646 out = xmalloc_aligned(out_len, CO_CACHE_LINE_SIZE);
648 if (ctx->device_out) {
649 if (!strncmp("-", ctx->device_out, strlen("-"))) {
650 fdo = dup_or_die(fileno(stdout));
651 close(fileno(stdout));
652 } else {
653 fdo = open_or_die_m(ctx->device_out, O_RDWR | O_CREAT |
654 O_TRUNC | O_LARGEFILE, DEFFILEMODE);
658 if (is_out_pcap) {
659 ret = pcap_out_ops->push_fhdr_pcap(fdo, ctx->magic,
660 ctx->link_type);
661 if (ret)
662 panic("Error writing pcap header!\n");
665 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
667 printf("Running! Hang up with ^C!\n\n");
668 fflush(stdout);
670 bug_on(gettimeofday(&start, NULL));
672 while (likely(sigint == 0)) {
673 do {
674 ret = __pcap_io->read_pcap(fd, &phdr, ctx->magic,
675 out, out_len);
676 if (unlikely(ret < 0))
677 goto out;
679 if (unlikely(pcap_get_length(&phdr, ctx->magic) == 0)) {
680 trunced++;
681 continue;
684 if (unlikely(pcap_get_length(&phdr, ctx->magic) > out_len)) {
685 pcap_set_length(&phdr, ctx->magic, out_len);
686 trunced++;
688 } while (ctx->filter &&
689 !bpf_run_filter(&bpf_ops, out,
690 pcap_get_length(&phdr, ctx->magic)));
692 pcap_pkthdr_to_tpacket_hdr(&phdr, ctx->magic, &fm.tp_h, &fm.s_ll);
694 ctx->tx_bytes += fm.tp_h.tp_len;
695 ctx->tx_packets++;
697 show_frame_hdr(out, fm.tp_h.tp_snaplen, ctx->link_type, &fm,
698 ctx->print_mode, ctx->tx_packets);
700 dissector_entry_point(out, fm.tp_h.tp_snaplen,
701 ctx->link_type, ctx->print_mode,
702 &fm.s_ll);
704 if (is_out_pcap) {
705 size_t pcap_len = pcap_get_length(&phdr, ctx->magic);
706 int wlen = pcap_out_ops->write_pcap(fdo, &phdr,
707 ctx->magic, out,
708 pcap_len);
709 if (unlikely(wlen != (int)pcap_get_total_length(&phdr, ctx->magic)))
710 panic("Error writing to pcap!\n");
711 } else if (ctx->device_out) {
712 translate_pcap_to_txf(fdo, out, fm.tp_h.tp_snaplen);
715 if (frame_count_max != 0) {
716 if (ctx->tx_packets >= frame_count_max) {
717 sigint = 1;
718 break;
723 out:
724 bug_on(gettimeofday(&end, NULL));
725 timersub(&end, &start, &diff);
727 bpf_release(&bpf_ops);
729 dissector_cleanup_all();
731 if (__pcap_io->prepare_close_pcap)
732 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_RD);
734 xfree(out);
736 fflush(stdout);
737 printf("\n");
738 printf("\r%12lu packets outgoing\n", ctx->tx_packets);
739 printf("\r%12lu packets truncated in file\n", trunced);
740 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
741 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
743 if (!strncmp("-", ctx->device_in, strlen("-")))
744 dup2(fd, fileno(stdin));
745 close(fd);
747 if (ctx->device_out) {
748 if (!strncmp("-", ctx->device_out, strlen("-")))
749 dup2(fdo, fileno(stdout));
750 close(fdo);
754 static void finish_multi_pcap_file(struct ctx *ctx, int fd)
756 __pcap_io->fsync_pcap(fd);
758 if (__pcap_io->prepare_close_pcap)
759 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
761 close(fd);
763 fmemset(&itimer, 0, sizeof(itimer));
764 setitimer(ITIMER_REAL, &itimer, NULL);
767 static int next_multi_pcap_file(struct ctx *ctx, int fd)
769 int ret;
770 char fname[512];
772 __pcap_io->fsync_pcap(fd);
774 if (__pcap_io->prepare_close_pcap)
775 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
777 close(fd);
779 slprintf(fname, sizeof(fname), "%s/%s%lu.pcap", ctx->device_out,
780 ctx->prefix ? : "dump-", time(NULL));
782 fd = open_or_die_m(fname, O_RDWR | O_CREAT | O_TRUNC |
783 O_LARGEFILE, DEFFILEMODE);
785 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
786 if (ret)
787 panic("Error writing pcap header!\n");
789 if (__pcap_io->prepare_access_pcap) {
790 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
791 if (ret)
792 panic("Error prepare writing pcap!\n");
795 return fd;
798 static void reset_interval(struct ctx *ctx)
800 if (ctx->dump_mode == DUMP_INTERVAL_TIME) {
801 interval = ctx->dump_interval;
803 set_itimer_interval_value(&itimer, interval, 0);
804 setitimer(ITIMER_REAL, &itimer, NULL);
805 } else {
806 interval = 0;
810 static int begin_multi_pcap_file(struct ctx *ctx)
812 int fd, ret;
813 char fname[256];
815 bug_on(!__pcap_io);
817 if (ctx->device_out[strlen(ctx->device_out) - 1] == '/')
818 ctx->device_out[strlen(ctx->device_out) - 1] = 0;
820 slprintf(fname, sizeof(fname), "%s/%s%lu.pcap", ctx->device_out,
821 ctx->prefix ? : "dump-", time(NULL));
823 fd = open_or_die_m(fname, O_RDWR | O_CREAT | O_TRUNC |
824 O_LARGEFILE, DEFFILEMODE);
826 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
827 if (ret)
828 panic("Error writing pcap header!\n");
830 if (__pcap_io->prepare_access_pcap) {
831 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
832 if (ret)
833 panic("Error prepare writing pcap!\n");
836 reset_interval(ctx);
838 return fd;
841 static void finish_single_pcap_file(struct ctx *ctx, int fd)
843 __pcap_io->fsync_pcap(fd);
845 if (__pcap_io->prepare_close_pcap)
846 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
848 if (strncmp("-", ctx->device_out, strlen("-")))
849 close(fd);
850 else
851 dup2(fd, fileno(stdout));
854 static int begin_single_pcap_file(struct ctx *ctx)
856 int fd, ret;
858 bug_on(!__pcap_io);
860 if (!strncmp("-", ctx->device_out, strlen("-"))) {
861 fd = dup_or_die(fileno(stdout));
862 close(fileno(stdout));
863 if (ctx->pcap == PCAP_OPS_MM)
864 ctx->pcap = PCAP_OPS_SG;
865 } else {
866 fd = open_or_die_m(ctx->device_out,
867 O_RDWR | O_CREAT | O_TRUNC |
868 O_LARGEFILE, DEFFILEMODE);
871 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
872 if (ret)
873 panic("Error writing pcap header!\n");
875 if (__pcap_io->prepare_access_pcap) {
876 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
877 if (ret)
878 panic("Error prepare writing pcap!\n");
881 return fd;
884 static void update_pcap_next_dump(struct ctx *ctx, unsigned long snaplen,
885 int *fd, int sock, bool is_v3)
887 if (!dump_to_pcap(ctx))
888 return;
890 if (ctx->dump_mode == DUMP_INTERVAL_SIZE) {
891 interval += snaplen;
892 if (interval > ctx->dump_interval) {
893 next_dump = true;
894 interval = 0;
898 if (sighup) {
899 if (ctx->verbose)
900 printf("SIGHUP received, prematurely rotating pcap\n");
901 sighup = 0;
902 next_dump = true;
903 reset_interval(ctx);
906 if (next_dump) {
907 *fd = next_multi_pcap_file(ctx, *fd);
908 next_dump = false;
910 if (update_rx_stats(ctx, sock, is_v3))
911 return;
913 if (ctx->verbose && ctx->print_mode == PRINT_NONE)
914 printf(".(+%lu/-%lu)",
915 ctx->pkts_recvd_last - ctx->pkts_drops_last,
916 ctx->pkts_drops_last);
920 #ifdef HAVE_TPACKET3
921 static void walk_t3_block(struct block_desc *pbd, struct ctx *ctx,
922 int sock, int *fd)
924 int num_pkts = pbd->h1.num_pkts, i;
925 struct tpacket3_hdr *hdr;
926 struct sockaddr_ll *sll;
928 hdr = (void *) ((uint8_t *) pbd + pbd->h1.offset_to_first_pkt);
929 sll = (void *) ((uint8_t *) hdr + TPACKET_ALIGN(sizeof(*hdr)));
931 for (i = 0; i < num_pkts && likely(sigint == 0); ++i) {
932 uint8_t *packet = ((uint8_t *) hdr + hdr->tp_mac);
933 pcap_pkthdr_t phdr;
935 if (ctx->packet_type != -1)
936 if (ctx->packet_type != sll->sll_pkttype)
937 goto next;
939 ctx->pkts_seen++;
941 if (dump_to_pcap(ctx)) {
942 int ret;
944 tpacket3_hdr_to_pcap_pkthdr(hdr, sll, &phdr, ctx->magic);
946 ret = __pcap_io->write_pcap(*fd, &phdr, ctx->magic, packet,
947 pcap_get_length(&phdr, ctx->magic));
948 if (unlikely(ret != (int) pcap_get_total_length(&phdr, ctx->magic)))
949 panic("Write error to pcap!\n");
952 __show_frame_hdr(packet, hdr->tp_snaplen, ctx->link_type, sll,
953 hdr, ctx->print_mode, true, ctx->pkts_seen);
955 dissector_entry_point(packet, hdr->tp_snaplen, ctx->link_type,
956 ctx->print_mode, sll);
957 next:
958 hdr = (void *) ((uint8_t *) hdr + hdr->tp_next_offset);
959 sll = (void *) ((uint8_t *) hdr + TPACKET_ALIGN(sizeof(*hdr)));
961 if (frame_count_max != 0) {
962 if (unlikely(ctx->pkts_seen >= frame_count_max)) {
963 sigint = 1;
964 break;
968 update_pcap_next_dump(ctx, hdr->tp_snaplen, fd, sock, true);
971 #endif /* HAVE_TPACKET3 */
973 static void recv_only_or_dump(struct ctx *ctx)
975 short ifflags = 0;
976 int sock, ifindex, fd = 0, ret;
977 size_t size;
978 unsigned int it = 0;
979 struct ring rx_ring;
980 struct pollfd rx_poll;
981 struct sock_fprog bpf_ops;
982 struct timeval start, end, diff;
983 bool is_v3 = is_defined(HAVE_TPACKET3);
985 sock = pf_socket_type(ctx->link_type);
987 ifindex = device_ifindex(ctx->device_in);
988 size = ring_size(ctx->device_in, ctx->reserve_size);
990 enable_kernel_bpf_jit_compiler();
992 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
993 if (ctx->dump_bpf)
994 bpf_dump_all(&bpf_ops);
995 bpf_attach_to_sock(sock, &bpf_ops);
997 if (ctx->hwtimestamp) {
998 ret = set_sockopt_hwtimestamp(sock, ctx->device_in);
999 if (ret == 0 && ctx->verbose)
1000 printf("HW timestamping enabled\n");
1003 ring_rx_setup(&rx_ring, sock, size, ifindex, &rx_poll, is_v3, true,
1004 ctx->verbose, ctx->fanout_group, ctx->fanout_type);
1006 dissector_init_all(ctx->print_mode);
1008 if (ctx->cpu >= 0 && ifindex > 0) {
1009 int irq = device_irq_number(ctx->device_in);
1010 device_set_irq_affinity(irq, ctx->cpu);
1012 if (ctx->verbose)
1013 printf("IRQ: %s:%d > CPU%d\n",
1014 ctx->device_in, irq, ctx->cpu);
1017 if (ctx->promiscuous)
1018 ifflags = device_enter_promiscuous_mode(ctx->device_in);
1020 if (dump_to_pcap(ctx) && __pcap_io->init_once_pcap)
1021 __pcap_io->init_once_pcap(true);
1023 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
1025 if (dump_to_pcap(ctx)) {
1026 struct stat stats;
1028 ret = stat(ctx->device_out, &stats);
1029 if (ret < 0)
1030 ctx->dump_dir = 0;
1031 else
1032 ctx->dump_dir = S_ISDIR(stats.st_mode);
1034 if (ctx->dump_dir)
1035 fd = begin_multi_pcap_file(ctx);
1036 else
1037 fd = begin_single_pcap_file(ctx);
1040 printf("Running! Hang up with ^C!\n\n");
1041 fflush(stdout);
1043 bug_on(gettimeofday(&start, NULL));
1045 while (likely(sigint == 0)) {
1046 #ifdef HAVE_TPACKET3
1047 struct block_desc *pbd;
1049 while (user_may_pull_from_rx_block((pbd = rx_ring.frames[it].iov_base))) {
1050 walk_t3_block(pbd, ctx, sock, &fd);
1052 kernel_may_pull_from_rx_block(pbd);
1053 it = (it + 1) % rx_ring.layout3.tp_block_nr;
1055 if (unlikely(sigint == 1))
1056 break;
1058 #else
1059 while (user_may_pull_from_rx(rx_ring.frames[it].iov_base)) {
1060 struct frame_map *hdr = rx_ring.frames[it].iov_base;
1061 uint8_t *packet = ((uint8_t *) hdr) + hdr->tp_h.tp_mac;
1062 pcap_pkthdr_t phdr;
1064 if (ctx->packet_type != -1)
1065 if (ctx->packet_type != hdr->s_ll.sll_pkttype)
1066 goto next;
1068 ctx->pkts_seen++;
1070 if (unlikely(ring_frame_size(&rx_ring) < hdr->tp_h.tp_snaplen)) {
1071 /* XXX: silently ignore for now. We used to
1072 * report them with dump_rx_stats() */
1073 goto next;
1076 if (dump_to_pcap(ctx)) {
1077 tpacket_hdr_to_pcap_pkthdr(&hdr->tp_h, &hdr->s_ll, &phdr, ctx->magic);
1079 ret = __pcap_io->write_pcap(fd, &phdr, ctx->magic, packet,
1080 pcap_get_length(&phdr, ctx->magic));
1081 if (unlikely(ret != (int) pcap_get_total_length(&phdr, ctx->magic)))
1082 panic("Write error to pcap!\n");
1085 show_frame_hdr(packet, hdr->tp_h.tp_snaplen,
1086 ctx->link_type, hdr, ctx->print_mode,
1087 ctx->pkts_seen);
1089 dissector_entry_point(packet, hdr->tp_h.tp_snaplen,
1090 ctx->link_type, ctx->print_mode,
1091 &hdr->s_ll);
1093 if (frame_count_max != 0) {
1094 if (unlikely(ctx->pkts_seen >= frame_count_max)) {
1095 sigint = 1;
1096 break;
1100 next:
1101 kernel_may_pull_from_rx(&hdr->tp_h);
1102 it = (it + 1) % rx_ring.layout.tp_frame_nr;
1104 if (unlikely(sigint == 1))
1105 break;
1107 update_pcap_next_dump(ctx, hdr->tp_h.tp_snaplen, &fd,
1108 sock, is_v3);
1110 #endif /* HAVE_TPACKET3 */
1112 ret = poll(&rx_poll, 1, -1);
1113 if (unlikely(ret < 0)) {
1114 if (errno != EINTR)
1115 panic("Poll failed!\n");
1119 bug_on(gettimeofday(&end, NULL));
1120 timersub(&end, &start, &diff);
1122 if (ctx->print_mode != PRINT_NONE) {
1123 dump_rx_stats(ctx, sock, is_v3);
1125 printf("\r%12lu sec, %lu usec in total\n",
1126 diff.tv_sec, diff.tv_usec);
1129 bpf_release(&bpf_ops);
1130 dissector_cleanup_all();
1131 destroy_rx_ring(sock, &rx_ring);
1133 if (ctx->promiscuous)
1134 device_leave_promiscuous_mode(ctx->device_in, ifflags);
1136 if (ctx->rfraw)
1137 leave_rfmon_mac80211(ctx->device_in);
1139 if (dump_to_pcap(ctx)) {
1140 if (ctx->dump_dir)
1141 finish_multi_pcap_file(ctx, fd);
1142 else
1143 finish_single_pcap_file(ctx, fd);
1146 close(sock);
1149 static void init_ctx(struct ctx *ctx)
1151 memset(ctx, 0, sizeof(*ctx));
1153 ctx->uid = getuid();
1154 ctx->gid = getgid();
1156 ctx->cpu = -1;
1157 ctx->packet_type = -1;
1159 ctx->fanout_type = PACKET_FANOUT_ROLLOVER;
1161 ctx->magic = ORIGINAL_TCPDUMP_MAGIC;
1162 ctx->print_mode = PRINT_NORM;
1163 ctx->pcap = PCAP_OPS_SG;
1165 ctx->dump_mode = DUMP_INTERVAL_TIME;
1166 ctx->dump_interval = 60;
1168 ctx->promiscuous = true;
1169 ctx->randomize = false;
1170 ctx->hwtimestamp = true;
1172 ctx->pkts_recvd = 0;
1173 ctx->pkts_seen = 0;
1174 ctx->pkts_drops = 0;
1175 ctx->pkts_recvd_last = 0;
1176 ctx->pkts_drops_last = 0;
1179 static void destroy_ctx(struct ctx *ctx)
1181 free(ctx->device_in);
1182 free(ctx->device_out);
1183 free(ctx->device_trans);
1185 free(ctx->prefix);
1188 static void __noreturn help(void)
1190 printf("netsniff-ng %s, the packet sniffing beast\n", VERSION_STRING);
1191 puts("http://www.netsniff-ng.org\n\n"
1192 "Usage: netsniff-ng [options] [filter-expression]\n"
1193 "Options:\n"
1194 " -i|-d|--dev|--in <dev|pcap|-> Input source as netdev, pcap or pcap stdin\n"
1195 " -o|--out <dev|pcap|dir|cfg|-> Output sink as netdev, pcap, directory, trafgen, or stdout\n"
1196 " -C|--fanout-group <id> Join packet fanout group\n"
1197 " -K|--fanout-type <type> Apply fanout discipline: hash|lb|cpu|rnd|roll|qm\n"
1198 " -L|--fanout-opts <opts> Additional fanout options: defrag|roll\n"
1199 " -f|--filter <bpf-file|expr> Use BPF filter file from bpfc or tcpdump-like expression\n"
1200 " -t|--type <type> Filter for: host|broadcast|multicast|others|outgoing\n"
1201 " -F|--interval <size|time> Dump interval if -o is a dir: <num>KiB/MiB/GiB/s/sec/min/hrs\n"
1202 " -R|--rfraw Capture or inject raw 802.11 frames\n"
1203 " -n|--num <0|uint> Number of packets until exit (def: 0)\n"
1204 " -P|--prefix <name> Prefix for pcaps stored in directory\n"
1205 " -T|--magic <pcap-magic> Pcap magic number/pcap format to store, see -D\n"
1206 " -w|--cooked Use Linux \"cooked\" header instead of link header\n"
1207 " -D|--dump-pcap-types Dump pcap types and magic numbers and quit\n"
1208 " -B|--dump-bpf Dump generated BPF assembly\n"
1209 " -r|--rand Randomize packet forwarding order (dev->dev)\n"
1210 " -M|--no-promisc No promiscuous mode for netdev\n"
1211 " -A|--no-sock-mem Don't tune core socket memory\n"
1212 " -N|--no-hwtimestamp Disable hardware time stamping\n"
1213 " -m|--mmap Mmap(2) pcap file I/O, e.g. for replaying pcaps\n"
1214 " -G|--sg Scatter/gather pcap file I/O\n"
1215 " -c|--clrw Use slower read(2)/write(2) I/O\n"
1216 " -S|--ring-size <size> Specify ring size to: <num>KiB/MiB/GiB\n"
1217 " -k|--kernel-pull <uint> Kernel pull from user interval in us (def: 10us)\n"
1218 " -J|--jumbo-support Support replay/fwd 64KB Super Jumbo Frames (def: 2048B)\n"
1219 " -b|--bind-cpu <cpu> Bind to specific CPU\n"
1220 " -u|--user <userid> Drop privileges and change to userid\n"
1221 " -g|--group <groupid> Drop privileges and change to groupid\n"
1222 " -H|--prio-high Make this high priority process\n"
1223 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
1224 " -s|--silent Do not print captured packets\n"
1225 " -q|--less Print less-verbose packet information\n"
1226 " -X|--hex Print packet data in hex format\n"
1227 " -l|--ascii Print human-readable packet data\n"
1228 " -U|--update Update GeoIP databases\n"
1229 " -V|--verbose Be more verbose\n"
1230 " -v|--version Show version and exit\n"
1231 " -h|--help Guess what?!\n\n"
1232 "Examples:\n"
1233 " netsniff-ng --in eth0 --out dump.pcap -s -T 0xa1b2c3d4 --b 0 tcp or udp\n"
1234 " netsniff-ng --in wlan0 --rfraw --out dump.pcap --silent --bind-cpu 0\n"
1235 " netsniff-ng --in dump.pcap --mmap --out eth0 -k1000 --silent --bind-cpu 0\n"
1236 " netsniff-ng --in dump.pcap --out dump.cfg --silent --bind-cpu 0\n"
1237 " netsniff-ng --in dump.pcap --out dump2.pcap --silent tcp\n"
1238 " netsniff-ng --in eth0 --out eth1 --silent --bind-cpu 0 -J --type host\n"
1239 " netsniff-ng --in eth1 --out /opt/probe/ -s -m --interval 100MiB -b 0\n"
1240 " netsniff-ng --in vlan0 --out dump.pcap -c -u `id -u bob` -g `id -g bob`\n"
1241 " netsniff-ng --in any --filter http.bpf --jumbo-support --ascii -V\n\n"
1242 "Note:\n"
1243 " For introducing bit errors, delays with random variation and more\n"
1244 " while replaying pcaps, make use of tc(8) with its disciplines (e.g. netem).\n");
1245 puts(copyright);
1246 die();
1249 static void __noreturn version(void)
1251 printf("netsniff-ng %s, Git id: %s\n", VERSION_LONG, GITVERSION);
1252 puts("the packet sniffing beast\n"
1253 "http://www.netsniff-ng.org\n");
1254 puts(copyright);
1255 die();
1258 int main(int argc, char **argv)
1260 char *ptr;
1261 int c, i, j, cpu_tmp, opt_index, ops_touched = 0, vals[4] = {0};
1262 bool prio_high = false, setsockmem = true;
1263 void (*main_loop)(struct ctx *ctx) = NULL;
1264 struct ctx ctx;
1266 init_ctx(&ctx);
1267 srand(time(NULL));
1269 while ((c = getopt_long(argc, argv, short_options, long_options,
1270 &opt_index)) != EOF) {
1271 switch (c) {
1272 case 'd':
1273 case 'i':
1274 ctx.device_in = xstrdup(optarg);
1275 break;
1276 case 'o':
1277 ctx.device_out = xstrdup(optarg);
1278 break;
1279 case 'P':
1280 ctx.prefix = xstrdup(optarg);
1281 break;
1282 case 'R':
1283 ctx.rfraw = 1;
1284 break;
1285 case 'r':
1286 ctx.randomize = true;
1287 break;
1288 case 'J':
1289 ctx.jumbo = true;
1290 break;
1291 case 'T':
1292 ctx.magic = (uint32_t) strtoul(optarg, NULL, 0);
1293 pcap_check_magic(ctx.magic);
1294 break;
1295 case 'f':
1296 ctx.filter = xstrdup(optarg);
1297 break;
1298 case 'M':
1299 ctx.promiscuous = false;
1300 break;
1301 case 'N':
1302 ctx.hwtimestamp = false;
1303 break;
1304 case 'A':
1305 setsockmem = false;
1306 break;
1307 case 'u':
1308 ctx.uid = strtoul(optarg, NULL, 0);
1309 ctx.enforce = true;
1310 break;
1311 case 'g':
1312 ctx.gid = strtoul(optarg, NULL, 0);
1313 ctx.enforce = true;
1314 break;
1315 case 'C':
1316 ctx.fanout_group = strtoul(optarg, NULL, 0);
1317 if (ctx.fanout_group == 0)
1318 panic("Non-zero fanout group id required!\n");
1319 break;
1320 case 'K':
1321 if (!strncmp(optarg, "hash", strlen("hash")))
1322 ctx.fanout_type = PACKET_FANOUT_HASH;
1323 else if (!strncmp(optarg, "lb", strlen("lb")) ||
1324 !strncmp(optarg, "rr", strlen("rr")))
1325 ctx.fanout_type = PACKET_FANOUT_LB;
1326 else if (!strncmp(optarg, "cpu", strlen("cpu")))
1327 ctx.fanout_type = PACKET_FANOUT_CPU;
1328 else if (!strncmp(optarg, "rnd", strlen("rnd")))
1329 ctx.fanout_type = PACKET_FANOUT_RND;
1330 else if (!strncmp(optarg, "roll", strlen("roll")))
1331 ctx.fanout_type = PACKET_FANOUT_ROLLOVER;
1332 else if (!strncmp(optarg, "qm", strlen("qm")))
1333 ctx.fanout_type = PACKET_FANOUT_QM;
1334 else
1335 panic("Unknown fanout type!\n");
1336 break;
1337 case 'L':
1338 if (!strncmp(optarg, "defrag", strlen("defrag")))
1339 ctx.fanout_type |= PACKET_FANOUT_FLAG_DEFRAG;
1340 else if (!strncmp(optarg, "roll", strlen("roll")))
1341 ctx.fanout_type |= PACKET_FANOUT_FLAG_ROLLOVER;
1342 else
1343 panic("Unknown fanout option!\n");
1344 break;
1345 case 't':
1346 if (!strncmp(optarg, "host", strlen("host")))
1347 ctx.packet_type = PACKET_HOST;
1348 else if (!strncmp(optarg, "broadcast", strlen("broadcast")))
1349 ctx.packet_type = PACKET_BROADCAST;
1350 else if (!strncmp(optarg, "multicast", strlen("multicast")))
1351 ctx.packet_type = PACKET_MULTICAST;
1352 else if (!strncmp(optarg, "others", strlen("others")))
1353 ctx.packet_type = PACKET_OTHERHOST;
1354 else if (!strncmp(optarg, "outgoing", strlen("outgoing")))
1355 ctx.packet_type = PACKET_OUTGOING;
1356 else
1357 ctx.packet_type = -1;
1358 break;
1359 case 'S':
1360 ptr = optarg;
1361 for (j = i = strlen(optarg); i > 0; --i) {
1362 if (!isdigit(optarg[j - i]))
1363 break;
1364 ptr++;
1367 if (!strncmp(ptr, "KiB", strlen("KiB")))
1368 ctx.reserve_size = 1 << 10;
1369 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1370 ctx.reserve_size = 1 << 20;
1371 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1372 ctx.reserve_size = 1 << 30;
1373 else
1374 panic("Syntax error in ring size param!\n");
1376 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1377 break;
1378 case 'b':
1379 cpu_tmp = strtol(optarg, NULL, 0);
1381 cpu_affinity(cpu_tmp);
1382 if (ctx.cpu != -2)
1383 ctx.cpu = cpu_tmp;
1384 break;
1385 case 'H':
1386 prio_high = true;
1387 break;
1388 case 'c':
1389 ctx.pcap = PCAP_OPS_RW;
1390 ops_touched = 1;
1391 break;
1392 case 'm':
1393 ctx.pcap = PCAP_OPS_MM;
1394 ops_touched = 1;
1395 break;
1396 case 'G':
1397 ctx.pcap = PCAP_OPS_SG;
1398 ops_touched = 1;
1399 break;
1400 case 'Q':
1401 ctx.cpu = -2;
1402 break;
1403 case 's':
1404 ctx.print_mode = PRINT_NONE;
1405 break;
1406 case 'q':
1407 ctx.print_mode = PRINT_LESS;
1408 break;
1409 case 'X':
1410 ctx.print_mode =
1411 (ctx.print_mode == PRINT_ASCII) ?
1412 PRINT_HEX_ASCII : PRINT_HEX;
1413 break;
1414 case 'l':
1415 ctx.print_mode =
1416 (ctx.print_mode == PRINT_HEX) ?
1417 PRINT_HEX_ASCII : PRINT_ASCII;
1418 break;
1419 case 'k':
1420 ctx.kpull = strtoul(optarg, NULL, 0);
1421 break;
1422 case 'n':
1423 frame_count_max = strtoul(optarg, NULL, 0);
1424 break;
1425 case 'F':
1426 ptr = optarg;
1427 for (j = i = strlen(optarg); i > 0; --i) {
1428 if (!isdigit(optarg[j - i]))
1429 break;
1430 ptr++;
1433 if (!strncmp(ptr, "KiB", strlen("KiB"))) {
1434 ctx.dump_interval = 1 << 10;
1435 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1436 } else if (!strncmp(ptr, "MiB", strlen("MiB"))) {
1437 ctx.dump_interval = 1 << 20;
1438 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1439 } else if (!strncmp(ptr, "GiB", strlen("GiB"))) {
1440 ctx.dump_interval = 1 << 30;
1441 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1442 } else if (!strncmp(ptr, "sec", strlen("sec"))) {
1443 ctx.dump_interval = 1;
1444 ctx.dump_mode = DUMP_INTERVAL_TIME;
1445 } else if (!strncmp(ptr, "min", strlen("min"))) {
1446 ctx.dump_interval = 60;
1447 ctx.dump_mode = DUMP_INTERVAL_TIME;
1448 } else if (!strncmp(ptr, "hrs", strlen("hrs"))) {
1449 ctx.dump_interval = 60 * 60;
1450 ctx.dump_mode = DUMP_INTERVAL_TIME;
1451 } else if (!strncmp(ptr, "s", strlen("s"))) {
1452 ctx.dump_interval = 1;
1453 ctx.dump_mode = DUMP_INTERVAL_TIME;
1454 } else {
1455 panic("Syntax error in time/size param!\n");
1458 ctx.dump_interval *= strtoul(optarg, NULL, 0);
1459 break;
1460 case 'V':
1461 ctx.verbose = true;
1462 break;
1463 case 'B':
1464 ctx.dump_bpf = true;
1465 break;
1466 case 'D':
1467 pcap_dump_type_features();
1468 die();
1469 break;
1470 case 'U':
1471 update_geoip();
1472 die();
1473 break;
1474 case 'w':
1475 ctx.link_type = LINKTYPE_LINUX_SLL;
1476 break;
1477 case 'v':
1478 version();
1479 break;
1480 case 'h':
1481 help();
1482 break;
1483 case '?':
1484 switch (optopt) {
1485 case 'd':
1486 case 'i':
1487 case 'o':
1488 case 'f':
1489 case 't':
1490 case 'P':
1491 case 'F':
1492 case 'n':
1493 case 'S':
1494 case 'b':
1495 case 'k':
1496 case 'T':
1497 case 'u':
1498 case 'g':
1499 case 'e':
1500 panic("Option -%c requires an argument!\n",
1501 optopt);
1502 default:
1503 if (isprint(optopt))
1504 printf("Unknown option character `0x%X\'!\n", optopt);
1505 die();
1507 default:
1508 break;
1512 if (!ctx.filter && optind != argc) {
1513 int ret;
1514 off_t offset = 0;
1516 for (i = optind; i < argc; ++i) {
1517 size_t alen = strlen(argv[i]) + 2;
1518 size_t flen = ctx.filter ? strlen(ctx.filter) : 0;
1520 ctx.filter = xrealloc(ctx.filter, flen + alen);
1521 ret = slprintf(ctx.filter + offset, strlen(argv[i]) + 2, "%s ", argv[i]);
1522 if (ret < 0)
1523 panic("Cannot concatenate filter string!\n");
1524 else
1525 offset += ret;
1529 if (!ctx.device_in)
1530 ctx.device_in = xstrdup("any");
1532 register_signal(SIGINT, signal_handler);
1533 register_signal(SIGQUIT, signal_handler);
1534 register_signal(SIGTERM, signal_handler);
1535 register_signal(SIGHUP, signal_handler);
1537 tprintf_init();
1539 if (prio_high) {
1540 set_proc_prio(-20);
1541 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1544 if (device_mtu(ctx.device_in) || !strncmp("any", ctx.device_in, strlen(ctx.device_in))) {
1545 if (ctx.rfraw)
1546 setup_rfmon_mac80211_dev(&ctx, &ctx.device_in);
1548 if (!ctx.link_type)
1549 ctx.link_type = pcap_dev_to_linktype(ctx.device_in);
1550 if (link_has_sll_hdr(ctx.link_type)) {
1551 switch (ctx.magic) {
1552 case ORIGINAL_TCPDUMP_MAGIC:
1553 ctx.magic = ORIGINAL_TCPDUMP_MAGIC_LL;
1554 break;
1555 case NSEC_TCPDUMP_MAGIC:
1556 ctx.magic = NSEC_TCPDUMP_MAGIC_LL;
1557 break;
1558 case ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC):
1559 ctx.magic = ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC_LL);
1560 break;
1561 case ___constant_swab32(NSEC_TCPDUMP_MAGIC):
1562 ctx.magic = ___constant_swab32(NSEC_TCPDUMP_MAGIC_LL);
1563 break;
1568 if (!ctx.device_out) {
1569 ctx.dump = 0;
1570 main_loop = recv_only_or_dump;
1571 } else if (device_mtu(ctx.device_out)) {
1572 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1573 main_loop = receive_to_xmit;
1574 } else {
1575 ctx.dump = 1;
1576 register_signal_f(SIGALRM, timer_next_dump, SA_SIGINFO);
1577 main_loop = recv_only_or_dump;
1578 if (!ops_touched)
1579 ctx.pcap = PCAP_OPS_SG;
1581 } else {
1582 if (ctx.device_out && device_mtu(ctx.device_out)) {
1583 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1584 main_loop = pcap_to_xmit;
1585 if (!ops_touched)
1586 ctx.pcap = PCAP_OPS_MM;
1587 } else {
1588 setsockmem = false;
1589 main_loop = read_pcap;
1590 if (!ops_touched)
1591 ctx.pcap = PCAP_OPS_SG;
1595 bug_on(!main_loop);
1597 init_geoip(0);
1598 if (setsockmem)
1599 set_system_socket_memory(vals, array_size(vals));
1600 if (!ctx.enforce)
1601 xlockme();
1603 if (ctx.verbose)
1604 printf("pcap file I/O method: %s\n", pcap_ops_group_to_str[ctx.pcap]);
1606 main_loop(&ctx);
1608 if (!ctx.enforce)
1609 xunlockme();
1610 if (setsockmem)
1611 reset_system_socket_memory(vals, array_size(vals));
1612 destroy_geoip();
1614 device_restore_irq_affinity_list();
1615 tprintf_cleanup();
1617 destroy_ctx(&ctx);
1618 return 0;