netsniff-ng v0.6.8
[netsniff-ng.git] / netsniff-ng.c
blobaff569d0629e03df99174460181311a18eb3a41b
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 printf("\r%12"PRIu64" packets incoming (%"PRIu64" unread on exit)\n",
242 is_v3 ? ctx->pkts_seen : ctx->pkts_recvd,
243 is_v3 ? ctx->pkts_recvd - ctx->pkts_seen : 0);
244 printf("\r%12"PRIu64" packets passed filter\n",
245 ctx->pkts_recvd - ctx->pkts_drops);
246 printf("\r%12"PRIu64" packets failed filter (out of space)\n",
247 ctx->pkts_drops);
249 if (ctx->pkts_recvd > 0)
250 printf("\r%12.4lf%% packet droprate\n",
251 (1.0 * ctx->pkts_drops / ctx->pkts_recvd) * 100.0);
254 static void pcap_to_xmit(struct ctx *ctx)
256 uint8_t *out = NULL;
257 int ifindex, fd = 0, ret;
258 size_t size;
259 unsigned int it = 0;
260 unsigned long trunced = 0;
261 struct ring tx_ring;
262 struct frame_map *hdr;
263 struct sock_fprog bpf_ops;
264 struct timeval start, end, diff;
265 pcap_pkthdr_t phdr;
267 if (!device_up_and_running(ctx->device_out) && !ctx->rfraw)
268 panic("Device not up and running!\n");
270 bug_on(!__pcap_io);
272 tx_sock = pf_socket();
274 if (!strncmp("-", ctx->device_in, strlen("-"))) {
275 fd = dup_or_die(fileno(stdin));
276 close(fileno(stdin));
277 if (ctx->pcap == PCAP_OPS_MM)
278 ctx->pcap = PCAP_OPS_SG;
279 } else {
280 fd = open_or_die(ctx->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
283 if (__pcap_io->init_once_pcap)
284 __pcap_io->init_once_pcap(true);
286 ret = __pcap_io->pull_fhdr_pcap(fd, &ctx->magic, &ctx->link_type);
287 if (ret)
288 panic("Error reading pcap header!\n");
290 if (__pcap_io->prepare_access_pcap) {
291 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_RD, ctx->jumbo);
292 if (ret)
293 panic("Error prepare reading pcap!\n");
296 if (ctx->rfraw) {
297 setup_rfmon_mac80211_dev(ctx, &ctx->device_out);
299 if (ctx->link_type != LINKTYPE_IEEE802_11 &&
300 ctx->link_type != LINKTYPE_IEEE802_11_RADIOTAP)
301 panic("Wrong linktype of pcap!\n");
304 ifindex = device_ifindex(ctx->device_out);
305 size = ring_size(ctx->device_out, ctx->reserve_size);
307 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
308 if (ctx->dump_bpf)
309 bpf_dump_all(&bpf_ops);
311 ring_tx_setup(&tx_ring, tx_sock, size, ifindex, ctx->jumbo, ctx->verbose);
313 dissector_init_all(ctx->print_mode);
315 if (ctx->cpu >= 0 && ifindex > 0) {
316 int irq = device_irq_number(ctx->device_out);
317 device_set_irq_affinity(irq, ctx->cpu);
319 if (ctx->verbose)
320 printf("IRQ: %s:%d > CPU%d\n",
321 ctx->device_out, irq, ctx->cpu);
324 if (ctx->kpull)
325 interval = ctx->kpull;
327 set_itimer_interval_value(&itimer, 0, interval);
328 setitimer(ITIMER_REAL, &itimer, NULL);
330 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
332 printf("Running! Hang up with ^C!\n\n");
333 fflush(stdout);
335 bug_on(gettimeofday(&start, NULL));
337 while (likely(sigint == 0)) {
338 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
339 hdr = tx_ring.frames[it].iov_base;
340 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
342 do {
343 ret = __pcap_io->read_pcap(fd, &phdr, ctx->magic, out,
344 ring_frame_size(&tx_ring));
345 if (unlikely(ret <= 0))
346 goto out;
348 if (ring_frame_size(&tx_ring) <
349 pcap_get_length(&phdr, ctx->magic)) {
350 pcap_set_length(&phdr, ctx->magic,
351 ring_frame_size(&tx_ring));
352 trunced++;
354 } while (ctx->filter &&
355 !bpf_run_filter(&bpf_ops, out,
356 pcap_get_length(&phdr, ctx->magic)));
358 pcap_pkthdr_to_tpacket_hdr(&phdr, ctx->magic, &hdr->tp_h, NULL);
360 ctx->tx_bytes += hdr->tp_h.tp_len;;
361 ctx->tx_packets++;
363 show_frame_hdr(out, hdr->tp_h.tp_snaplen,
364 ctx->link_type, hdr, ctx->print_mode,
365 ctx->tx_packets);
367 dissector_entry_point(out, hdr->tp_h.tp_snaplen,
368 ctx->link_type, ctx->print_mode,
369 &hdr->s_ll);
371 kernel_may_pull_from_tx(&hdr->tp_h);
373 it++;
374 if (it >= tx_ring.layout.tp_frame_nr)
375 it = 0;
377 if (unlikely(sigint == 1))
378 break;
380 if (frame_count_max != 0) {
381 if (ctx->tx_packets >= frame_count_max) {
382 sigint = 1;
383 break;
389 out:
390 bug_on(gettimeofday(&end, NULL));
391 timersub(&end, &start, &diff);
393 timer_purge();
395 bpf_release(&bpf_ops);
397 dissector_cleanup_all();
398 destroy_tx_ring(tx_sock, &tx_ring);
400 if (ctx->rfraw)
401 leave_rfmon_mac80211(ctx->device_out);
403 if (__pcap_io->prepare_close_pcap)
404 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_RD);
406 if (!strncmp("-", ctx->device_in, strlen("-")))
407 dup2(fd, fileno(stdin));
408 close(fd);
410 close(tx_sock);
412 fflush(stdout);
413 printf("\n");
414 printf("\r%12lu packets outgoing\n", ctx->tx_packets);
415 printf("\r%12lu packets truncated in file\n", trunced);
416 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
417 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
420 static inline bool __skip_packet(struct ctx *ctx, struct sockaddr_ll *sll)
422 if (ctx->packet_type != -1)
423 return ctx->packet_type != sll->sll_pkttype;
425 /* when receving from the loopback device, each packet is seen twice,
426 * so drop the outgoing ones to avoid duplicates
428 return (sll->sll_ifindex == ctx->lo_ifindex) &&
429 (sll->sll_pkttype == PACKET_OUTGOING);
432 static inline bool skip_packet(struct ctx *ctx, struct sockaddr_ll *sll)
434 bool skip = __skip_packet(ctx, sll);
436 if (skip)
437 ctx->pkts_skipd_last++;
438 return skip;
441 static void receive_to_xmit(struct ctx *ctx)
443 short ifflags = 0;
444 uint8_t *in, *out;
445 int rx_sock, ifindex_in, ifindex_out, ret;
446 size_t size_in, size_out;
447 unsigned int it_in = 0, it_out = 0;
448 struct frame_map *hdr_in, *hdr_out;
449 struct ring tx_ring, rx_ring;
450 struct pollfd rx_poll;
451 struct sock_fprog bpf_ops;
453 if (!strncmp(ctx->device_in, ctx->device_out, IFNAMSIZ))
454 panic("Ingress/egress devices must be different!\n");
455 if (!device_up_and_running(ctx->device_out))
456 panic("Egress device not up and running!\n");
458 rx_sock = pf_socket();
459 tx_sock = pf_socket();
461 ifindex_in = device_ifindex(ctx->device_in);
462 ifindex_out = device_ifindex(ctx->device_out);
464 size_in = ring_size(ctx->device_in, ctx->reserve_size);
465 size_out = ring_size(ctx->device_out, ctx->reserve_size);
467 enable_kernel_bpf_jit_compiler();
469 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
470 if (ctx->dump_bpf)
471 bpf_dump_all(&bpf_ops);
472 bpf_attach_to_sock(rx_sock, &bpf_ops);
474 ring_rx_setup(&rx_ring, rx_sock, size_in, ifindex_in, &rx_poll, false, ctx->jumbo,
475 ctx->verbose, ctx->fanout_group, ctx->fanout_type);
476 ring_tx_setup(&tx_ring, tx_sock, size_out, ifindex_out, ctx->jumbo, ctx->verbose);
478 dissector_init_all(ctx->print_mode);
480 if (ctx->promiscuous)
481 ifflags = device_enter_promiscuous_mode(ctx->device_in);
483 if (ctx->kpull)
484 interval = ctx->kpull;
486 set_itimer_interval_value(&itimer, 0, interval);
487 setitimer(ITIMER_REAL, &itimer, NULL);
489 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
491 printf("Running! Hang up with ^C!\n\n");
492 fflush(stdout);
494 while (likely(sigint == 0)) {
495 while (user_may_pull_from_rx(rx_ring.frames[it_in].iov_base)) {
496 hdr_in = rx_ring.frames[it_in].iov_base;
497 in = ((uint8_t *) hdr_in) + hdr_in->tp_h.tp_mac;
499 if (skip_packet(ctx, &hdr_in->s_ll))
500 goto next;
502 ctx->pkts_seen++;
504 hdr_out = tx_ring.frames[it_out].iov_base;
505 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
507 while (!user_may_pull_from_tx(tx_ring.frames[it_out].iov_base) &&
508 likely(!sigint)) {
509 if (ctx->randomize)
510 next_rnd_slot(&it_out, &tx_ring);
511 else {
512 it_out++;
513 if (it_out >= tx_ring.layout.tp_frame_nr)
514 it_out = 0;
517 hdr_out = tx_ring.frames[it_out].iov_base;
518 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
521 tpacket_hdr_clone(&hdr_out->tp_h, &hdr_in->tp_h);
522 memcpy(out, in, hdr_in->tp_h.tp_len);
524 kernel_may_pull_from_tx(&hdr_out->tp_h);
525 if (ctx->randomize)
526 next_rnd_slot(&it_out, &tx_ring);
527 else {
528 it_out++;
529 if (it_out >= tx_ring.layout.tp_frame_nr)
530 it_out = 0;
533 show_frame_hdr(in, hdr_in->tp_h.tp_snaplen,
534 ctx->link_type, hdr_in, ctx->print_mode,
535 ctx->pkts_seen);
537 dissector_entry_point(in, hdr_in->tp_h.tp_snaplen,
538 ctx->link_type, ctx->print_mode,
539 &hdr_in->s_ll);
541 if (frame_count_max != 0) {
542 if (ctx->pkts_seen >= frame_count_max) {
543 sigint = 1;
544 break;
548 next:
549 kernel_may_pull_from_rx(&hdr_in->tp_h);
551 it_in++;
552 if (it_in >= rx_ring.layout.tp_frame_nr)
553 it_in = 0;
555 if (unlikely(sigint == 1))
556 goto out;
559 ret = poll(&rx_poll, 1, -1);
560 if (unlikely(ret < 0)) {
561 if (errno != EINTR)
562 panic("Poll failed!\n");
566 out:
567 timer_purge();
569 dump_rx_stats(ctx, rx_sock, false);
571 bpf_release(&bpf_ops);
573 dissector_cleanup_all();
575 destroy_tx_ring(tx_sock, &tx_ring);
576 destroy_rx_ring(rx_sock, &rx_ring);
578 if (ctx->promiscuous)
579 device_leave_promiscuous_mode(ctx->device_in, ifflags);
581 close(tx_sock);
582 close(rx_sock);
585 static void translate_pcap_to_txf(int fdo, uint8_t *out, size_t len)
587 size_t bytes_done = 0;
588 char bout[80];
590 slprintf(bout, sizeof(bout), "{\n ");
591 write_or_die(fdo, bout, strlen(bout));
593 while (bytes_done < len) {
594 slprintf(bout, sizeof(bout), "0x%02x,", out[bytes_done]);
595 write_or_die(fdo, bout, strlen(bout));
597 bytes_done++;
599 if (bytes_done % 10 == 0) {
600 slprintf(bout, sizeof(bout), "\n");
601 write_or_die(fdo, bout, strlen(bout));
603 if (bytes_done < len) {
604 slprintf(bout, sizeof(bout), " ");
605 write_or_die(fdo, bout, strlen(bout));
607 } else if (bytes_done < len) {
608 slprintf(bout, sizeof(bout), " ");
609 write_or_die(fdo, bout, strlen(bout));
612 if (bytes_done % 10 != 0) {
613 slprintf(bout, sizeof(bout), "\n");
614 write_or_die(fdo, bout, strlen(bout));
617 slprintf(bout, sizeof(bout), "}\n\n");
618 write_or_die(fdo, bout, strlen(bout));
621 static void read_pcap(struct ctx *ctx)
623 uint8_t *out;
624 int ret, fd, fdo = 0;
625 unsigned long trunced = 0;
626 size_t out_len;
627 pcap_pkthdr_t phdr;
628 struct sock_fprog bpf_ops;
629 struct frame_map fm;
630 struct timeval start, end, diff;
631 bool is_out_pcap = ctx->device_out && strstr(ctx->device_out, ".pcap");
632 const struct pcap_file_ops *pcap_out_ops = pcap_ops[PCAP_OPS_RW];
634 bug_on(!__pcap_io);
636 if (!strncmp("-", ctx->device_in, strlen("-"))) {
637 fd = dup_or_die(fileno(stdin));
638 close(fileno(stdin));
639 if (ctx->pcap == PCAP_OPS_MM)
640 ctx->pcap = PCAP_OPS_SG;
641 } else {
642 /* O_NOATIME requires privileges, in case we don't have
643 * them, retry without them at a minor cost of updating
644 * atime in case the fs has been mounted as such.
646 fd = open(ctx->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
647 if (fd < 0 && errno == EPERM)
648 fd = open_or_die(ctx->device_in, O_RDONLY | O_LARGEFILE);
649 if (fd < 0)
650 panic("Cannot open file %s! %s.\n", ctx->device_in,
651 strerror(errno));
654 if (__pcap_io->init_once_pcap)
655 __pcap_io->init_once_pcap(false);
657 ret = __pcap_io->pull_fhdr_pcap(fd, &ctx->magic, &ctx->link_type);
658 if (ret)
659 panic("Error reading pcap header!\n");
661 if (__pcap_io->prepare_access_pcap) {
662 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_RD, ctx->jumbo);
663 if (ret)
664 panic("Error prepare reading pcap!\n");
667 memset(&fm, 0, sizeof(fm));
669 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
670 if (ctx->dump_bpf)
671 bpf_dump_all(&bpf_ops);
673 dissector_init_all(ctx->print_mode);
675 out_len = round_up(1024 * 1024, RUNTIME_PAGE_SIZE);
676 out = xmalloc_aligned(out_len, CO_CACHE_LINE_SIZE);
678 if (ctx->device_out) {
679 if (!strncmp("-", ctx->device_out, strlen("-"))) {
680 fdo = dup_or_die(fileno(stdout));
681 close(fileno(stdout));
682 } else {
683 fdo = open_or_die_m(ctx->device_out, O_RDWR | O_CREAT |
684 O_TRUNC | O_LARGEFILE, DEFFILEMODE);
688 if (is_out_pcap) {
689 ret = pcap_out_ops->push_fhdr_pcap(fdo, ctx->magic,
690 ctx->link_type);
691 if (ret)
692 panic("Error writing pcap header!\n");
695 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
697 printf("Running! Hang up with ^C!\n\n");
698 fflush(stdout);
700 bug_on(gettimeofday(&start, NULL));
702 while (likely(sigint == 0)) {
703 do {
704 ret = __pcap_io->read_pcap(fd, &phdr, ctx->magic,
705 out, out_len);
706 if (unlikely(ret < 0))
707 goto out;
709 if (unlikely(pcap_get_length(&phdr, ctx->magic) == 0)) {
710 trunced++;
711 continue;
714 if (unlikely(pcap_get_length(&phdr, ctx->magic) > out_len)) {
715 pcap_set_length(&phdr, ctx->magic, out_len);
716 trunced++;
718 } while (ctx->filter &&
719 !bpf_run_filter(&bpf_ops, out,
720 pcap_get_length(&phdr, ctx->magic)));
722 pcap_pkthdr_to_tpacket_hdr(&phdr, ctx->magic, &fm.tp_h, &fm.s_ll);
724 ctx->tx_bytes += fm.tp_h.tp_len;
725 ctx->tx_packets++;
727 show_frame_hdr(out, fm.tp_h.tp_snaplen, ctx->link_type, &fm,
728 ctx->print_mode, ctx->tx_packets);
730 dissector_entry_point(out, fm.tp_h.tp_snaplen,
731 ctx->link_type, ctx->print_mode,
732 &fm.s_ll);
734 if (is_out_pcap) {
735 size_t pcap_len = pcap_get_length(&phdr, ctx->magic);
736 int wlen = pcap_out_ops->write_pcap(fdo, &phdr,
737 ctx->magic, out,
738 pcap_len);
739 if (unlikely(wlen != (int)pcap_get_total_length(&phdr, ctx->magic)))
740 panic("Error writing to pcap!\n");
741 } else if (ctx->device_out) {
742 translate_pcap_to_txf(fdo, out, fm.tp_h.tp_snaplen);
745 if (frame_count_max != 0) {
746 if (ctx->tx_packets >= frame_count_max) {
747 sigint = 1;
748 break;
753 out:
754 bug_on(gettimeofday(&end, NULL));
755 timersub(&end, &start, &diff);
757 bpf_release(&bpf_ops);
759 dissector_cleanup_all();
761 if (__pcap_io->prepare_close_pcap)
762 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_RD);
764 xfree(out);
766 fflush(stdout);
767 printf("\n");
768 printf("\r%12lu packets outgoing\n", ctx->tx_packets);
769 printf("\r%12lu packets truncated in file\n", trunced);
770 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
771 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
773 if (!strncmp("-", ctx->device_in, strlen("-")))
774 dup2(fd, fileno(stdin));
775 close(fd);
777 if (ctx->device_out) {
778 if (!strncmp("-", ctx->device_out, strlen("-")))
779 dup2(fdo, fileno(stdout));
780 close(fdo);
784 static void generate_multi_pcap_filename(struct ctx *ctx, char *fname, size_t size, time_t ftime)
786 if (ctx->overwrite_interval > 0) {
787 slprintf(fname, size, "%s/%s%010lu.pcap", ctx->device_out,
788 ctx->prefix, ctx->file_number);
790 ctx->file_number++;
792 if (ctx->file_number >= ctx->overwrite_interval)
793 ctx->file_number = 0;
794 } else {
795 slprintf(fname, size, "%s/%s%lu.pcap", ctx->device_out,
796 ctx->prefix, ftime);
800 static void finish_multi_pcap_file(struct ctx *ctx, int fd)
802 __pcap_io->fsync_pcap(fd);
804 if (__pcap_io->prepare_close_pcap)
805 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
807 close(fd);
809 memset(&itimer, 0, sizeof(itimer));
810 setitimer(ITIMER_REAL, &itimer, NULL);
813 static int next_multi_pcap_file(struct ctx *ctx, int fd)
815 int ret;
816 char fname[PATH_MAX] = {0};
817 time_t ftime;
819 __pcap_io->fsync_pcap(fd);
821 if (__pcap_io->prepare_close_pcap)
822 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
824 close(fd);
826 if (sighup_time > 0) {
827 ftime = (time_t)(start_time + sighup_time);
828 sighup_time = 0;
829 } else
830 ftime = time(NULL);
832 generate_multi_pcap_filename(ctx, fname, sizeof(fname), ftime);
834 fd = open_or_die_m(fname, O_RDWR | O_CREAT | O_TRUNC |
835 O_LARGEFILE, DEFFILEMODE);
837 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
838 if (ret)
839 panic("Error writing pcap header!\n");
841 if (__pcap_io->prepare_access_pcap) {
842 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
843 if (ret)
844 panic("Error prepare writing pcap!\n");
847 return fd;
850 static void reset_interval(struct ctx *ctx)
852 if (ctx->dump_mode == DUMP_INTERVAL_TIME) {
853 interval = ctx->dump_interval;
855 set_itimer_interval_value(&itimer, interval, 0);
856 setitimer(ITIMER_REAL, &itimer, NULL);
857 } else {
858 interval = 0;
862 static int begin_multi_pcap_file(struct ctx *ctx)
864 int fd, ret;
865 char fname[PATH_MAX] = {0};
867 bug_on(!__pcap_io);
869 if (ctx->device_out[strlen(ctx->device_out) - 1] == '/')
870 ctx->device_out[strlen(ctx->device_out) - 1] = 0;
872 generate_multi_pcap_filename(ctx, fname, sizeof(fname), time(NULL));
874 fd = open_or_die_m(fname, O_RDWR | O_CREAT | O_TRUNC |
875 O_LARGEFILE, DEFFILEMODE);
877 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
878 if (ret)
879 panic("Error writing pcap header!\n");
881 if (__pcap_io->prepare_access_pcap) {
882 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
883 if (ret)
884 panic("Error prepare writing pcap!\n");
887 reset_interval(ctx);
889 return fd;
892 static void finish_single_pcap_file(struct ctx *ctx, int fd)
894 __pcap_io->fsync_pcap(fd);
896 if (__pcap_io->prepare_close_pcap)
897 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
899 if (strncmp("-", ctx->device_out, strlen("-")))
900 close(fd);
901 else
902 dup2(fd, fileno(stdout));
905 static int begin_single_pcap_file(struct ctx *ctx)
907 int fd, ret;
908 char fname[PATH_MAX];
910 bug_on(!__pcap_io);
912 if (!strncmp("-", ctx->device_out, strlen("-"))) {
913 fd = dup_or_die(fileno(stdout));
914 close(fileno(stdout));
915 if (ctx->pcap == PCAP_OPS_MM)
916 ctx->pcap = PCAP_OPS_SG;
917 } else {
918 time_t t;
919 struct tm *ltm;
921 t = time(NULL);
922 if (t == -1)
923 panic("time() failed\n");
925 ltm = localtime(&t);
926 if (ltm == NULL)
927 panic("localtime() failed\n");
929 strftime(fname, sizeof(fname), ctx->device_out, ltm);
931 fd = open_or_die_m(fname,
932 O_RDWR | O_CREAT | O_TRUNC |
933 O_LARGEFILE, DEFFILEMODE);
936 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
937 if (ret)
938 panic("Error writing pcap header!\n");
940 if (__pcap_io->prepare_access_pcap) {
941 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
942 if (ret)
943 panic("Error prepare writing pcap!\n");
946 return fd;
949 static void update_pcap_next_dump(struct ctx *ctx, unsigned long snaplen,
950 int *fd, int sock, bool is_v3)
952 if (!dump_to_pcap(ctx))
953 return;
955 if (ctx->dump_mode == DUMP_INTERVAL_SIZE) {
956 interval += snaplen;
957 if (interval > ctx->dump_interval) {
958 next_dump = true;
959 interval = 0;
963 if (sighup) {
964 if (ctx->verbose)
965 printf("SIGHUP received, prematurely rotating pcap\n");
966 sighup = 0;
967 next_dump = true;
968 reset_interval(ctx);
971 if (next_dump) {
972 *fd = next_multi_pcap_file(ctx, *fd);
973 next_dump = false;
975 if (update_rx_stats(ctx, sock, is_v3))
976 return;
978 if (ctx->verbose && ctx->print_mode == PRINT_NONE)
979 printf(".(+%"PRIu64"/-%"PRIu64")",
980 ctx->pkts_recvd_last - ctx->pkts_drops_last,
981 ctx->pkts_drops_last);
985 #ifdef HAVE_TPACKET3
986 static void walk_t3_block(struct block_desc *pbd, struct ctx *ctx,
987 int sock, int *fd)
989 int num_pkts = pbd->h1.num_pkts, i;
990 struct tpacket3_hdr *hdr;
991 struct sockaddr_ll *sll;
993 hdr = (void *) ((uint8_t *) pbd + pbd->h1.offset_to_first_pkt);
994 sll = (void *) ((uint8_t *) hdr + TPACKET_ALIGN(sizeof(*hdr)));
996 for (i = 0; i < num_pkts && likely(sigint == 0); ++i) {
997 uint8_t *packet = ((uint8_t *) hdr + hdr->tp_mac);
998 pcap_pkthdr_t phdr;
1000 if (skip_packet(ctx, sll))
1001 goto next;
1003 ctx->pkts_seen++;
1005 if (dump_to_pcap(ctx)) {
1006 int ret;
1008 tpacket3_hdr_to_pcap_pkthdr(hdr, sll, &phdr, ctx->magic);
1010 ret = __pcap_io->write_pcap(*fd, &phdr, ctx->magic, packet,
1011 pcap_get_length(&phdr, ctx->magic));
1012 if (unlikely(ret != (int) pcap_get_total_length(&phdr, ctx->magic)))
1013 panic("Write error to pcap!\n");
1016 __show_frame_hdr(packet, hdr->tp_snaplen, ctx->link_type, sll,
1017 hdr, ctx->print_mode, true, ctx->pkts_seen);
1019 dissector_entry_point(packet, hdr->tp_snaplen, ctx->link_type,
1020 ctx->print_mode, sll);
1021 next:
1022 hdr = (void *) ((uint8_t *) hdr + hdr->tp_next_offset);
1023 sll = (void *) ((uint8_t *) hdr + TPACKET_ALIGN(sizeof(*hdr)));
1025 if (frame_count_max != 0) {
1026 if (unlikely(ctx->pkts_seen >= frame_count_max)) {
1027 sigint = 1;
1028 break;
1032 update_pcap_next_dump(ctx, hdr->tp_snaplen, fd, sock, true);
1035 #endif /* HAVE_TPACKET3 */
1037 static void recv_only_or_dump(struct ctx *ctx)
1039 short ifflags = 0;
1040 int sock, ifindex, fd = 0, ret;
1041 size_t size;
1042 unsigned int it = 0;
1043 struct ring rx_ring;
1044 struct pollfd rx_poll;
1045 struct sock_fprog bpf_ops;
1046 struct timeval start, end, diff;
1047 bool is_v3 = is_defined(HAVE_TPACKET3);
1049 sock = pf_socket_type(ctx->link_type);
1051 ifindex = device_ifindex(ctx->device_in);
1052 size = ring_size(ctx->device_in, ctx->reserve_size);
1054 enable_kernel_bpf_jit_compiler();
1056 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
1057 if (ctx->dump_bpf)
1058 bpf_dump_all(&bpf_ops);
1059 bpf_attach_to_sock(sock, &bpf_ops);
1061 if (ctx->hwtimestamp) {
1062 ret = set_sockopt_hwtimestamp(sock, ctx->device_in);
1063 if (ret == 0 && ctx->verbose)
1064 printf("HW timestamping enabled\n");
1067 ring_rx_setup(&rx_ring, sock, size, ifindex, &rx_poll, is_v3, true,
1068 ctx->verbose, ctx->fanout_group, ctx->fanout_type);
1070 dissector_init_all(ctx->print_mode);
1072 if (ctx->cpu >= 0 && ifindex > 0) {
1073 int irq = device_irq_number(ctx->device_in);
1074 device_set_irq_affinity(irq, ctx->cpu);
1076 if (ctx->verbose)
1077 printf("IRQ: %s:%d > CPU%d\n",
1078 ctx->device_in, irq, ctx->cpu);
1081 if (ctx->promiscuous)
1082 ifflags = device_enter_promiscuous_mode(ctx->device_in);
1084 if (dump_to_pcap(ctx) && __pcap_io->init_once_pcap)
1085 __pcap_io->init_once_pcap(true);
1087 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
1089 if (dump_to_pcap(ctx)) {
1090 struct stat stats;
1092 ret = stat(ctx->device_out, &stats);
1093 if (ret < 0)
1094 ctx->dump_dir = 0;
1095 else
1096 ctx->dump_dir = S_ISDIR(stats.st_mode);
1098 if (ctx->dump_dir)
1099 fd = begin_multi_pcap_file(ctx);
1100 else
1101 fd = begin_single_pcap_file(ctx);
1104 printf("Running! Hang up with ^C!\n\n");
1105 fflush(stdout);
1107 bug_on(gettimeofday(&start, NULL));
1109 while (likely(sigint == 0)) {
1110 #ifdef HAVE_TPACKET3
1111 struct block_desc *pbd;
1113 while (user_may_pull_from_rx_block((pbd = rx_ring.frames[it].iov_base))) {
1114 walk_t3_block(pbd, ctx, sock, &fd);
1116 kernel_may_pull_from_rx_block(pbd);
1117 it = (it + 1) % rx_ring.layout3.tp_block_nr;
1119 if (unlikely(sigint == 1))
1120 break;
1122 #else
1123 while (user_may_pull_from_rx(rx_ring.frames[it].iov_base)) {
1124 struct frame_map *hdr = rx_ring.frames[it].iov_base;
1125 uint8_t *packet = ((uint8_t *) hdr) + hdr->tp_h.tp_mac;
1126 pcap_pkthdr_t phdr;
1128 if (skip_packet(ctx, &hdr->s_ll))
1129 goto next;
1131 ctx->pkts_seen++;
1133 if (unlikely(ring_frame_size(&rx_ring) < hdr->tp_h.tp_snaplen)) {
1134 /* XXX: silently ignore for now. We used to
1135 * report them with dump_rx_stats() */
1136 goto next;
1139 if (dump_to_pcap(ctx)) {
1140 tpacket_hdr_to_pcap_pkthdr(&hdr->tp_h, &hdr->s_ll, &phdr, ctx->magic);
1142 ret = __pcap_io->write_pcap(fd, &phdr, ctx->magic, packet,
1143 pcap_get_length(&phdr, ctx->magic));
1144 if (unlikely(ret != (int) pcap_get_total_length(&phdr, ctx->magic)))
1145 panic("Write error to pcap!\n");
1148 show_frame_hdr(packet, hdr->tp_h.tp_snaplen,
1149 ctx->link_type, hdr, ctx->print_mode,
1150 ctx->pkts_seen);
1152 dissector_entry_point(packet, hdr->tp_h.tp_snaplen,
1153 ctx->link_type, ctx->print_mode,
1154 &hdr->s_ll);
1156 if (frame_count_max != 0) {
1157 if (unlikely(ctx->pkts_seen >= frame_count_max)) {
1158 sigint = 1;
1159 break;
1163 next:
1164 kernel_may_pull_from_rx(&hdr->tp_h);
1165 it = (it + 1) % rx_ring.layout.tp_frame_nr;
1167 if (unlikely(sigint == 1))
1168 break;
1170 update_pcap_next_dump(ctx, hdr->tp_h.tp_snaplen, &fd,
1171 sock, is_v3);
1173 #endif /* HAVE_TPACKET3 */
1175 ret = poll(&rx_poll, 1, -1);
1176 if (unlikely(ret < 0)) {
1177 if (errno != EINTR)
1178 panic("Poll failed!\n");
1182 bug_on(gettimeofday(&end, NULL));
1183 timersub(&end, &start, &diff);
1185 dump_rx_stats(ctx, sock, is_v3);
1186 printf("\r%12lu sec, %lu usec in total\n",
1187 diff.tv_sec, diff.tv_usec);
1189 bpf_release(&bpf_ops);
1190 dissector_cleanup_all();
1191 destroy_rx_ring(sock, &rx_ring);
1193 if (ctx->promiscuous)
1194 device_leave_promiscuous_mode(ctx->device_in, ifflags);
1196 if (ctx->rfraw)
1197 leave_rfmon_mac80211(ctx->device_in);
1199 if (dump_to_pcap(ctx)) {
1200 if (ctx->dump_dir)
1201 finish_multi_pcap_file(ctx, fd);
1202 else
1203 finish_single_pcap_file(ctx, fd);
1206 close(sock);
1209 static void init_ctx(struct ctx *ctx)
1211 memset(ctx, 0, sizeof(*ctx));
1213 ctx->uid = getuid();
1214 ctx->gid = getgid();
1216 ctx->cpu = -1;
1217 ctx->packet_type = -1;
1219 ctx->fanout_type = PACKET_FANOUT_ROLLOVER;
1221 ctx->magic = ORIGINAL_TCPDUMP_MAGIC;
1222 ctx->print_mode = PRINT_NORM;
1223 ctx->pcap = PCAP_OPS_SG;
1225 ctx->dump_mode = DUMP_INTERVAL_TIME;
1226 ctx->dump_interval = 60;
1228 ctx->promiscuous = true;
1229 ctx->randomize = false;
1230 ctx->hwtimestamp = true;
1233 static void destroy_ctx(struct ctx *ctx)
1235 free(ctx->device_in);
1236 free(ctx->device_out);
1237 free(ctx->device_trans);
1239 free(ctx->prefix);
1242 static void __noreturn help(void)
1244 printf("netsniff-ng %s, the packet sniffing beast\n", VERSION_STRING);
1245 puts("http://www.netsniff-ng.org\n\n"
1246 "Usage: netsniff-ng [options] [filter-expression]\n"
1247 "Options:\n"
1248 " -i|-d|--dev|--in <dev|pcap|-> Input source as netdev, pcap or pcap stdin\n"
1249 " -o|--out <dev|pcap|dir|cfg|-> Output sink as netdev, pcap, directory, trafgen, or stdout\n"
1250 " -C|--fanout-group <id> Join packet fanout group\n"
1251 " -K|--fanout-type <type> Apply fanout discipline: hash|lb|cpu|rnd|roll|qm\n"
1252 " -L|--fanout-opts <opts> Additional fanout options: defrag|roll\n"
1253 " -f|--filter <bpf-file|-|expr> Use BPF filter from bpfc file/stdin or tcpdump-like expression\n"
1254 " -t|--type <type> Filter for: host|broadcast|multicast|others|outgoing\n"
1255 " -F|--interval <size|time> Dump interval if -o is a dir: <num>KiB/MiB/GiB/s/sec/min/hrs\n"
1256 " -R|--rfraw Capture or inject raw 802.11 frames\n"
1257 " -n|--num <0|uint> Number of packets until exit (def: 0)\n"
1258 " -P|--prefix <name> Prefix for pcaps stored in directory\n"
1259 " -O|--overwrite <N> Limit the number of pcaps to N (file names use numbers 0 to N-1)\n"
1260 " -T|--magic <pcap-magic> Pcap magic number/pcap format to store, see -D\n"
1261 " -w|--cooked Use Linux \"cooked\" header instead of link header\n"
1262 " -D|--dump-pcap-types Dump pcap types and magic numbers and quit\n"
1263 " -B|--dump-bpf Dump generated BPF assembly\n"
1264 " -r|--rand Randomize packet forwarding order (dev->dev)\n"
1265 " -M|--no-promisc No promiscuous mode for netdev\n"
1266 " -A|--no-sock-mem Don't tune core socket memory\n"
1267 " -N|--no-hwtimestamp Disable hardware time stamping\n"
1268 " -m|--mmap Mmap(2) pcap file I/O, e.g. for replaying pcaps\n"
1269 " -G|--sg Scatter/gather pcap file I/O\n"
1270 " -c|--clrw Use slower read(2)/write(2) I/O\n"
1271 " -S|--ring-size <size> Specify ring size to: <num>KiB/MiB/GiB\n"
1272 " -k|--kernel-pull <uint> Kernel pull from user interval in us (def: 10us)\n"
1273 " -J|--jumbo-support Support replay/fwd 64KB Super Jumbo Frames (def: 2048B)\n"
1274 " -b|--bind-cpu <cpu> Bind to specific CPU\n"
1275 " -u|--user <userid> Drop privileges and change to userid\n"
1276 " -g|--group <groupid> Drop privileges and change to groupid\n"
1277 " -H|--prio-high Make this high priority process\n"
1278 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
1279 " -s|--silent Do not print captured packets\n"
1280 " -q|--less Print less-verbose packet information\n"
1281 " -X|--hex Print packet data in hex format\n"
1282 " -l|--ascii Print human-readable packet data\n"
1283 " -U|--update Update GeoIP databases\n"
1284 " -V|--verbose Be more verbose\n"
1285 " -v|--version Show version and exit\n"
1286 " -h|--help Guess what?!\n\n"
1287 "Examples:\n"
1288 " netsniff-ng --in eth0 --out dump.pcap -s -T 0xa1b2c3d4 --bind-cpu 0 tcp or udp\n"
1289 " netsniff-ng --in wlan0 --rfraw --out dump.pcap --silent --bind-cpu 0\n"
1290 " netsniff-ng --in dump.pcap --mmap --out eth0 -k1000 --silent --bind-cpu 0\n"
1291 " netsniff-ng --in dump.pcap --out dump.cfg --silent --bind-cpu 0\n"
1292 " netsniff-ng --in dump.pcap --out dump2.pcap --silent tcp\n"
1293 " netsniff-ng --in eth0 --out eth1 --silent --bind-cpu 0 -J --type host\n"
1294 " netsniff-ng --in eth1 --out /opt/probe/ -s -m --interval 100MiB -b 0\n"
1295 " netsniff-ng --in vlan0 --out dump.pcap -c -u `id -u bob` -g `id -g bob`\n"
1296 " netsniff-ng --in any --filter http.bpf --jumbo-support --ascii -V\n\n"
1297 "Note:\n"
1298 " For introducing bit errors, delays with random variation and more\n"
1299 " while replaying pcaps, make use of tc(8) with its disciplines (e.g. netem).\n");
1300 puts(copyright);
1301 die();
1304 static void __noreturn version(void)
1306 printf("netsniff-ng %s, Git id: %s\n", VERSION_LONG, GITVERSION);
1307 puts("the packet sniffing beast\n"
1308 "http://www.netsniff-ng.org\n");
1309 puts(copyright);
1310 die();
1313 int main(int argc, char **argv)
1315 char *ptr;
1316 int c, i, j, cpu_tmp, ops_touched = 0, vals[4] = {0};
1317 bool prio_high = false, setsockmem = true;
1318 void (*main_loop)(struct ctx *ctx) = NULL;
1319 struct ctx ctx;
1321 init_ctx(&ctx);
1322 start_time = time(NULL);
1323 srand(start_time);
1325 while ((c = getopt_long(argc, argv, short_options, long_options,
1326 NULL)) != EOF) {
1327 switch (c) {
1328 case 'd':
1329 case 'i':
1330 ctx.device_in = xstrdup(optarg);
1331 break;
1332 case 'o':
1333 ctx.device_out = xstrdup(optarg);
1334 break;
1335 case 'P':
1336 ctx.prefix = xstrdup(optarg);
1337 break;
1338 case 'O':
1339 ctx.overwrite_interval = strtoul(optarg, NULL, 0);
1340 break;
1341 case 'R':
1342 ctx.rfraw = 1;
1343 break;
1344 case 'r':
1345 ctx.randomize = true;
1346 break;
1347 case 'J':
1348 ctx.jumbo = true;
1349 break;
1350 case 'T':
1351 ctx.magic = (uint32_t) strtoul(optarg, NULL, 0);
1352 pcap_check_magic(ctx.magic);
1353 break;
1354 case 'f':
1355 ctx.filter = xstrdup(optarg);
1356 break;
1357 case 'M':
1358 ctx.promiscuous = false;
1359 break;
1360 case 'N':
1361 ctx.hwtimestamp = false;
1362 break;
1363 case 'A':
1364 setsockmem = false;
1365 break;
1366 case 'u':
1367 ctx.uid = strtoul(optarg, NULL, 0);
1368 ctx.enforce = true;
1369 break;
1370 case 'g':
1371 ctx.gid = strtoul(optarg, NULL, 0);
1372 ctx.enforce = true;
1373 break;
1374 case 'C':
1375 ctx.fanout_group = strtoul(optarg, NULL, 0);
1376 if (ctx.fanout_group == 0)
1377 panic("Non-zero fanout group id required!\n");
1378 break;
1379 case 'K':
1380 if (!strncmp(optarg, "hash", strlen("hash")))
1381 ctx.fanout_type = PACKET_FANOUT_HASH;
1382 else if (!strncmp(optarg, "lb", strlen("lb")) ||
1383 !strncmp(optarg, "rr", strlen("rr")))
1384 ctx.fanout_type = PACKET_FANOUT_LB;
1385 else if (!strncmp(optarg, "cpu", strlen("cpu")))
1386 ctx.fanout_type = PACKET_FANOUT_CPU;
1387 else if (!strncmp(optarg, "rnd", strlen("rnd")))
1388 ctx.fanout_type = PACKET_FANOUT_RND;
1389 else if (!strncmp(optarg, "roll", strlen("roll")))
1390 ctx.fanout_type = PACKET_FANOUT_ROLLOVER;
1391 else if (!strncmp(optarg, "qm", strlen("qm")))
1392 ctx.fanout_type = PACKET_FANOUT_QM;
1393 else
1394 panic("Unknown fanout type!\n");
1395 break;
1396 case 'L':
1397 if (!strncmp(optarg, "defrag", strlen("defrag")))
1398 ctx.fanout_type |= PACKET_FANOUT_FLAG_DEFRAG;
1399 else if (!strncmp(optarg, "roll", strlen("roll")))
1400 ctx.fanout_type |= PACKET_FANOUT_FLAG_ROLLOVER;
1401 else
1402 panic("Unknown fanout option!\n");
1403 break;
1404 case 't':
1405 if (!strncmp(optarg, "host", strlen("host")))
1406 ctx.packet_type = PACKET_HOST;
1407 else if (!strncmp(optarg, "broadcast", strlen("broadcast")))
1408 ctx.packet_type = PACKET_BROADCAST;
1409 else if (!strncmp(optarg, "multicast", strlen("multicast")))
1410 ctx.packet_type = PACKET_MULTICAST;
1411 else if (!strncmp(optarg, "others", strlen("others")))
1412 ctx.packet_type = PACKET_OTHERHOST;
1413 else if (!strncmp(optarg, "outgoing", strlen("outgoing")))
1414 ctx.packet_type = PACKET_OUTGOING;
1415 else
1416 ctx.packet_type = -1;
1417 break;
1418 case 'S':
1419 ptr = optarg;
1420 for (j = i = strlen(optarg); i > 0; --i) {
1421 if (!isdigit(optarg[j - i]))
1422 break;
1423 ptr++;
1426 if (!strncmp(ptr, "KiB", strlen("KiB")))
1427 ctx.reserve_size = 1 << 10;
1428 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1429 ctx.reserve_size = 1 << 20;
1430 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1431 ctx.reserve_size = 1 << 30;
1432 else
1433 panic("Syntax error in ring size param!\n");
1435 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1436 break;
1437 case 'b':
1438 cpu_tmp = strtol(optarg, NULL, 0);
1440 cpu_affinity(cpu_tmp);
1441 if (ctx.cpu != -2)
1442 ctx.cpu = cpu_tmp;
1443 break;
1444 case 'H':
1445 prio_high = true;
1446 break;
1447 case 'c':
1448 ctx.pcap = PCAP_OPS_RW;
1449 ops_touched = 1;
1450 break;
1451 case 'm':
1452 ctx.pcap = PCAP_OPS_MM;
1453 ops_touched = 1;
1454 break;
1455 case 'G':
1456 ctx.pcap = PCAP_OPS_SG;
1457 ops_touched = 1;
1458 break;
1459 case 'Q':
1460 ctx.cpu = -2;
1461 break;
1462 case 's':
1463 ctx.print_mode = PRINT_NONE;
1464 break;
1465 case 'q':
1466 ctx.print_mode = PRINT_LESS;
1467 break;
1468 case 'X':
1469 ctx.print_mode =
1470 (ctx.print_mode == PRINT_ASCII) ?
1471 PRINT_HEX_ASCII : PRINT_HEX;
1472 break;
1473 case 'l':
1474 ctx.print_mode =
1475 (ctx.print_mode == PRINT_HEX) ?
1476 PRINT_HEX_ASCII : PRINT_ASCII;
1477 break;
1478 case 'k':
1479 ctx.kpull = strtoul(optarg, NULL, 0);
1480 break;
1481 case 'n':
1482 frame_count_max = strtoul(optarg, NULL, 0);
1483 break;
1484 case 'F':
1485 ptr = optarg;
1486 for (j = i = strlen(optarg); i > 0; --i) {
1487 if (!isdigit(optarg[j - i]))
1488 break;
1489 ptr++;
1492 if (!strncmp(ptr, "KiB", strlen("KiB"))) {
1493 ctx.dump_interval = 1 << 10;
1494 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1495 } else if (!strncmp(ptr, "MiB", strlen("MiB"))) {
1496 ctx.dump_interval = 1 << 20;
1497 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1498 } else if (!strncmp(ptr, "GiB", strlen("GiB"))) {
1499 ctx.dump_interval = 1 << 30;
1500 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1501 } else if (!strncmp(ptr, "sec", strlen("sec"))) {
1502 ctx.dump_interval = 1;
1503 ctx.dump_mode = DUMP_INTERVAL_TIME;
1504 } else if (!strncmp(ptr, "min", strlen("min"))) {
1505 ctx.dump_interval = 60;
1506 ctx.dump_mode = DUMP_INTERVAL_TIME;
1507 } else if (!strncmp(ptr, "hrs", strlen("hrs"))) {
1508 ctx.dump_interval = 60 * 60;
1509 ctx.dump_mode = DUMP_INTERVAL_TIME;
1510 } else if (!strncmp(ptr, "s", strlen("s"))) {
1511 ctx.dump_interval = 1;
1512 ctx.dump_mode = DUMP_INTERVAL_TIME;
1513 } else {
1514 panic("Syntax error in time/size param!\n");
1517 ctx.dump_interval *= strtoul(optarg, NULL, 0);
1518 break;
1519 case 'V':
1520 ctx.verbose = true;
1521 break;
1522 case 'B':
1523 ctx.dump_bpf = true;
1524 break;
1525 case 'D':
1526 pcap_dump_type_features();
1527 die();
1528 break;
1529 case 'U':
1530 update_geoip();
1531 die();
1532 break;
1533 case 'w':
1534 ctx.link_type = LINKTYPE_LINUX_SLL;
1535 break;
1536 case 'v':
1537 version();
1538 break;
1539 case 'h':
1540 help();
1541 break;
1542 case '?':
1543 switch (optopt) {
1544 case 'd':
1545 case 'i':
1546 case 'o':
1547 case 'f':
1548 case 't':
1549 case 'P':
1550 case 'O':
1551 case 'F':
1552 case 'n':
1553 case 'S':
1554 case 'b':
1555 case 'k':
1556 case 'T':
1557 case 'u':
1558 case 'g':
1559 case 'e':
1560 panic("Option -%c requires an argument!\n",
1561 optopt);
1562 default:
1563 if (isprint(optopt))
1564 printf("Unknown option character `0x%X\'!\n", optopt);
1565 die();
1567 default:
1568 break;
1572 if (!ctx.filter && optind != argc)
1573 ctx.filter = argv2str(optind, argc, argv);
1575 if (!ctx.device_in)
1576 ctx.device_in = xstrdup("any");
1578 if (!strcmp(ctx.device_in, "any") || !strcmp(ctx.device_in, "lo"))
1579 ctx.lo_ifindex = device_ifindex("lo");
1581 if (!ctx.prefix)
1582 ctx.prefix = xstrdup("dump-");
1584 register_signal(SIGINT, signal_handler);
1585 register_signal(SIGQUIT, signal_handler);
1586 register_signal(SIGTERM, signal_handler);
1587 register_signal(SIGHUP, signal_handler);
1589 tprintf_init();
1591 if (prio_high) {
1592 set_proc_prio(-20);
1593 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1596 if (device_mtu(ctx.device_in) || !strncmp("any", ctx.device_in, strlen(ctx.device_in))) {
1597 if (ctx.rfraw)
1598 setup_rfmon_mac80211_dev(&ctx, &ctx.device_in);
1600 if (!ctx.link_type)
1601 ctx.link_type = pcap_dev_to_linktype(ctx.device_in);
1602 if (link_has_sll_hdr(ctx.link_type)) {
1603 switch (ctx.magic) {
1604 case ORIGINAL_TCPDUMP_MAGIC:
1605 ctx.magic = ORIGINAL_TCPDUMP_MAGIC_LL;
1606 break;
1607 case NSEC_TCPDUMP_MAGIC:
1608 ctx.magic = NSEC_TCPDUMP_MAGIC_LL;
1609 break;
1610 case ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC):
1611 ctx.magic = ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC_LL);
1612 break;
1613 case ___constant_swab32(NSEC_TCPDUMP_MAGIC):
1614 ctx.magic = ___constant_swab32(NSEC_TCPDUMP_MAGIC_LL);
1615 break;
1620 if (!ctx.device_out) {
1621 ctx.dump = 0;
1622 main_loop = recv_only_or_dump;
1623 } else if (device_mtu(ctx.device_out)) {
1624 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1625 main_loop = receive_to_xmit;
1626 } else {
1627 ctx.dump = 1;
1628 register_signal_f(SIGALRM, timer_next_dump, SA_SIGINFO);
1629 main_loop = recv_only_or_dump;
1630 if (!ops_touched)
1631 ctx.pcap = PCAP_OPS_SG;
1633 } else {
1634 if (ctx.device_out && device_mtu(ctx.device_out)) {
1635 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1636 main_loop = pcap_to_xmit;
1637 if (!ops_touched)
1638 ctx.pcap = PCAP_OPS_MM;
1639 } else {
1640 setsockmem = false;
1641 main_loop = read_pcap;
1642 if (!ops_touched)
1643 ctx.pcap = PCAP_OPS_SG;
1647 bug_on(!main_loop);
1649 init_geoip(0);
1650 if (setsockmem)
1651 set_system_socket_memory(vals, array_size(vals));
1652 if (!ctx.enforce)
1653 xlockme();
1655 if (ctx.verbose)
1656 printf("pcap file I/O method: %s\n", pcap_ops_group_to_str[ctx.pcap]);
1658 main_loop(&ctx);
1660 if (!ctx.enforce)
1661 xunlockme();
1662 if (setsockmem)
1663 reset_system_socket_memory(vals, array_size(vals));
1664 destroy_geoip();
1666 device_restore_irq_affinity_list();
1667 tprintf_cleanup();
1669 destroy_ctx(&ctx);
1670 return 0;