netsniff-ng v0.6.5
[netsniff-ng.git] / netsniff-ng.c
blob48e122108d9e63ae018e54bc84a410409f30c3c0
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;
73 static volatile sig_atomic_t sigint = 0, sighup = 0;
74 static volatile bool next_dump = false;
75 static volatile sig_atomic_t sighup_time = 0;
77 static const char *short_options =
78 "d:i:o:rf:MNJt:S:k:n:b:HQmcsqXlvhF:RGAP:Vu:g:T:DBUC:K:L:w";
79 static const struct option long_options[] = {
80 {"dev", required_argument, NULL, 'd'},
81 {"in", required_argument, NULL, 'i'},
82 {"out", required_argument, NULL, 'o'},
83 {"filter", required_argument, NULL, 'f'},
84 {"num", required_argument, NULL, 'n'},
85 {"type", required_argument, NULL, 't'},
86 {"interval", required_argument, NULL, 'F'},
87 {"ring-size", required_argument, NULL, 'S'},
88 {"kernel-pull", required_argument, NULL, 'k'},
89 {"bind-cpu", required_argument, NULL, 'b'},
90 {"prefix", required_argument, NULL, 'P'},
91 {"user", required_argument, NULL, 'u'},
92 {"group", required_argument, NULL, 'g'},
93 {"magic", required_argument, NULL, 'T'},
94 {"fanout-group", required_argument, NULL, 'C'},
95 {"fanout-type", required_argument, NULL, 'K'},
96 {"fanout-opts", required_argument, NULL, 'L'},
97 {"rand", no_argument, NULL, 'r'},
98 {"rfraw", no_argument, NULL, 'R'},
99 {"mmap", no_argument, NULL, 'm'},
100 {"sg", no_argument, NULL, 'G'},
101 {"clrw", no_argument, NULL, 'c'},
102 {"jumbo-support", no_argument, NULL, 'J'},
103 {"no-promisc", no_argument, NULL, 'M'},
104 {"no-hwtimestamp", no_argument, NULL, 'N'},
105 {"prio-high", no_argument, NULL, 'H'},
106 {"notouch-irq", no_argument, NULL, 'Q'},
107 {"dump-pcap-types", no_argument, NULL, 'D'},
108 {"dump-bpf", no_argument, NULL, 'B'},
109 {"silent", no_argument, NULL, 's'},
110 {"less", no_argument, NULL, 'q'},
111 {"hex", no_argument, NULL, 'X'},
112 {"ascii", no_argument, NULL, 'l'},
113 {"no-sock-mem", no_argument, NULL, 'A'},
114 {"update", no_argument, NULL, 'U'},
115 {"cooked", no_argument, NULL, 'w'},
116 {"verbose", no_argument, NULL, 'V'},
117 {"version", no_argument, NULL, 'v'},
118 {"help", no_argument, NULL, 'h'},
119 {NULL, 0, NULL, 0}
122 static const char *copyright = "Please report bugs to <netsniff-ng@googlegroups.com>\n"
123 "Copyright (C) 2009-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
124 "Copyright (C) 2009-2012 Emmanuel Roullit <emmanuel.roullit@gmail.com>\n"
125 "Copyright (C) 2012 Markus Amend <markus@netsniff-ng.org>\n"
126 "Swiss federal institute of technology (ETH Zurich)\n"
127 "License: GNU GPL version 2.0\n"
128 "This is free software: you are free to change and redistribute it.\n"
129 "There is NO WARRANTY, to the extent permitted by law.";
131 static int tx_sock;
132 static struct itimerval itimer;
133 static unsigned long frame_count_max = 0, interval = TX_KERNEL_PULL_INT;
134 static time_t start_time;
136 #define __pcap_io pcap_ops[ctx->pcap]
138 static void signal_handler(int number)
140 switch (number) {
141 case SIGINT:
142 case SIGQUIT:
143 case SIGTERM:
144 sigint = 1;
145 break;
146 case SIGHUP:
147 sighup = 1;
148 sighup_time = (sig_atomic_t)(time(NULL) - start_time);
149 break;
150 default:
151 break;
155 static void timer_elapsed(int unused __maybe_unused)
157 int ret;
159 set_itimer_interval_value(&itimer, 0, interval);
161 ret = pull_and_flush_tx_ring(tx_sock);
162 if (unlikely(ret < 0)) {
163 /* We could hit EBADF if the socket has been closed before
164 * the timer was triggered.
166 if (errno != EBADF && errno != ENOBUFS)
167 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
170 setitimer(ITIMER_REAL, &itimer, NULL);
173 static void timer_purge(void)
175 int ret;
177 ret = pull_and_flush_tx_ring_wait(tx_sock);
178 if (unlikely(ret < 0)) {
179 if (errno != EBADF && errno != ENOBUFS)
180 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
183 set_itimer_interval_value(&itimer, 0, 0);
184 setitimer(ITIMER_REAL, &itimer, NULL);
187 static void timer_next_dump(int unused __maybe_unused)
189 set_itimer_interval_value(&itimer, interval, 0);
190 next_dump = true;
191 setitimer(ITIMER_REAL, &itimer, NULL);
194 static inline bool dump_to_pcap(struct ctx *ctx)
196 return ctx->dump;
199 static void on_panic_del_rfmon(void *arg)
201 leave_rfmon_mac80211(arg);
204 static inline void setup_rfmon_mac80211_dev(struct ctx *ctx, char **rfmon_dev)
206 ctx->device_trans = xstrdup(*rfmon_dev);
207 xfree(*rfmon_dev);
209 enter_rfmon_mac80211(ctx->device_trans, rfmon_dev);
210 panic_handler_add(on_panic_del_rfmon, *rfmon_dev);
213 static int update_rx_stats(struct ctx *ctx, int sock, bool is_v3)
215 uint64_t packets, drops;
216 int ret;
218 ret = get_rx_net_stats(sock, &packets, &drops, is_v3);
219 if (ret)
220 return ret;
222 drops += ctx->pkts_skipd_last;
223 ctx->pkts_seen += ctx->pkts_skipd_last;
224 ctx->pkts_recvd += packets;
225 ctx->pkts_drops += drops;
226 ctx->pkts_recvd_last = packets;
227 ctx->pkts_drops_last = drops;
228 ctx->pkts_skipd_last = 0;
230 return 0;
233 static void dump_rx_stats(struct ctx *ctx, int sock, bool is_v3)
235 if (update_rx_stats(ctx, sock, is_v3))
236 return;
238 printf("\r%12"PRIu64" packets incoming (%"PRIu64" unread on exit)\n",
239 is_v3 ? ctx->pkts_seen : ctx->pkts_recvd,
240 is_v3 ? ctx->pkts_recvd - ctx->pkts_seen : 0);
241 printf("\r%12"PRIu64" packets passed filter\n",
242 ctx->pkts_recvd - ctx->pkts_drops);
243 printf("\r%12"PRIu64" packets failed filter (out of space)\n",
244 ctx->pkts_drops);
246 if (ctx->pkts_recvd > 0)
247 printf("\r%12.4lf%% packet droprate\n",
248 (1.0 * ctx->pkts_drops / ctx->pkts_recvd) * 100.0);
251 static void pcap_to_xmit(struct ctx *ctx)
253 uint8_t *out = NULL;
254 int ifindex, fd = 0, ret;
255 size_t size;
256 unsigned int it = 0;
257 unsigned long trunced = 0;
258 struct ring tx_ring;
259 struct frame_map *hdr;
260 struct sock_fprog bpf_ops;
261 struct timeval start, end, diff;
262 pcap_pkthdr_t phdr;
264 if (!device_up_and_running(ctx->device_out) && !ctx->rfraw)
265 panic("Device not up and running!\n");
267 bug_on(!__pcap_io);
269 tx_sock = pf_socket();
271 if (!strncmp("-", ctx->device_in, strlen("-"))) {
272 fd = dup_or_die(fileno(stdin));
273 close(fileno(stdin));
274 if (ctx->pcap == PCAP_OPS_MM)
275 ctx->pcap = PCAP_OPS_SG;
276 } else {
277 fd = open_or_die(ctx->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
280 if (__pcap_io->init_once_pcap)
281 __pcap_io->init_once_pcap(true);
283 ret = __pcap_io->pull_fhdr_pcap(fd, &ctx->magic, &ctx->link_type);
284 if (ret)
285 panic("Error reading pcap header!\n");
287 if (__pcap_io->prepare_access_pcap) {
288 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_RD, ctx->jumbo);
289 if (ret)
290 panic("Error prepare reading pcap!\n");
293 if (ctx->rfraw) {
294 setup_rfmon_mac80211_dev(ctx, &ctx->device_out);
296 if (ctx->link_type != LINKTYPE_IEEE802_11 &&
297 ctx->link_type != LINKTYPE_IEEE802_11_RADIOTAP)
298 panic("Wrong linktype of pcap!\n");
301 ifindex = device_ifindex(ctx->device_out);
302 size = ring_size(ctx->device_out, ctx->reserve_size);
304 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
305 if (ctx->dump_bpf)
306 bpf_dump_all(&bpf_ops);
308 ring_tx_setup(&tx_ring, tx_sock, size, ifindex, ctx->jumbo, ctx->verbose);
310 dissector_init_all(ctx->print_mode);
312 if (ctx->cpu >= 0 && ifindex > 0) {
313 int irq = device_irq_number(ctx->device_out);
314 device_set_irq_affinity(irq, ctx->cpu);
316 if (ctx->verbose)
317 printf("IRQ: %s:%d > CPU%d\n",
318 ctx->device_out, irq, ctx->cpu);
321 if (ctx->kpull)
322 interval = ctx->kpull;
324 set_itimer_interval_value(&itimer, 0, interval);
325 setitimer(ITIMER_REAL, &itimer, NULL);
327 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
329 printf("Running! Hang up with ^C!\n\n");
330 fflush(stdout);
332 bug_on(gettimeofday(&start, NULL));
334 while (likely(sigint == 0)) {
335 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
336 hdr = tx_ring.frames[it].iov_base;
337 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
339 do {
340 ret = __pcap_io->read_pcap(fd, &phdr, ctx->magic, out,
341 ring_frame_size(&tx_ring));
342 if (unlikely(ret <= 0))
343 goto out;
345 if (ring_frame_size(&tx_ring) <
346 pcap_get_length(&phdr, ctx->magic)) {
347 pcap_set_length(&phdr, ctx->magic,
348 ring_frame_size(&tx_ring));
349 trunced++;
351 } while (ctx->filter &&
352 !bpf_run_filter(&bpf_ops, out,
353 pcap_get_length(&phdr, ctx->magic)));
355 pcap_pkthdr_to_tpacket_hdr(&phdr, ctx->magic, &hdr->tp_h, NULL);
357 ctx->tx_bytes += hdr->tp_h.tp_len;;
358 ctx->tx_packets++;
360 show_frame_hdr(out, hdr->tp_h.tp_snaplen,
361 ctx->link_type, hdr, ctx->print_mode,
362 ctx->tx_packets);
364 dissector_entry_point(out, hdr->tp_h.tp_snaplen,
365 ctx->link_type, ctx->print_mode,
366 &hdr->s_ll);
368 kernel_may_pull_from_tx(&hdr->tp_h);
370 it++;
371 if (it >= tx_ring.layout.tp_frame_nr)
372 it = 0;
374 if (unlikely(sigint == 1))
375 break;
377 if (frame_count_max != 0) {
378 if (ctx->tx_packets >= frame_count_max) {
379 sigint = 1;
380 break;
386 out:
387 bug_on(gettimeofday(&end, NULL));
388 timersub(&end, &start, &diff);
390 timer_purge();
392 bpf_release(&bpf_ops);
394 dissector_cleanup_all();
395 destroy_tx_ring(tx_sock, &tx_ring);
397 if (ctx->rfraw)
398 leave_rfmon_mac80211(ctx->device_out);
400 if (__pcap_io->prepare_close_pcap)
401 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_RD);
403 if (!strncmp("-", ctx->device_in, strlen("-")))
404 dup2(fd, fileno(stdin));
405 close(fd);
407 close(tx_sock);
409 fflush(stdout);
410 printf("\n");
411 printf("\r%12lu packets outgoing\n", ctx->tx_packets);
412 printf("\r%12lu packets truncated in file\n", trunced);
413 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
414 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
417 static inline bool __skip_packet(struct ctx *ctx, struct sockaddr_ll *sll)
419 if (ctx->packet_type != -1)
420 return ctx->packet_type != sll->sll_pkttype;
422 /* when receving from the loopback device, each packet is seen twice,
423 * so drop the outgoing ones to avoid duplicates
425 return (sll->sll_ifindex == ctx->lo_ifindex) &&
426 (sll->sll_pkttype == PACKET_OUTGOING);
429 static inline bool skip_packet(struct ctx *ctx, struct sockaddr_ll *sll)
431 bool skip = __skip_packet(ctx, sll);
433 if (skip)
434 ctx->pkts_skipd_last++;
435 return skip;
438 static void receive_to_xmit(struct ctx *ctx)
440 short ifflags = 0;
441 uint8_t *in, *out;
442 int rx_sock, ifindex_in, ifindex_out, ret;
443 size_t size_in, size_out;
444 unsigned int it_in = 0, it_out = 0;
445 struct frame_map *hdr_in, *hdr_out;
446 struct ring tx_ring, rx_ring;
447 struct pollfd rx_poll;
448 struct sock_fprog bpf_ops;
450 if (!strncmp(ctx->device_in, ctx->device_out, IFNAMSIZ))
451 panic("Ingress/egress devices must be different!\n");
452 if (!device_up_and_running(ctx->device_out))
453 panic("Egress device not up and running!\n");
455 rx_sock = pf_socket();
456 tx_sock = pf_socket();
458 ifindex_in = device_ifindex(ctx->device_in);
459 ifindex_out = device_ifindex(ctx->device_out);
461 size_in = ring_size(ctx->device_in, ctx->reserve_size);
462 size_out = ring_size(ctx->device_out, ctx->reserve_size);
464 enable_kernel_bpf_jit_compiler();
466 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
467 if (ctx->dump_bpf)
468 bpf_dump_all(&bpf_ops);
469 bpf_attach_to_sock(rx_sock, &bpf_ops);
471 ring_rx_setup(&rx_ring, rx_sock, size_in, ifindex_in, &rx_poll, false, ctx->jumbo,
472 ctx->verbose, ctx->fanout_group, ctx->fanout_type);
473 ring_tx_setup(&tx_ring, tx_sock, size_out, ifindex_out, ctx->jumbo, ctx->verbose);
475 dissector_init_all(ctx->print_mode);
477 if (ctx->promiscuous)
478 ifflags = device_enter_promiscuous_mode(ctx->device_in);
480 if (ctx->kpull)
481 interval = ctx->kpull;
483 set_itimer_interval_value(&itimer, 0, interval);
484 setitimer(ITIMER_REAL, &itimer, NULL);
486 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
488 printf("Running! Hang up with ^C!\n\n");
489 fflush(stdout);
491 while (likely(sigint == 0)) {
492 while (user_may_pull_from_rx(rx_ring.frames[it_in].iov_base)) {
493 hdr_in = rx_ring.frames[it_in].iov_base;
494 in = ((uint8_t *) hdr_in) + hdr_in->tp_h.tp_mac;
496 if (skip_packet(ctx, &hdr_in->s_ll))
497 goto next;
499 ctx->pkts_seen++;
501 hdr_out = tx_ring.frames[it_out].iov_base;
502 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
504 while (!user_may_pull_from_tx(tx_ring.frames[it_out].iov_base) &&
505 likely(!sigint)) {
506 if (ctx->randomize)
507 next_rnd_slot(&it_out, &tx_ring);
508 else {
509 it_out++;
510 if (it_out >= tx_ring.layout.tp_frame_nr)
511 it_out = 0;
514 hdr_out = tx_ring.frames[it_out].iov_base;
515 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
518 tpacket_hdr_clone(&hdr_out->tp_h, &hdr_in->tp_h);
519 memcpy(out, in, hdr_in->tp_h.tp_len);
521 kernel_may_pull_from_tx(&hdr_out->tp_h);
522 if (ctx->randomize)
523 next_rnd_slot(&it_out, &tx_ring);
524 else {
525 it_out++;
526 if (it_out >= tx_ring.layout.tp_frame_nr)
527 it_out = 0;
530 show_frame_hdr(in, hdr_in->tp_h.tp_snaplen,
531 ctx->link_type, hdr_in, ctx->print_mode,
532 ctx->pkts_seen);
534 dissector_entry_point(in, hdr_in->tp_h.tp_snaplen,
535 ctx->link_type, ctx->print_mode,
536 &hdr_in->s_ll);
538 if (frame_count_max != 0) {
539 if (ctx->pkts_seen >= frame_count_max) {
540 sigint = 1;
541 break;
545 next:
546 kernel_may_pull_from_rx(&hdr_in->tp_h);
548 it_in++;
549 if (it_in >= rx_ring.layout.tp_frame_nr)
550 it_in = 0;
552 if (unlikely(sigint == 1))
553 goto out;
556 ret = poll(&rx_poll, 1, -1);
557 if (unlikely(ret < 0)) {
558 if (errno != EINTR)
559 panic("Poll failed!\n");
563 out:
564 timer_purge();
566 dump_rx_stats(ctx, rx_sock, false);
568 bpf_release(&bpf_ops);
570 dissector_cleanup_all();
572 destroy_tx_ring(tx_sock, &tx_ring);
573 destroy_rx_ring(rx_sock, &rx_ring);
575 if (ctx->promiscuous)
576 device_leave_promiscuous_mode(ctx->device_in, ifflags);
578 close(tx_sock);
579 close(rx_sock);
582 static void translate_pcap_to_txf(int fdo, uint8_t *out, size_t len)
584 size_t bytes_done = 0;
585 char bout[80];
587 slprintf(bout, sizeof(bout), "{\n ");
588 write_or_die(fdo, bout, strlen(bout));
590 while (bytes_done < len) {
591 slprintf(bout, sizeof(bout), "0x%02x,", out[bytes_done]);
592 write_or_die(fdo, bout, strlen(bout));
594 bytes_done++;
596 if (bytes_done % 10 == 0) {
597 slprintf(bout, sizeof(bout), "\n");
598 write_or_die(fdo, bout, strlen(bout));
600 if (bytes_done < len) {
601 slprintf(bout, sizeof(bout), " ");
602 write_or_die(fdo, bout, strlen(bout));
604 } else if (bytes_done < len) {
605 slprintf(bout, sizeof(bout), " ");
606 write_or_die(fdo, bout, strlen(bout));
609 if (bytes_done % 10 != 0) {
610 slprintf(bout, sizeof(bout), "\n");
611 write_or_die(fdo, bout, strlen(bout));
614 slprintf(bout, sizeof(bout), "}\n\n");
615 write_or_die(fdo, bout, strlen(bout));
618 static void read_pcap(struct ctx *ctx)
620 uint8_t *out;
621 int ret, fd, fdo = 0;
622 unsigned long trunced = 0;
623 size_t out_len;
624 pcap_pkthdr_t phdr;
625 struct sock_fprog bpf_ops;
626 struct frame_map fm;
627 struct timeval start, end, diff;
628 bool is_out_pcap = ctx->device_out && strstr(ctx->device_out, ".pcap");
629 const struct pcap_file_ops *pcap_out_ops = pcap_ops[PCAP_OPS_RW];
631 bug_on(!__pcap_io);
633 if (!strncmp("-", ctx->device_in, strlen("-"))) {
634 fd = dup_or_die(fileno(stdin));
635 close(fileno(stdin));
636 if (ctx->pcap == PCAP_OPS_MM)
637 ctx->pcap = PCAP_OPS_SG;
638 } else {
639 /* O_NOATIME requires privileges, in case we don't have
640 * them, retry without them at a minor cost of updating
641 * atime in case the fs has been mounted as such.
643 fd = open(ctx->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
644 if (fd < 0 && errno == EPERM)
645 fd = open_or_die(ctx->device_in, O_RDONLY | O_LARGEFILE);
646 if (fd < 0)
647 panic("Cannot open file %s! %s.\n", ctx->device_in,
648 strerror(errno));
651 if (__pcap_io->init_once_pcap)
652 __pcap_io->init_once_pcap(false);
654 ret = __pcap_io->pull_fhdr_pcap(fd, &ctx->magic, &ctx->link_type);
655 if (ret)
656 panic("Error reading pcap header!\n");
658 if (__pcap_io->prepare_access_pcap) {
659 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_RD, ctx->jumbo);
660 if (ret)
661 panic("Error prepare reading pcap!\n");
664 memset(&fm, 0, sizeof(fm));
666 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
667 if (ctx->dump_bpf)
668 bpf_dump_all(&bpf_ops);
670 dissector_init_all(ctx->print_mode);
672 out_len = round_up(1024 * 1024, RUNTIME_PAGE_SIZE);
673 out = xmalloc_aligned(out_len, CO_CACHE_LINE_SIZE);
675 if (ctx->device_out) {
676 if (!strncmp("-", ctx->device_out, strlen("-"))) {
677 fdo = dup_or_die(fileno(stdout));
678 close(fileno(stdout));
679 } else {
680 fdo = open_or_die_m(ctx->device_out, O_RDWR | O_CREAT |
681 O_TRUNC | O_LARGEFILE, DEFFILEMODE);
685 if (is_out_pcap) {
686 ret = pcap_out_ops->push_fhdr_pcap(fdo, ctx->magic,
687 ctx->link_type);
688 if (ret)
689 panic("Error writing pcap header!\n");
692 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
694 printf("Running! Hang up with ^C!\n\n");
695 fflush(stdout);
697 bug_on(gettimeofday(&start, NULL));
699 while (likely(sigint == 0)) {
700 do {
701 ret = __pcap_io->read_pcap(fd, &phdr, ctx->magic,
702 out, out_len);
703 if (unlikely(ret < 0))
704 goto out;
706 if (unlikely(pcap_get_length(&phdr, ctx->magic) == 0)) {
707 trunced++;
708 continue;
711 if (unlikely(pcap_get_length(&phdr, ctx->magic) > out_len)) {
712 pcap_set_length(&phdr, ctx->magic, out_len);
713 trunced++;
715 } while (ctx->filter &&
716 !bpf_run_filter(&bpf_ops, out,
717 pcap_get_length(&phdr, ctx->magic)));
719 pcap_pkthdr_to_tpacket_hdr(&phdr, ctx->magic, &fm.tp_h, &fm.s_ll);
721 ctx->tx_bytes += fm.tp_h.tp_len;
722 ctx->tx_packets++;
724 show_frame_hdr(out, fm.tp_h.tp_snaplen, ctx->link_type, &fm,
725 ctx->print_mode, ctx->tx_packets);
727 dissector_entry_point(out, fm.tp_h.tp_snaplen,
728 ctx->link_type, ctx->print_mode,
729 &fm.s_ll);
731 if (is_out_pcap) {
732 size_t pcap_len = pcap_get_length(&phdr, ctx->magic);
733 int wlen = pcap_out_ops->write_pcap(fdo, &phdr,
734 ctx->magic, out,
735 pcap_len);
736 if (unlikely(wlen != (int)pcap_get_total_length(&phdr, ctx->magic)))
737 panic("Error writing to pcap!\n");
738 } else if (ctx->device_out) {
739 translate_pcap_to_txf(fdo, out, fm.tp_h.tp_snaplen);
742 if (frame_count_max != 0) {
743 if (ctx->tx_packets >= frame_count_max) {
744 sigint = 1;
745 break;
750 out:
751 bug_on(gettimeofday(&end, NULL));
752 timersub(&end, &start, &diff);
754 bpf_release(&bpf_ops);
756 dissector_cleanup_all();
758 if (__pcap_io->prepare_close_pcap)
759 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_RD);
761 xfree(out);
763 fflush(stdout);
764 printf("\n");
765 printf("\r%12lu packets outgoing\n", ctx->tx_packets);
766 printf("\r%12lu packets truncated in file\n", trunced);
767 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
768 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
770 if (!strncmp("-", ctx->device_in, strlen("-")))
771 dup2(fd, fileno(stdin));
772 close(fd);
774 if (ctx->device_out) {
775 if (!strncmp("-", ctx->device_out, strlen("-")))
776 dup2(fdo, fileno(stdout));
777 close(fdo);
781 static void finish_multi_pcap_file(struct ctx *ctx, int fd)
783 __pcap_io->fsync_pcap(fd);
785 if (__pcap_io->prepare_close_pcap)
786 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
788 close(fd);
790 memset(&itimer, 0, sizeof(itimer));
791 setitimer(ITIMER_REAL, &itimer, NULL);
794 static int next_multi_pcap_file(struct ctx *ctx, int fd)
796 int ret;
797 char fname[PATH_MAX];
798 time_t ftime;
800 __pcap_io->fsync_pcap(fd);
802 if (__pcap_io->prepare_close_pcap)
803 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
805 close(fd);
807 if (sighup_time > 0) {
808 ftime = (time_t)(start_time + sighup_time);
809 sighup_time = 0;
810 } else
811 ftime = time(NULL);
813 slprintf(fname, sizeof(fname), "%s/%s%lu.pcap", ctx->device_out,
814 ctx->prefix ? : "dump-", ftime);
816 fd = open_or_die_m(fname, O_RDWR | O_CREAT | O_TRUNC |
817 O_LARGEFILE, DEFFILEMODE);
819 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
820 if (ret)
821 panic("Error writing pcap header!\n");
823 if (__pcap_io->prepare_access_pcap) {
824 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
825 if (ret)
826 panic("Error prepare writing pcap!\n");
829 return fd;
832 static void reset_interval(struct ctx *ctx)
834 if (ctx->dump_mode == DUMP_INTERVAL_TIME) {
835 interval = ctx->dump_interval;
837 set_itimer_interval_value(&itimer, interval, 0);
838 setitimer(ITIMER_REAL, &itimer, NULL);
839 } else {
840 interval = 0;
844 static int begin_multi_pcap_file(struct ctx *ctx)
846 int fd, ret;
847 char fname[PATH_MAX];
849 bug_on(!__pcap_io);
851 if (ctx->device_out[strlen(ctx->device_out) - 1] == '/')
852 ctx->device_out[strlen(ctx->device_out) - 1] = 0;
854 slprintf(fname, sizeof(fname), "%s/%s%lu.pcap", ctx->device_out,
855 ctx->prefix ? : "dump-", time(NULL));
857 fd = open_or_die_m(fname, O_RDWR | O_CREAT | O_TRUNC |
858 O_LARGEFILE, DEFFILEMODE);
860 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
861 if (ret)
862 panic("Error writing pcap header!\n");
864 if (__pcap_io->prepare_access_pcap) {
865 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
866 if (ret)
867 panic("Error prepare writing pcap!\n");
870 reset_interval(ctx);
872 return fd;
875 static void finish_single_pcap_file(struct ctx *ctx, int fd)
877 __pcap_io->fsync_pcap(fd);
879 if (__pcap_io->prepare_close_pcap)
880 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
882 if (strncmp("-", ctx->device_out, strlen("-")))
883 close(fd);
884 else
885 dup2(fd, fileno(stdout));
888 static int begin_single_pcap_file(struct ctx *ctx)
890 int fd, ret;
891 char fname[PATH_MAX];
893 bug_on(!__pcap_io);
895 if (!strncmp("-", ctx->device_out, strlen("-"))) {
896 fd = dup_or_die(fileno(stdout));
897 close(fileno(stdout));
898 if (ctx->pcap == PCAP_OPS_MM)
899 ctx->pcap = PCAP_OPS_SG;
900 } else {
901 time_t t;
902 struct tm *ltm;
904 t = time(NULL);
905 if (t == -1)
906 panic("time() failed\n");
908 ltm = localtime(&t);
909 if (ltm == NULL)
910 panic("localtime() failed\n");
912 strftime(fname, sizeof(fname), ctx->device_out, ltm);
914 fd = open_or_die_m(fname,
915 O_RDWR | O_CREAT | O_TRUNC |
916 O_LARGEFILE, DEFFILEMODE);
919 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
920 if (ret)
921 panic("Error writing pcap header!\n");
923 if (__pcap_io->prepare_access_pcap) {
924 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
925 if (ret)
926 panic("Error prepare writing pcap!\n");
929 return fd;
932 static void update_pcap_next_dump(struct ctx *ctx, unsigned long snaplen,
933 int *fd, int sock, bool is_v3)
935 if (!dump_to_pcap(ctx))
936 return;
938 if (ctx->dump_mode == DUMP_INTERVAL_SIZE) {
939 interval += snaplen;
940 if (interval > ctx->dump_interval) {
941 next_dump = true;
942 interval = 0;
946 if (sighup) {
947 if (ctx->verbose)
948 printf("SIGHUP received, prematurely rotating pcap\n");
949 sighup = 0;
950 next_dump = true;
951 reset_interval(ctx);
954 if (next_dump) {
955 *fd = next_multi_pcap_file(ctx, *fd);
956 next_dump = false;
958 if (update_rx_stats(ctx, sock, is_v3))
959 return;
961 if (ctx->verbose && ctx->print_mode == PRINT_NONE)
962 printf(".(+%"PRIu64"/-%"PRIu64")",
963 ctx->pkts_recvd_last - ctx->pkts_drops_last,
964 ctx->pkts_drops_last);
968 #ifdef HAVE_TPACKET3
969 static void walk_t3_block(struct block_desc *pbd, struct ctx *ctx,
970 int sock, int *fd)
972 int num_pkts = pbd->h1.num_pkts, i;
973 struct tpacket3_hdr *hdr;
974 struct sockaddr_ll *sll;
976 hdr = (void *) ((uint8_t *) pbd + pbd->h1.offset_to_first_pkt);
977 sll = (void *) ((uint8_t *) hdr + TPACKET_ALIGN(sizeof(*hdr)));
979 for (i = 0; i < num_pkts && likely(sigint == 0); ++i) {
980 uint8_t *packet = ((uint8_t *) hdr + hdr->tp_mac);
981 pcap_pkthdr_t phdr;
983 if (skip_packet(ctx, sll))
984 goto next;
986 ctx->pkts_seen++;
988 if (dump_to_pcap(ctx)) {
989 int ret;
991 tpacket3_hdr_to_pcap_pkthdr(hdr, sll, &phdr, ctx->magic);
993 ret = __pcap_io->write_pcap(*fd, &phdr, ctx->magic, packet,
994 pcap_get_length(&phdr, ctx->magic));
995 if (unlikely(ret != (int) pcap_get_total_length(&phdr, ctx->magic)))
996 panic("Write error to pcap!\n");
999 __show_frame_hdr(packet, hdr->tp_snaplen, ctx->link_type, sll,
1000 hdr, ctx->print_mode, true, ctx->pkts_seen);
1002 dissector_entry_point(packet, hdr->tp_snaplen, ctx->link_type,
1003 ctx->print_mode, sll);
1004 next:
1005 hdr = (void *) ((uint8_t *) hdr + hdr->tp_next_offset);
1006 sll = (void *) ((uint8_t *) hdr + TPACKET_ALIGN(sizeof(*hdr)));
1008 if (frame_count_max != 0) {
1009 if (unlikely(ctx->pkts_seen >= frame_count_max)) {
1010 sigint = 1;
1011 break;
1015 update_pcap_next_dump(ctx, hdr->tp_snaplen, fd, sock, true);
1018 #endif /* HAVE_TPACKET3 */
1020 static void recv_only_or_dump(struct ctx *ctx)
1022 short ifflags = 0;
1023 int sock, ifindex, fd = 0, ret;
1024 size_t size;
1025 unsigned int it = 0;
1026 struct ring rx_ring;
1027 struct pollfd rx_poll;
1028 struct sock_fprog bpf_ops;
1029 struct timeval start, end, diff;
1030 bool is_v3 = is_defined(HAVE_TPACKET3);
1032 sock = pf_socket_type(ctx->link_type);
1034 ifindex = device_ifindex(ctx->device_in);
1035 size = ring_size(ctx->device_in, ctx->reserve_size);
1037 enable_kernel_bpf_jit_compiler();
1039 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
1040 if (ctx->dump_bpf)
1041 bpf_dump_all(&bpf_ops);
1042 bpf_attach_to_sock(sock, &bpf_ops);
1044 if (ctx->hwtimestamp) {
1045 ret = set_sockopt_hwtimestamp(sock, ctx->device_in);
1046 if (ret == 0 && ctx->verbose)
1047 printf("HW timestamping enabled\n");
1050 ring_rx_setup(&rx_ring, sock, size, ifindex, &rx_poll, is_v3, true,
1051 ctx->verbose, ctx->fanout_group, ctx->fanout_type);
1053 dissector_init_all(ctx->print_mode);
1055 if (ctx->cpu >= 0 && ifindex > 0) {
1056 int irq = device_irq_number(ctx->device_in);
1057 device_set_irq_affinity(irq, ctx->cpu);
1059 if (ctx->verbose)
1060 printf("IRQ: %s:%d > CPU%d\n",
1061 ctx->device_in, irq, ctx->cpu);
1064 if (ctx->promiscuous)
1065 ifflags = device_enter_promiscuous_mode(ctx->device_in);
1067 if (dump_to_pcap(ctx) && __pcap_io->init_once_pcap)
1068 __pcap_io->init_once_pcap(true);
1070 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
1072 if (dump_to_pcap(ctx)) {
1073 struct stat stats;
1075 ret = stat(ctx->device_out, &stats);
1076 if (ret < 0)
1077 ctx->dump_dir = 0;
1078 else
1079 ctx->dump_dir = S_ISDIR(stats.st_mode);
1081 if (ctx->dump_dir)
1082 fd = begin_multi_pcap_file(ctx);
1083 else
1084 fd = begin_single_pcap_file(ctx);
1087 printf("Running! Hang up with ^C!\n\n");
1088 fflush(stdout);
1090 bug_on(gettimeofday(&start, NULL));
1092 while (likely(sigint == 0)) {
1093 #ifdef HAVE_TPACKET3
1094 struct block_desc *pbd;
1096 while (user_may_pull_from_rx_block((pbd = rx_ring.frames[it].iov_base))) {
1097 walk_t3_block(pbd, ctx, sock, &fd);
1099 kernel_may_pull_from_rx_block(pbd);
1100 it = (it + 1) % rx_ring.layout3.tp_block_nr;
1102 if (unlikely(sigint == 1))
1103 break;
1105 #else
1106 while (user_may_pull_from_rx(rx_ring.frames[it].iov_base)) {
1107 struct frame_map *hdr = rx_ring.frames[it].iov_base;
1108 uint8_t *packet = ((uint8_t *) hdr) + hdr->tp_h.tp_mac;
1109 pcap_pkthdr_t phdr;
1111 if (skip_packet(ctx, &hdr->s_ll))
1112 goto next;
1114 ctx->pkts_seen++;
1116 if (unlikely(ring_frame_size(&rx_ring) < hdr->tp_h.tp_snaplen)) {
1117 /* XXX: silently ignore for now. We used to
1118 * report them with dump_rx_stats() */
1119 goto next;
1122 if (dump_to_pcap(ctx)) {
1123 tpacket_hdr_to_pcap_pkthdr(&hdr->tp_h, &hdr->s_ll, &phdr, ctx->magic);
1125 ret = __pcap_io->write_pcap(fd, &phdr, ctx->magic, packet,
1126 pcap_get_length(&phdr, ctx->magic));
1127 if (unlikely(ret != (int) pcap_get_total_length(&phdr, ctx->magic)))
1128 panic("Write error to pcap!\n");
1131 show_frame_hdr(packet, hdr->tp_h.tp_snaplen,
1132 ctx->link_type, hdr, ctx->print_mode,
1133 ctx->pkts_seen);
1135 dissector_entry_point(packet, hdr->tp_h.tp_snaplen,
1136 ctx->link_type, ctx->print_mode,
1137 &hdr->s_ll);
1139 if (frame_count_max != 0) {
1140 if (unlikely(ctx->pkts_seen >= frame_count_max)) {
1141 sigint = 1;
1142 break;
1146 next:
1147 kernel_may_pull_from_rx(&hdr->tp_h);
1148 it = (it + 1) % rx_ring.layout.tp_frame_nr;
1150 if (unlikely(sigint == 1))
1151 break;
1153 update_pcap_next_dump(ctx, hdr->tp_h.tp_snaplen, &fd,
1154 sock, is_v3);
1156 #endif /* HAVE_TPACKET3 */
1158 ret = poll(&rx_poll, 1, -1);
1159 if (unlikely(ret < 0)) {
1160 if (errno != EINTR)
1161 panic("Poll failed!\n");
1165 bug_on(gettimeofday(&end, NULL));
1166 timersub(&end, &start, &diff);
1168 dump_rx_stats(ctx, sock, is_v3);
1169 printf("\r%12lu sec, %lu usec in total\n",
1170 diff.tv_sec, diff.tv_usec);
1172 bpf_release(&bpf_ops);
1173 dissector_cleanup_all();
1174 destroy_rx_ring(sock, &rx_ring);
1176 if (ctx->promiscuous)
1177 device_leave_promiscuous_mode(ctx->device_in, ifflags);
1179 if (ctx->rfraw)
1180 leave_rfmon_mac80211(ctx->device_in);
1182 if (dump_to_pcap(ctx)) {
1183 if (ctx->dump_dir)
1184 finish_multi_pcap_file(ctx, fd);
1185 else
1186 finish_single_pcap_file(ctx, fd);
1189 close(sock);
1192 static void init_ctx(struct ctx *ctx)
1194 memset(ctx, 0, sizeof(*ctx));
1196 ctx->uid = getuid();
1197 ctx->gid = getgid();
1199 ctx->cpu = -1;
1200 ctx->packet_type = -1;
1202 ctx->fanout_type = PACKET_FANOUT_ROLLOVER;
1204 ctx->magic = ORIGINAL_TCPDUMP_MAGIC;
1205 ctx->print_mode = PRINT_NORM;
1206 ctx->pcap = PCAP_OPS_SG;
1208 ctx->dump_mode = DUMP_INTERVAL_TIME;
1209 ctx->dump_interval = 60;
1211 ctx->promiscuous = true;
1212 ctx->randomize = false;
1213 ctx->hwtimestamp = true;
1216 static void destroy_ctx(struct ctx *ctx)
1218 free(ctx->device_in);
1219 free(ctx->device_out);
1220 free(ctx->device_trans);
1222 free(ctx->prefix);
1225 static void __noreturn help(void)
1227 printf("netsniff-ng %s, the packet sniffing beast\n", VERSION_STRING);
1228 puts("http://www.netsniff-ng.org\n\n"
1229 "Usage: netsniff-ng [options] [filter-expression]\n"
1230 "Options:\n"
1231 " -i|-d|--dev|--in <dev|pcap|-> Input source as netdev, pcap or pcap stdin\n"
1232 " -o|--out <dev|pcap|dir|cfg|-> Output sink as netdev, pcap, directory, trafgen, or stdout\n"
1233 " -C|--fanout-group <id> Join packet fanout group\n"
1234 " -K|--fanout-type <type> Apply fanout discipline: hash|lb|cpu|rnd|roll|qm\n"
1235 " -L|--fanout-opts <opts> Additional fanout options: defrag|roll\n"
1236 " -f|--filter <bpf-file|-|expr> Use BPF filter from bpfc file/stdin or tcpdump-like expression\n"
1237 " -t|--type <type> Filter for: host|broadcast|multicast|others|outgoing\n"
1238 " -F|--interval <size|time> Dump interval if -o is a dir: <num>KiB/MiB/GiB/s/sec/min/hrs\n"
1239 " -R|--rfraw Capture or inject raw 802.11 frames\n"
1240 " -n|--num <0|uint> Number of packets until exit (def: 0)\n"
1241 " -P|--prefix <name> Prefix for pcaps stored in directory\n"
1242 " -T|--magic <pcap-magic> Pcap magic number/pcap format to store, see -D\n"
1243 " -w|--cooked Use Linux \"cooked\" header instead of link header\n"
1244 " -D|--dump-pcap-types Dump pcap types and magic numbers and quit\n"
1245 " -B|--dump-bpf Dump generated BPF assembly\n"
1246 " -r|--rand Randomize packet forwarding order (dev->dev)\n"
1247 " -M|--no-promisc No promiscuous mode for netdev\n"
1248 " -A|--no-sock-mem Don't tune core socket memory\n"
1249 " -N|--no-hwtimestamp Disable hardware time stamping\n"
1250 " -m|--mmap Mmap(2) pcap file I/O, e.g. for replaying pcaps\n"
1251 " -G|--sg Scatter/gather pcap file I/O\n"
1252 " -c|--clrw Use slower read(2)/write(2) I/O\n"
1253 " -S|--ring-size <size> Specify ring size to: <num>KiB/MiB/GiB\n"
1254 " -k|--kernel-pull <uint> Kernel pull from user interval in us (def: 10us)\n"
1255 " -J|--jumbo-support Support replay/fwd 64KB Super Jumbo Frames (def: 2048B)\n"
1256 " -b|--bind-cpu <cpu> Bind to specific CPU\n"
1257 " -u|--user <userid> Drop privileges and change to userid\n"
1258 " -g|--group <groupid> Drop privileges and change to groupid\n"
1259 " -H|--prio-high Make this high priority process\n"
1260 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
1261 " -s|--silent Do not print captured packets\n"
1262 " -q|--less Print less-verbose packet information\n"
1263 " -X|--hex Print packet data in hex format\n"
1264 " -l|--ascii Print human-readable packet data\n"
1265 " -U|--update Update GeoIP databases\n"
1266 " -V|--verbose Be more verbose\n"
1267 " -v|--version Show version and exit\n"
1268 " -h|--help Guess what?!\n\n"
1269 "Examples:\n"
1270 " netsniff-ng --in eth0 --out dump.pcap -s -T 0xa1b2c3d4 --bind-cpu 0 tcp or udp\n"
1271 " netsniff-ng --in wlan0 --rfraw --out dump.pcap --silent --bind-cpu 0\n"
1272 " netsniff-ng --in dump.pcap --mmap --out eth0 -k1000 --silent --bind-cpu 0\n"
1273 " netsniff-ng --in dump.pcap --out dump.cfg --silent --bind-cpu 0\n"
1274 " netsniff-ng --in dump.pcap --out dump2.pcap --silent tcp\n"
1275 " netsniff-ng --in eth0 --out eth1 --silent --bind-cpu 0 -J --type host\n"
1276 " netsniff-ng --in eth1 --out /opt/probe/ -s -m --interval 100MiB -b 0\n"
1277 " netsniff-ng --in vlan0 --out dump.pcap -c -u `id -u bob` -g `id -g bob`\n"
1278 " netsniff-ng --in any --filter http.bpf --jumbo-support --ascii -V\n\n"
1279 "Note:\n"
1280 " For introducing bit errors, delays with random variation and more\n"
1281 " while replaying pcaps, make use of tc(8) with its disciplines (e.g. netem).\n");
1282 puts(copyright);
1283 die();
1286 static void __noreturn version(void)
1288 printf("netsniff-ng %s, Git id: %s\n", VERSION_LONG, GITVERSION);
1289 puts("the packet sniffing beast\n"
1290 "http://www.netsniff-ng.org\n");
1291 puts(copyright);
1292 die();
1295 int main(int argc, char **argv)
1297 char *ptr;
1298 int c, i, j, cpu_tmp, ops_touched = 0, vals[4] = {0};
1299 bool prio_high = false, setsockmem = true;
1300 void (*main_loop)(struct ctx *ctx) = NULL;
1301 struct ctx ctx;
1303 init_ctx(&ctx);
1304 start_time = time(NULL);
1305 srand(start_time);
1307 while ((c = getopt_long(argc, argv, short_options, long_options,
1308 NULL)) != EOF) {
1309 switch (c) {
1310 case 'd':
1311 case 'i':
1312 ctx.device_in = xstrdup(optarg);
1313 break;
1314 case 'o':
1315 ctx.device_out = xstrdup(optarg);
1316 break;
1317 case 'P':
1318 ctx.prefix = xstrdup(optarg);
1319 break;
1320 case 'R':
1321 ctx.rfraw = 1;
1322 break;
1323 case 'r':
1324 ctx.randomize = true;
1325 break;
1326 case 'J':
1327 ctx.jumbo = true;
1328 break;
1329 case 'T':
1330 ctx.magic = (uint32_t) strtoul(optarg, NULL, 0);
1331 pcap_check_magic(ctx.magic);
1332 break;
1333 case 'f':
1334 ctx.filter = xstrdup(optarg);
1335 break;
1336 case 'M':
1337 ctx.promiscuous = false;
1338 break;
1339 case 'N':
1340 ctx.hwtimestamp = false;
1341 break;
1342 case 'A':
1343 setsockmem = false;
1344 break;
1345 case 'u':
1346 ctx.uid = strtoul(optarg, NULL, 0);
1347 ctx.enforce = true;
1348 break;
1349 case 'g':
1350 ctx.gid = strtoul(optarg, NULL, 0);
1351 ctx.enforce = true;
1352 break;
1353 case 'C':
1354 ctx.fanout_group = strtoul(optarg, NULL, 0);
1355 if (ctx.fanout_group == 0)
1356 panic("Non-zero fanout group id required!\n");
1357 break;
1358 case 'K':
1359 if (!strncmp(optarg, "hash", strlen("hash")))
1360 ctx.fanout_type = PACKET_FANOUT_HASH;
1361 else if (!strncmp(optarg, "lb", strlen("lb")) ||
1362 !strncmp(optarg, "rr", strlen("rr")))
1363 ctx.fanout_type = PACKET_FANOUT_LB;
1364 else if (!strncmp(optarg, "cpu", strlen("cpu")))
1365 ctx.fanout_type = PACKET_FANOUT_CPU;
1366 else if (!strncmp(optarg, "rnd", strlen("rnd")))
1367 ctx.fanout_type = PACKET_FANOUT_RND;
1368 else if (!strncmp(optarg, "roll", strlen("roll")))
1369 ctx.fanout_type = PACKET_FANOUT_ROLLOVER;
1370 else if (!strncmp(optarg, "qm", strlen("qm")))
1371 ctx.fanout_type = PACKET_FANOUT_QM;
1372 else
1373 panic("Unknown fanout type!\n");
1374 break;
1375 case 'L':
1376 if (!strncmp(optarg, "defrag", strlen("defrag")))
1377 ctx.fanout_type |= PACKET_FANOUT_FLAG_DEFRAG;
1378 else if (!strncmp(optarg, "roll", strlen("roll")))
1379 ctx.fanout_type |= PACKET_FANOUT_FLAG_ROLLOVER;
1380 else
1381 panic("Unknown fanout option!\n");
1382 break;
1383 case 't':
1384 if (!strncmp(optarg, "host", strlen("host")))
1385 ctx.packet_type = PACKET_HOST;
1386 else if (!strncmp(optarg, "broadcast", strlen("broadcast")))
1387 ctx.packet_type = PACKET_BROADCAST;
1388 else if (!strncmp(optarg, "multicast", strlen("multicast")))
1389 ctx.packet_type = PACKET_MULTICAST;
1390 else if (!strncmp(optarg, "others", strlen("others")))
1391 ctx.packet_type = PACKET_OTHERHOST;
1392 else if (!strncmp(optarg, "outgoing", strlen("outgoing")))
1393 ctx.packet_type = PACKET_OUTGOING;
1394 else
1395 ctx.packet_type = -1;
1396 break;
1397 case 'S':
1398 ptr = optarg;
1399 for (j = i = strlen(optarg); i > 0; --i) {
1400 if (!isdigit(optarg[j - i]))
1401 break;
1402 ptr++;
1405 if (!strncmp(ptr, "KiB", strlen("KiB")))
1406 ctx.reserve_size = 1 << 10;
1407 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1408 ctx.reserve_size = 1 << 20;
1409 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1410 ctx.reserve_size = 1 << 30;
1411 else
1412 panic("Syntax error in ring size param!\n");
1414 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1415 break;
1416 case 'b':
1417 cpu_tmp = strtol(optarg, NULL, 0);
1419 cpu_affinity(cpu_tmp);
1420 if (ctx.cpu != -2)
1421 ctx.cpu = cpu_tmp;
1422 break;
1423 case 'H':
1424 prio_high = true;
1425 break;
1426 case 'c':
1427 ctx.pcap = PCAP_OPS_RW;
1428 ops_touched = 1;
1429 break;
1430 case 'm':
1431 ctx.pcap = PCAP_OPS_MM;
1432 ops_touched = 1;
1433 break;
1434 case 'G':
1435 ctx.pcap = PCAP_OPS_SG;
1436 ops_touched = 1;
1437 break;
1438 case 'Q':
1439 ctx.cpu = -2;
1440 break;
1441 case 's':
1442 ctx.print_mode = PRINT_NONE;
1443 break;
1444 case 'q':
1445 ctx.print_mode = PRINT_LESS;
1446 break;
1447 case 'X':
1448 ctx.print_mode =
1449 (ctx.print_mode == PRINT_ASCII) ?
1450 PRINT_HEX_ASCII : PRINT_HEX;
1451 break;
1452 case 'l':
1453 ctx.print_mode =
1454 (ctx.print_mode == PRINT_HEX) ?
1455 PRINT_HEX_ASCII : PRINT_ASCII;
1456 break;
1457 case 'k':
1458 ctx.kpull = strtoul(optarg, NULL, 0);
1459 break;
1460 case 'n':
1461 frame_count_max = strtoul(optarg, NULL, 0);
1462 break;
1463 case 'F':
1464 ptr = optarg;
1465 for (j = i = strlen(optarg); i > 0; --i) {
1466 if (!isdigit(optarg[j - i]))
1467 break;
1468 ptr++;
1471 if (!strncmp(ptr, "KiB", strlen("KiB"))) {
1472 ctx.dump_interval = 1 << 10;
1473 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1474 } else if (!strncmp(ptr, "MiB", strlen("MiB"))) {
1475 ctx.dump_interval = 1 << 20;
1476 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1477 } else if (!strncmp(ptr, "GiB", strlen("GiB"))) {
1478 ctx.dump_interval = 1 << 30;
1479 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1480 } else if (!strncmp(ptr, "sec", strlen("sec"))) {
1481 ctx.dump_interval = 1;
1482 ctx.dump_mode = DUMP_INTERVAL_TIME;
1483 } else if (!strncmp(ptr, "min", strlen("min"))) {
1484 ctx.dump_interval = 60;
1485 ctx.dump_mode = DUMP_INTERVAL_TIME;
1486 } else if (!strncmp(ptr, "hrs", strlen("hrs"))) {
1487 ctx.dump_interval = 60 * 60;
1488 ctx.dump_mode = DUMP_INTERVAL_TIME;
1489 } else if (!strncmp(ptr, "s", strlen("s"))) {
1490 ctx.dump_interval = 1;
1491 ctx.dump_mode = DUMP_INTERVAL_TIME;
1492 } else {
1493 panic("Syntax error in time/size param!\n");
1496 ctx.dump_interval *= strtoul(optarg, NULL, 0);
1497 break;
1498 case 'V':
1499 ctx.verbose = true;
1500 break;
1501 case 'B':
1502 ctx.dump_bpf = true;
1503 break;
1504 case 'D':
1505 pcap_dump_type_features();
1506 die();
1507 break;
1508 case 'U':
1509 update_geoip();
1510 die();
1511 break;
1512 case 'w':
1513 ctx.link_type = LINKTYPE_LINUX_SLL;
1514 break;
1515 case 'v':
1516 version();
1517 break;
1518 case 'h':
1519 help();
1520 break;
1521 case '?':
1522 switch (optopt) {
1523 case 'd':
1524 case 'i':
1525 case 'o':
1526 case 'f':
1527 case 't':
1528 case 'P':
1529 case 'F':
1530 case 'n':
1531 case 'S':
1532 case 'b':
1533 case 'k':
1534 case 'T':
1535 case 'u':
1536 case 'g':
1537 case 'e':
1538 panic("Option -%c requires an argument!\n",
1539 optopt);
1540 default:
1541 if (isprint(optopt))
1542 printf("Unknown option character `0x%X\'!\n", optopt);
1543 die();
1545 default:
1546 break;
1550 if (!ctx.filter && optind != argc)
1551 ctx.filter = argv2str(optind, argc, argv);
1553 if (!ctx.device_in)
1554 ctx.device_in = xstrdup("any");
1556 if (!strcmp(ctx.device_in, "any") || !strcmp(ctx.device_in, "lo"))
1557 ctx.lo_ifindex = device_ifindex("lo");
1559 register_signal(SIGINT, signal_handler);
1560 register_signal(SIGQUIT, signal_handler);
1561 register_signal(SIGTERM, signal_handler);
1562 register_signal(SIGHUP, signal_handler);
1564 tprintf_init();
1566 if (prio_high) {
1567 set_proc_prio(-20);
1568 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1571 if (device_mtu(ctx.device_in) || !strncmp("any", ctx.device_in, strlen(ctx.device_in))) {
1572 if (ctx.rfraw)
1573 setup_rfmon_mac80211_dev(&ctx, &ctx.device_in);
1575 if (!ctx.link_type)
1576 ctx.link_type = pcap_dev_to_linktype(ctx.device_in);
1577 if (link_has_sll_hdr(ctx.link_type)) {
1578 switch (ctx.magic) {
1579 case ORIGINAL_TCPDUMP_MAGIC:
1580 ctx.magic = ORIGINAL_TCPDUMP_MAGIC_LL;
1581 break;
1582 case NSEC_TCPDUMP_MAGIC:
1583 ctx.magic = NSEC_TCPDUMP_MAGIC_LL;
1584 break;
1585 case ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC):
1586 ctx.magic = ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC_LL);
1587 break;
1588 case ___constant_swab32(NSEC_TCPDUMP_MAGIC):
1589 ctx.magic = ___constant_swab32(NSEC_TCPDUMP_MAGIC_LL);
1590 break;
1595 if (!ctx.device_out) {
1596 ctx.dump = 0;
1597 main_loop = recv_only_or_dump;
1598 } else if (device_mtu(ctx.device_out)) {
1599 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1600 main_loop = receive_to_xmit;
1601 } else {
1602 ctx.dump = 1;
1603 register_signal_f(SIGALRM, timer_next_dump, SA_SIGINFO);
1604 main_loop = recv_only_or_dump;
1605 if (!ops_touched)
1606 ctx.pcap = PCAP_OPS_SG;
1608 } else {
1609 if (ctx.device_out && device_mtu(ctx.device_out)) {
1610 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1611 main_loop = pcap_to_xmit;
1612 if (!ops_touched)
1613 ctx.pcap = PCAP_OPS_MM;
1614 } else {
1615 setsockmem = false;
1616 main_loop = read_pcap;
1617 if (!ops_touched)
1618 ctx.pcap = PCAP_OPS_SG;
1622 bug_on(!main_loop);
1624 init_geoip(0);
1625 if (setsockmem)
1626 set_system_socket_memory(vals, array_size(vals));
1627 if (!ctx.enforce)
1628 xlockme();
1630 if (ctx.verbose)
1631 printf("pcap file I/O method: %s\n", pcap_ops_group_to_str[ctx.pcap]);
1633 main_loop(&ctx);
1635 if (!ctx.enforce)
1636 xunlockme();
1637 if (setsockmem)
1638 reset_system_socket_memory(vals, array_size(vals));
1639 destroy_geoip();
1641 device_restore_irq_affinity_list();
1642 tprintf_cleanup();
1644 destroy_ctx(&ctx);
1645 return 0;