netsniff-ng: implement rotating capture files
[netsniff-ng.git] / netsniff-ng.c
blob1a74d91528cf0a7cbebced7ad853f19736ac6344
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 = "Please report bugs to <netsniff-ng@googlegroups.com>\n"
125 "Copyright (C) 2009-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
126 "Copyright (C) 2009-2012 Emmanuel Roullit <emmanuel.roullit@gmail.com>\n"
127 "Copyright (C) 2012 Markus Amend <markus@netsniff-ng.org>\n"
128 "Swiss federal institute of technology (ETH Zurich)\n"
129 "License: GNU GPL version 2.0\n"
130 "This is free software: you are free to change and redistribute it.\n"
131 "There is NO WARRANTY, to the extent permitted by law.";
133 static int tx_sock;
134 static struct itimerval itimer;
135 static unsigned long frame_count_max = 0, interval = TX_KERNEL_PULL_INT;
136 static time_t start_time;
138 #define __pcap_io pcap_ops[ctx->pcap]
140 static void signal_handler(int number)
142 switch (number) {
143 case SIGINT:
144 case SIGQUIT:
145 case SIGTERM:
146 sigint = 1;
147 break;
148 case SIGHUP:
149 sighup = 1;
150 sighup_time = (sig_atomic_t)(time(NULL) - start_time);
151 break;
152 default:
153 break;
157 static void timer_elapsed(int unused __maybe_unused)
159 int ret;
161 set_itimer_interval_value(&itimer, 0, interval);
163 ret = pull_and_flush_tx_ring(tx_sock);
164 if (unlikely(ret < 0)) {
165 /* We could hit EBADF if the socket has been closed before
166 * the timer was triggered.
168 if (errno != EBADF && errno != ENOBUFS)
169 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
172 setitimer(ITIMER_REAL, &itimer, NULL);
175 static void timer_purge(void)
177 int ret;
179 ret = pull_and_flush_tx_ring_wait(tx_sock);
180 if (unlikely(ret < 0)) {
181 if (errno != EBADF && errno != ENOBUFS)
182 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
185 set_itimer_interval_value(&itimer, 0, 0);
186 setitimer(ITIMER_REAL, &itimer, NULL);
189 static void timer_next_dump(int unused __maybe_unused)
191 set_itimer_interval_value(&itimer, interval, 0);
192 next_dump = true;
193 setitimer(ITIMER_REAL, &itimer, NULL);
196 static inline bool dump_to_pcap(struct ctx *ctx)
198 return ctx->dump;
201 static void on_panic_del_rfmon(void *arg)
203 leave_rfmon_mac80211(arg);
206 static inline void setup_rfmon_mac80211_dev(struct ctx *ctx, char **rfmon_dev)
208 ctx->device_trans = xstrdup(*rfmon_dev);
209 xfree(*rfmon_dev);
211 enter_rfmon_mac80211(ctx->device_trans, rfmon_dev);
212 panic_handler_add(on_panic_del_rfmon, *rfmon_dev);
215 static int update_rx_stats(struct ctx *ctx, int sock, bool is_v3)
217 uint64_t packets, drops;
218 int ret;
220 ret = get_rx_net_stats(sock, &packets, &drops, is_v3);
221 if (ret)
222 return ret;
224 drops += ctx->pkts_skipd_last;
225 ctx->pkts_seen += ctx->pkts_skipd_last;
226 ctx->pkts_recvd += packets;
227 ctx->pkts_drops += drops;
228 ctx->pkts_recvd_last = packets;
229 ctx->pkts_drops_last = drops;
230 ctx->pkts_skipd_last = 0;
232 return 0;
235 static void dump_rx_stats(struct ctx *ctx, int sock, bool is_v3)
237 if (update_rx_stats(ctx, sock, is_v3))
238 return;
240 printf("\r%12"PRIu64" packets incoming (%"PRIu64" unread on exit)\n",
241 is_v3 ? ctx->pkts_seen : ctx->pkts_recvd,
242 is_v3 ? ctx->pkts_recvd - ctx->pkts_seen : 0);
243 printf("\r%12"PRIu64" packets passed filter\n",
244 ctx->pkts_recvd - ctx->pkts_drops);
245 printf("\r%12"PRIu64" packets failed filter (out of space)\n",
246 ctx->pkts_drops);
248 if (ctx->pkts_recvd > 0)
249 printf("\r%12.4lf%% packet droprate\n",
250 (1.0 * ctx->pkts_drops / ctx->pkts_recvd) * 100.0);
253 static void pcap_to_xmit(struct ctx *ctx)
255 uint8_t *out = NULL;
256 int ifindex, fd = 0, ret;
257 size_t size;
258 unsigned int it = 0;
259 unsigned long trunced = 0;
260 struct ring tx_ring;
261 struct frame_map *hdr;
262 struct sock_fprog bpf_ops;
263 struct timeval start, end, diff;
264 pcap_pkthdr_t phdr;
266 if (!device_up_and_running(ctx->device_out) && !ctx->rfraw)
267 panic("Device not up and running!\n");
269 bug_on(!__pcap_io);
271 tx_sock = pf_socket();
273 if (!strncmp("-", ctx->device_in, strlen("-"))) {
274 fd = dup_or_die(fileno(stdin));
275 close(fileno(stdin));
276 if (ctx->pcap == PCAP_OPS_MM)
277 ctx->pcap = PCAP_OPS_SG;
278 } else {
279 fd = open_or_die(ctx->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
282 if (__pcap_io->init_once_pcap)
283 __pcap_io->init_once_pcap(true);
285 ret = __pcap_io->pull_fhdr_pcap(fd, &ctx->magic, &ctx->link_type);
286 if (ret)
287 panic("Error reading pcap header!\n");
289 if (__pcap_io->prepare_access_pcap) {
290 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_RD, ctx->jumbo);
291 if (ret)
292 panic("Error prepare reading pcap!\n");
295 if (ctx->rfraw) {
296 setup_rfmon_mac80211_dev(ctx, &ctx->device_out);
298 if (ctx->link_type != LINKTYPE_IEEE802_11 &&
299 ctx->link_type != LINKTYPE_IEEE802_11_RADIOTAP)
300 panic("Wrong linktype of pcap!\n");
303 ifindex = device_ifindex(ctx->device_out);
304 size = ring_size(ctx->device_out, ctx->reserve_size);
306 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
307 if (ctx->dump_bpf)
308 bpf_dump_all(&bpf_ops);
310 ring_tx_setup(&tx_ring, tx_sock, size, ifindex, ctx->jumbo, ctx->verbose);
312 dissector_init_all(ctx->print_mode);
314 if (ctx->cpu >= 0 && ifindex > 0) {
315 int irq = device_irq_number(ctx->device_out);
316 device_set_irq_affinity(irq, ctx->cpu);
318 if (ctx->verbose)
319 printf("IRQ: %s:%d > CPU%d\n",
320 ctx->device_out, irq, ctx->cpu);
323 if (ctx->kpull)
324 interval = ctx->kpull;
326 set_itimer_interval_value(&itimer, 0, interval);
327 setitimer(ITIMER_REAL, &itimer, NULL);
329 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
331 printf("Running! Hang up with ^C!\n\n");
332 fflush(stdout);
334 bug_on(gettimeofday(&start, NULL));
336 while (likely(sigint == 0)) {
337 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
338 hdr = tx_ring.frames[it].iov_base;
339 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
341 do {
342 ret = __pcap_io->read_pcap(fd, &phdr, ctx->magic, out,
343 ring_frame_size(&tx_ring));
344 if (unlikely(ret <= 0))
345 goto out;
347 if (ring_frame_size(&tx_ring) <
348 pcap_get_length(&phdr, ctx->magic)) {
349 pcap_set_length(&phdr, ctx->magic,
350 ring_frame_size(&tx_ring));
351 trunced++;
353 } while (ctx->filter &&
354 !bpf_run_filter(&bpf_ops, out,
355 pcap_get_length(&phdr, ctx->magic)));
357 pcap_pkthdr_to_tpacket_hdr(&phdr, ctx->magic, &hdr->tp_h, NULL);
359 ctx->tx_bytes += hdr->tp_h.tp_len;;
360 ctx->tx_packets++;
362 show_frame_hdr(out, hdr->tp_h.tp_snaplen,
363 ctx->link_type, hdr, ctx->print_mode,
364 ctx->tx_packets);
366 dissector_entry_point(out, hdr->tp_h.tp_snaplen,
367 ctx->link_type, ctx->print_mode,
368 &hdr->s_ll);
370 kernel_may_pull_from_tx(&hdr->tp_h);
372 it++;
373 if (it >= tx_ring.layout.tp_frame_nr)
374 it = 0;
376 if (unlikely(sigint == 1))
377 break;
379 if (frame_count_max != 0) {
380 if (ctx->tx_packets >= frame_count_max) {
381 sigint = 1;
382 break;
388 out:
389 bug_on(gettimeofday(&end, NULL));
390 timersub(&end, &start, &diff);
392 timer_purge();
394 bpf_release(&bpf_ops);
396 dissector_cleanup_all();
397 destroy_tx_ring(tx_sock, &tx_ring);
399 if (ctx->rfraw)
400 leave_rfmon_mac80211(ctx->device_out);
402 if (__pcap_io->prepare_close_pcap)
403 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_RD);
405 if (!strncmp("-", ctx->device_in, strlen("-")))
406 dup2(fd, fileno(stdin));
407 close(fd);
409 close(tx_sock);
411 fflush(stdout);
412 printf("\n");
413 printf("\r%12lu packets outgoing\n", ctx->tx_packets);
414 printf("\r%12lu packets truncated in file\n", trunced);
415 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
416 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
419 static inline bool __skip_packet(struct ctx *ctx, struct sockaddr_ll *sll)
421 if (ctx->packet_type != -1)
422 return ctx->packet_type != sll->sll_pkttype;
424 /* when receving from the loopback device, each packet is seen twice,
425 * so drop the outgoing ones to avoid duplicates
427 return (sll->sll_ifindex == ctx->lo_ifindex) &&
428 (sll->sll_pkttype == PACKET_OUTGOING);
431 static inline bool skip_packet(struct ctx *ctx, struct sockaddr_ll *sll)
433 bool skip = __skip_packet(ctx, sll);
435 if (skip)
436 ctx->pkts_skipd_last++;
437 return skip;
440 static void receive_to_xmit(struct ctx *ctx)
442 short ifflags = 0;
443 uint8_t *in, *out;
444 int rx_sock, ifindex_in, ifindex_out, ret;
445 size_t size_in, size_out;
446 unsigned int it_in = 0, it_out = 0;
447 struct frame_map *hdr_in, *hdr_out;
448 struct ring tx_ring, rx_ring;
449 struct pollfd rx_poll;
450 struct sock_fprog bpf_ops;
452 if (!strncmp(ctx->device_in, ctx->device_out, IFNAMSIZ))
453 panic("Ingress/egress devices must be different!\n");
454 if (!device_up_and_running(ctx->device_out))
455 panic("Egress device not up and running!\n");
457 rx_sock = pf_socket();
458 tx_sock = pf_socket();
460 ifindex_in = device_ifindex(ctx->device_in);
461 ifindex_out = device_ifindex(ctx->device_out);
463 size_in = ring_size(ctx->device_in, ctx->reserve_size);
464 size_out = ring_size(ctx->device_out, ctx->reserve_size);
466 enable_kernel_bpf_jit_compiler();
468 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
469 if (ctx->dump_bpf)
470 bpf_dump_all(&bpf_ops);
471 bpf_attach_to_sock(rx_sock, &bpf_ops);
473 ring_rx_setup(&rx_ring, rx_sock, size_in, ifindex_in, &rx_poll, false, ctx->jumbo,
474 ctx->verbose, ctx->fanout_group, ctx->fanout_type);
475 ring_tx_setup(&tx_ring, tx_sock, size_out, ifindex_out, ctx->jumbo, ctx->verbose);
477 dissector_init_all(ctx->print_mode);
479 if (ctx->promiscuous)
480 ifflags = device_enter_promiscuous_mode(ctx->device_in);
482 if (ctx->kpull)
483 interval = ctx->kpull;
485 set_itimer_interval_value(&itimer, 0, interval);
486 setitimer(ITIMER_REAL, &itimer, NULL);
488 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
490 printf("Running! Hang up with ^C!\n\n");
491 fflush(stdout);
493 while (likely(sigint == 0)) {
494 while (user_may_pull_from_rx(rx_ring.frames[it_in].iov_base)) {
495 hdr_in = rx_ring.frames[it_in].iov_base;
496 in = ((uint8_t *) hdr_in) + hdr_in->tp_h.tp_mac;
498 if (skip_packet(ctx, &hdr_in->s_ll))
499 goto next;
501 ctx->pkts_seen++;
503 hdr_out = tx_ring.frames[it_out].iov_base;
504 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
506 while (!user_may_pull_from_tx(tx_ring.frames[it_out].iov_base) &&
507 likely(!sigint)) {
508 if (ctx->randomize)
509 next_rnd_slot(&it_out, &tx_ring);
510 else {
511 it_out++;
512 if (it_out >= tx_ring.layout.tp_frame_nr)
513 it_out = 0;
516 hdr_out = tx_ring.frames[it_out].iov_base;
517 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
520 tpacket_hdr_clone(&hdr_out->tp_h, &hdr_in->tp_h);
521 memcpy(out, in, hdr_in->tp_h.tp_len);
523 kernel_may_pull_from_tx(&hdr_out->tp_h);
524 if (ctx->randomize)
525 next_rnd_slot(&it_out, &tx_ring);
526 else {
527 it_out++;
528 if (it_out >= tx_ring.layout.tp_frame_nr)
529 it_out = 0;
532 show_frame_hdr(in, hdr_in->tp_h.tp_snaplen,
533 ctx->link_type, hdr_in, ctx->print_mode,
534 ctx->pkts_seen);
536 dissector_entry_point(in, hdr_in->tp_h.tp_snaplen,
537 ctx->link_type, ctx->print_mode,
538 &hdr_in->s_ll);
540 if (frame_count_max != 0) {
541 if (ctx->pkts_seen >= frame_count_max) {
542 sigint = 1;
543 break;
547 next:
548 kernel_may_pull_from_rx(&hdr_in->tp_h);
550 it_in++;
551 if (it_in >= rx_ring.layout.tp_frame_nr)
552 it_in = 0;
554 if (unlikely(sigint == 1))
555 goto out;
558 ret = poll(&rx_poll, 1, -1);
559 if (unlikely(ret < 0)) {
560 if (errno != EINTR)
561 panic("Poll failed!\n");
565 out:
566 timer_purge();
568 dump_rx_stats(ctx, rx_sock, false);
570 bpf_release(&bpf_ops);
572 dissector_cleanup_all();
574 destroy_tx_ring(tx_sock, &tx_ring);
575 destroy_rx_ring(rx_sock, &rx_ring);
577 if (ctx->promiscuous)
578 device_leave_promiscuous_mode(ctx->device_in, ifflags);
580 close(tx_sock);
581 close(rx_sock);
584 static void translate_pcap_to_txf(int fdo, uint8_t *out, size_t len)
586 size_t bytes_done = 0;
587 char bout[80];
589 slprintf(bout, sizeof(bout), "{\n ");
590 write_or_die(fdo, bout, strlen(bout));
592 while (bytes_done < len) {
593 slprintf(bout, sizeof(bout), "0x%02x,", out[bytes_done]);
594 write_or_die(fdo, bout, strlen(bout));
596 bytes_done++;
598 if (bytes_done % 10 == 0) {
599 slprintf(bout, sizeof(bout), "\n");
600 write_or_die(fdo, bout, strlen(bout));
602 if (bytes_done < len) {
603 slprintf(bout, sizeof(bout), " ");
604 write_or_die(fdo, bout, strlen(bout));
606 } else if (bytes_done < len) {
607 slprintf(bout, sizeof(bout), " ");
608 write_or_die(fdo, bout, strlen(bout));
611 if (bytes_done % 10 != 0) {
612 slprintf(bout, sizeof(bout), "\n");
613 write_or_die(fdo, bout, strlen(bout));
616 slprintf(bout, sizeof(bout), "}\n\n");
617 write_or_die(fdo, bout, strlen(bout));
620 static void read_pcap(struct ctx *ctx)
622 uint8_t *out;
623 int ret, fd, fdo = 0;
624 unsigned long trunced = 0;
625 size_t out_len;
626 pcap_pkthdr_t phdr;
627 struct sock_fprog bpf_ops;
628 struct frame_map fm;
629 struct timeval start, end, diff;
630 bool is_out_pcap = ctx->device_out && strstr(ctx->device_out, ".pcap");
631 const struct pcap_file_ops *pcap_out_ops = pcap_ops[PCAP_OPS_RW];
633 bug_on(!__pcap_io);
635 if (!strncmp("-", ctx->device_in, strlen("-"))) {
636 fd = dup_or_die(fileno(stdin));
637 close(fileno(stdin));
638 if (ctx->pcap == PCAP_OPS_MM)
639 ctx->pcap = PCAP_OPS_SG;
640 } else {
641 /* O_NOATIME requires privileges, in case we don't have
642 * them, retry without them at a minor cost of updating
643 * atime in case the fs has been mounted as such.
645 fd = open(ctx->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
646 if (fd < 0 && errno == EPERM)
647 fd = open_or_die(ctx->device_in, O_RDONLY | O_LARGEFILE);
648 if (fd < 0)
649 panic("Cannot open file %s! %s.\n", ctx->device_in,
650 strerror(errno));
653 if (__pcap_io->init_once_pcap)
654 __pcap_io->init_once_pcap(false);
656 ret = __pcap_io->pull_fhdr_pcap(fd, &ctx->magic, &ctx->link_type);
657 if (ret)
658 panic("Error reading pcap header!\n");
660 if (__pcap_io->prepare_access_pcap) {
661 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_RD, ctx->jumbo);
662 if (ret)
663 panic("Error prepare reading pcap!\n");
666 memset(&fm, 0, sizeof(fm));
668 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
669 if (ctx->dump_bpf)
670 bpf_dump_all(&bpf_ops);
672 dissector_init_all(ctx->print_mode);
674 out_len = round_up(1024 * 1024, RUNTIME_PAGE_SIZE);
675 out = xmalloc_aligned(out_len, CO_CACHE_LINE_SIZE);
677 if (ctx->device_out) {
678 if (!strncmp("-", ctx->device_out, strlen("-"))) {
679 fdo = dup_or_die(fileno(stdout));
680 close(fileno(stdout));
681 } else {
682 fdo = open_or_die_m(ctx->device_out, O_RDWR | O_CREAT |
683 O_TRUNC | O_LARGEFILE, DEFFILEMODE);
687 if (is_out_pcap) {
688 ret = pcap_out_ops->push_fhdr_pcap(fdo, ctx->magic,
689 ctx->link_type);
690 if (ret)
691 panic("Error writing pcap header!\n");
694 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
696 printf("Running! Hang up with ^C!\n\n");
697 fflush(stdout);
699 bug_on(gettimeofday(&start, NULL));
701 while (likely(sigint == 0)) {
702 do {
703 ret = __pcap_io->read_pcap(fd, &phdr, ctx->magic,
704 out, out_len);
705 if (unlikely(ret < 0))
706 goto out;
708 if (unlikely(pcap_get_length(&phdr, ctx->magic) == 0)) {
709 trunced++;
710 continue;
713 if (unlikely(pcap_get_length(&phdr, ctx->magic) > out_len)) {
714 pcap_set_length(&phdr, ctx->magic, out_len);
715 trunced++;
717 } while (ctx->filter &&
718 !bpf_run_filter(&bpf_ops, out,
719 pcap_get_length(&phdr, ctx->magic)));
721 pcap_pkthdr_to_tpacket_hdr(&phdr, ctx->magic, &fm.tp_h, &fm.s_ll);
723 ctx->tx_bytes += fm.tp_h.tp_len;
724 ctx->tx_packets++;
726 show_frame_hdr(out, fm.tp_h.tp_snaplen, ctx->link_type, &fm,
727 ctx->print_mode, ctx->tx_packets);
729 dissector_entry_point(out, fm.tp_h.tp_snaplen,
730 ctx->link_type, ctx->print_mode,
731 &fm.s_ll);
733 if (is_out_pcap) {
734 size_t pcap_len = pcap_get_length(&phdr, ctx->magic);
735 int wlen = pcap_out_ops->write_pcap(fdo, &phdr,
736 ctx->magic, out,
737 pcap_len);
738 if (unlikely(wlen != (int)pcap_get_total_length(&phdr, ctx->magic)))
739 panic("Error writing to pcap!\n");
740 } else if (ctx->device_out) {
741 translate_pcap_to_txf(fdo, out, fm.tp_h.tp_snaplen);
744 if (frame_count_max != 0) {
745 if (ctx->tx_packets >= frame_count_max) {
746 sigint = 1;
747 break;
752 out:
753 bug_on(gettimeofday(&end, NULL));
754 timersub(&end, &start, &diff);
756 bpf_release(&bpf_ops);
758 dissector_cleanup_all();
760 if (__pcap_io->prepare_close_pcap)
761 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_RD);
763 xfree(out);
765 fflush(stdout);
766 printf("\n");
767 printf("\r%12lu packets outgoing\n", ctx->tx_packets);
768 printf("\r%12lu packets truncated in file\n", trunced);
769 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
770 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
772 if (!strncmp("-", ctx->device_in, strlen("-")))
773 dup2(fd, fileno(stdin));
774 close(fd);
776 if (ctx->device_out) {
777 if (!strncmp("-", ctx->device_out, strlen("-")))
778 dup2(fdo, fileno(stdout));
779 close(fdo);
783 static void generate_multi_pcap_filename(struct ctx *ctx, char *fname, size_t size, time_t ftime)
785 if (ctx->overwrite_interval > 0) {
786 slprintf(fname, size, "%s/%s%010lu.pcap", ctx->device_out,
787 ctx->prefix ? : "dump-", ctx->file_number);
789 ctx->file_number++;
791 if (ctx->file_number >= ctx->overwrite_interval)
792 ctx->file_number = 0;
793 } else {
794 slprintf(fname, size, "%s/%s%lu.pcap", ctx->device_out,
795 ctx->prefix ? : "dump-", ftime);
799 static void finish_multi_pcap_file(struct ctx *ctx, int fd)
801 __pcap_io->fsync_pcap(fd);
803 if (__pcap_io->prepare_close_pcap)
804 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
806 close(fd);
808 memset(&itimer, 0, sizeof(itimer));
809 setitimer(ITIMER_REAL, &itimer, NULL);
812 static int next_multi_pcap_file(struct ctx *ctx, int fd)
814 int ret;
815 char fname[PATH_MAX] = {0};
816 time_t ftime;
818 __pcap_io->fsync_pcap(fd);
820 if (__pcap_io->prepare_close_pcap)
821 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
823 close(fd);
825 if (sighup_time > 0) {
826 ftime = (time_t)(start_time + sighup_time);
827 sighup_time = 0;
828 } else
829 ftime = time(NULL);
831 generate_multi_pcap_filename(ctx, fname, sizeof(fname), ftime);
833 fd = open_or_die_m(fname, O_RDWR | O_CREAT | O_TRUNC |
834 O_LARGEFILE, DEFFILEMODE);
836 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
837 if (ret)
838 panic("Error writing pcap header!\n");
840 if (__pcap_io->prepare_access_pcap) {
841 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
842 if (ret)
843 panic("Error prepare writing pcap!\n");
846 return fd;
849 static void reset_interval(struct ctx *ctx)
851 if (ctx->dump_mode == DUMP_INTERVAL_TIME) {
852 interval = ctx->dump_interval;
854 set_itimer_interval_value(&itimer, interval, 0);
855 setitimer(ITIMER_REAL, &itimer, NULL);
856 } else {
857 interval = 0;
861 static int begin_multi_pcap_file(struct ctx *ctx)
863 int fd, ret;
864 char fname[PATH_MAX] = {0};
866 bug_on(!__pcap_io);
868 if (ctx->device_out[strlen(ctx->device_out) - 1] == '/')
869 ctx->device_out[strlen(ctx->device_out) - 1] = 0;
871 generate_multi_pcap_filename(ctx, fname, sizeof(fname), time(NULL));
873 fd = open_or_die_m(fname, O_RDWR | O_CREAT | O_TRUNC |
874 O_LARGEFILE, DEFFILEMODE);
876 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
877 if (ret)
878 panic("Error writing pcap header!\n");
880 if (__pcap_io->prepare_access_pcap) {
881 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
882 if (ret)
883 panic("Error prepare writing pcap!\n");
886 reset_interval(ctx);
888 return fd;
891 static void finish_single_pcap_file(struct ctx *ctx, int fd)
893 __pcap_io->fsync_pcap(fd);
895 if (__pcap_io->prepare_close_pcap)
896 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
898 if (strncmp("-", ctx->device_out, strlen("-")))
899 close(fd);
900 else
901 dup2(fd, fileno(stdout));
904 static int begin_single_pcap_file(struct ctx *ctx)
906 int fd, ret;
907 char fname[PATH_MAX];
909 bug_on(!__pcap_io);
911 if (!strncmp("-", ctx->device_out, strlen("-"))) {
912 fd = dup_or_die(fileno(stdout));
913 close(fileno(stdout));
914 if (ctx->pcap == PCAP_OPS_MM)
915 ctx->pcap = PCAP_OPS_SG;
916 } else {
917 time_t t;
918 struct tm *ltm;
920 t = time(NULL);
921 if (t == -1)
922 panic("time() failed\n");
924 ltm = localtime(&t);
925 if (ltm == NULL)
926 panic("localtime() failed\n");
928 strftime(fname, sizeof(fname), ctx->device_out, ltm);
930 fd = open_or_die_m(fname,
931 O_RDWR | O_CREAT | O_TRUNC |
932 O_LARGEFILE, DEFFILEMODE);
935 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
936 if (ret)
937 panic("Error writing pcap header!\n");
939 if (__pcap_io->prepare_access_pcap) {
940 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
941 if (ret)
942 panic("Error prepare writing pcap!\n");
945 return fd;
948 static void update_pcap_next_dump(struct ctx *ctx, unsigned long snaplen,
949 int *fd, int sock, bool is_v3)
951 if (!dump_to_pcap(ctx))
952 return;
954 if (ctx->dump_mode == DUMP_INTERVAL_SIZE) {
955 interval += snaplen;
956 if (interval > ctx->dump_interval) {
957 next_dump = true;
958 interval = 0;
962 if (sighup) {
963 if (ctx->verbose)
964 printf("SIGHUP received, prematurely rotating pcap\n");
965 sighup = 0;
966 next_dump = true;
967 reset_interval(ctx);
970 if (next_dump) {
971 *fd = next_multi_pcap_file(ctx, *fd);
972 next_dump = false;
974 if (update_rx_stats(ctx, sock, is_v3))
975 return;
977 if (ctx->verbose && ctx->print_mode == PRINT_NONE)
978 printf(".(+%"PRIu64"/-%"PRIu64")",
979 ctx->pkts_recvd_last - ctx->pkts_drops_last,
980 ctx->pkts_drops_last);
984 #ifdef HAVE_TPACKET3
985 static void walk_t3_block(struct block_desc *pbd, struct ctx *ctx,
986 int sock, int *fd)
988 int num_pkts = pbd->h1.num_pkts, i;
989 struct tpacket3_hdr *hdr;
990 struct sockaddr_ll *sll;
992 hdr = (void *) ((uint8_t *) pbd + pbd->h1.offset_to_first_pkt);
993 sll = (void *) ((uint8_t *) hdr + TPACKET_ALIGN(sizeof(*hdr)));
995 for (i = 0; i < num_pkts && likely(sigint == 0); ++i) {
996 uint8_t *packet = ((uint8_t *) hdr + hdr->tp_mac);
997 pcap_pkthdr_t phdr;
999 if (skip_packet(ctx, sll))
1000 goto next;
1002 ctx->pkts_seen++;
1004 if (dump_to_pcap(ctx)) {
1005 int ret;
1007 tpacket3_hdr_to_pcap_pkthdr(hdr, sll, &phdr, ctx->magic);
1009 ret = __pcap_io->write_pcap(*fd, &phdr, ctx->magic, packet,
1010 pcap_get_length(&phdr, ctx->magic));
1011 if (unlikely(ret != (int) pcap_get_total_length(&phdr, ctx->magic)))
1012 panic("Write error to pcap!\n");
1015 __show_frame_hdr(packet, hdr->tp_snaplen, ctx->link_type, sll,
1016 hdr, ctx->print_mode, true, ctx->pkts_seen);
1018 dissector_entry_point(packet, hdr->tp_snaplen, ctx->link_type,
1019 ctx->print_mode, sll);
1020 next:
1021 hdr = (void *) ((uint8_t *) hdr + hdr->tp_next_offset);
1022 sll = (void *) ((uint8_t *) hdr + TPACKET_ALIGN(sizeof(*hdr)));
1024 if (frame_count_max != 0) {
1025 if (unlikely(ctx->pkts_seen >= frame_count_max)) {
1026 sigint = 1;
1027 break;
1031 update_pcap_next_dump(ctx, hdr->tp_snaplen, fd, sock, true);
1034 #endif /* HAVE_TPACKET3 */
1036 static void recv_only_or_dump(struct ctx *ctx)
1038 short ifflags = 0;
1039 int sock, ifindex, fd = 0, ret;
1040 size_t size;
1041 unsigned int it = 0;
1042 struct ring rx_ring;
1043 struct pollfd rx_poll;
1044 struct sock_fprog bpf_ops;
1045 struct timeval start, end, diff;
1046 bool is_v3 = is_defined(HAVE_TPACKET3);
1048 sock = pf_socket_type(ctx->link_type);
1050 ifindex = device_ifindex(ctx->device_in);
1051 size = ring_size(ctx->device_in, ctx->reserve_size);
1053 enable_kernel_bpf_jit_compiler();
1055 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
1056 if (ctx->dump_bpf)
1057 bpf_dump_all(&bpf_ops);
1058 bpf_attach_to_sock(sock, &bpf_ops);
1060 if (ctx->hwtimestamp) {
1061 ret = set_sockopt_hwtimestamp(sock, ctx->device_in);
1062 if (ret == 0 && ctx->verbose)
1063 printf("HW timestamping enabled\n");
1066 ring_rx_setup(&rx_ring, sock, size, ifindex, &rx_poll, is_v3, true,
1067 ctx->verbose, ctx->fanout_group, ctx->fanout_type);
1069 dissector_init_all(ctx->print_mode);
1071 if (ctx->cpu >= 0 && ifindex > 0) {
1072 int irq = device_irq_number(ctx->device_in);
1073 device_set_irq_affinity(irq, ctx->cpu);
1075 if (ctx->verbose)
1076 printf("IRQ: %s:%d > CPU%d\n",
1077 ctx->device_in, irq, ctx->cpu);
1080 if (ctx->promiscuous)
1081 ifflags = device_enter_promiscuous_mode(ctx->device_in);
1083 if (dump_to_pcap(ctx) && __pcap_io->init_once_pcap)
1084 __pcap_io->init_once_pcap(true);
1086 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
1088 if (dump_to_pcap(ctx)) {
1089 struct stat stats;
1091 ret = stat(ctx->device_out, &stats);
1092 if (ret < 0)
1093 ctx->dump_dir = 0;
1094 else
1095 ctx->dump_dir = S_ISDIR(stats.st_mode);
1097 if (ctx->dump_dir)
1098 fd = begin_multi_pcap_file(ctx);
1099 else
1100 fd = begin_single_pcap_file(ctx);
1103 printf("Running! Hang up with ^C!\n\n");
1104 fflush(stdout);
1106 bug_on(gettimeofday(&start, NULL));
1108 while (likely(sigint == 0)) {
1109 #ifdef HAVE_TPACKET3
1110 struct block_desc *pbd;
1112 while (user_may_pull_from_rx_block((pbd = rx_ring.frames[it].iov_base))) {
1113 walk_t3_block(pbd, ctx, sock, &fd);
1115 kernel_may_pull_from_rx_block(pbd);
1116 it = (it + 1) % rx_ring.layout3.tp_block_nr;
1118 if (unlikely(sigint == 1))
1119 break;
1121 #else
1122 while (user_may_pull_from_rx(rx_ring.frames[it].iov_base)) {
1123 struct frame_map *hdr = rx_ring.frames[it].iov_base;
1124 uint8_t *packet = ((uint8_t *) hdr) + hdr->tp_h.tp_mac;
1125 pcap_pkthdr_t phdr;
1127 if (skip_packet(ctx, &hdr->s_ll))
1128 goto next;
1130 ctx->pkts_seen++;
1132 if (unlikely(ring_frame_size(&rx_ring) < hdr->tp_h.tp_snaplen)) {
1133 /* XXX: silently ignore for now. We used to
1134 * report them with dump_rx_stats() */
1135 goto next;
1138 if (dump_to_pcap(ctx)) {
1139 tpacket_hdr_to_pcap_pkthdr(&hdr->tp_h, &hdr->s_ll, &phdr, ctx->magic);
1141 ret = __pcap_io->write_pcap(fd, &phdr, ctx->magic, packet,
1142 pcap_get_length(&phdr, ctx->magic));
1143 if (unlikely(ret != (int) pcap_get_total_length(&phdr, ctx->magic)))
1144 panic("Write error to pcap!\n");
1147 show_frame_hdr(packet, hdr->tp_h.tp_snaplen,
1148 ctx->link_type, hdr, ctx->print_mode,
1149 ctx->pkts_seen);
1151 dissector_entry_point(packet, hdr->tp_h.tp_snaplen,
1152 ctx->link_type, ctx->print_mode,
1153 &hdr->s_ll);
1155 if (frame_count_max != 0) {
1156 if (unlikely(ctx->pkts_seen >= frame_count_max)) {
1157 sigint = 1;
1158 break;
1162 next:
1163 kernel_may_pull_from_rx(&hdr->tp_h);
1164 it = (it + 1) % rx_ring.layout.tp_frame_nr;
1166 if (unlikely(sigint == 1))
1167 break;
1169 update_pcap_next_dump(ctx, hdr->tp_h.tp_snaplen, &fd,
1170 sock, is_v3);
1172 #endif /* HAVE_TPACKET3 */
1174 ret = poll(&rx_poll, 1, -1);
1175 if (unlikely(ret < 0)) {
1176 if (errno != EINTR)
1177 panic("Poll failed!\n");
1181 bug_on(gettimeofday(&end, NULL));
1182 timersub(&end, &start, &diff);
1184 dump_rx_stats(ctx, sock, is_v3);
1185 printf("\r%12lu sec, %lu usec in total\n",
1186 diff.tv_sec, diff.tv_usec);
1188 bpf_release(&bpf_ops);
1189 dissector_cleanup_all();
1190 destroy_rx_ring(sock, &rx_ring);
1192 if (ctx->promiscuous)
1193 device_leave_promiscuous_mode(ctx->device_in, ifflags);
1195 if (ctx->rfraw)
1196 leave_rfmon_mac80211(ctx->device_in);
1198 if (dump_to_pcap(ctx)) {
1199 if (ctx->dump_dir)
1200 finish_multi_pcap_file(ctx, fd);
1201 else
1202 finish_single_pcap_file(ctx, fd);
1205 close(sock);
1208 static void init_ctx(struct ctx *ctx)
1210 memset(ctx, 0, sizeof(*ctx));
1212 ctx->uid = getuid();
1213 ctx->gid = getgid();
1215 ctx->cpu = -1;
1216 ctx->packet_type = -1;
1218 ctx->fanout_type = PACKET_FANOUT_ROLLOVER;
1220 ctx->magic = ORIGINAL_TCPDUMP_MAGIC;
1221 ctx->print_mode = PRINT_NORM;
1222 ctx->pcap = PCAP_OPS_SG;
1224 ctx->dump_mode = DUMP_INTERVAL_TIME;
1225 ctx->dump_interval = 60;
1227 ctx->promiscuous = true;
1228 ctx->randomize = false;
1229 ctx->hwtimestamp = true;
1232 static void destroy_ctx(struct ctx *ctx)
1234 free(ctx->device_in);
1235 free(ctx->device_out);
1236 free(ctx->device_trans);
1238 free(ctx->prefix);
1241 static void __noreturn help(void)
1243 printf("netsniff-ng %s, the packet sniffing beast\n", VERSION_STRING);
1244 puts("http://www.netsniff-ng.org\n\n"
1245 "Usage: netsniff-ng [options] [filter-expression]\n"
1246 "Options:\n"
1247 " -i|-d|--dev|--in <dev|pcap|-> Input source as netdev, pcap or pcap stdin\n"
1248 " -o|--out <dev|pcap|dir|cfg|-> Output sink as netdev, pcap, directory, trafgen, or stdout\n"
1249 " -C|--fanout-group <id> Join packet fanout group\n"
1250 " -K|--fanout-type <type> Apply fanout discipline: hash|lb|cpu|rnd|roll|qm\n"
1251 " -L|--fanout-opts <opts> Additional fanout options: defrag|roll\n"
1252 " -f|--filter <bpf-file|-|expr> Use BPF filter from bpfc file/stdin or tcpdump-like expression\n"
1253 " -t|--type <type> Filter for: host|broadcast|multicast|others|outgoing\n"
1254 " -F|--interval <size|time> Dump interval if -o is a dir: <num>KiB/MiB/GiB/s/sec/min/hrs\n"
1255 " -R|--rfraw Capture or inject raw 802.11 frames\n"
1256 " -n|--num <0|uint> Number of packets until exit (def: 0)\n"
1257 " -P|--prefix <name> Prefix for pcaps stored in directory\n"
1258 " -O|--overwrite <N> Limit the number of pcaps to N (file names use numbers 0 to N-1)\n"
1259 " -T|--magic <pcap-magic> Pcap magic number/pcap format to store, see -D\n"
1260 " -w|--cooked Use Linux \"cooked\" header instead of link header\n"
1261 " -D|--dump-pcap-types Dump pcap types and magic numbers and quit\n"
1262 " -B|--dump-bpf Dump generated BPF assembly\n"
1263 " -r|--rand Randomize packet forwarding order (dev->dev)\n"
1264 " -M|--no-promisc No promiscuous mode for netdev\n"
1265 " -A|--no-sock-mem Don't tune core socket memory\n"
1266 " -N|--no-hwtimestamp Disable hardware time stamping\n"
1267 " -m|--mmap Mmap(2) pcap file I/O, e.g. for replaying pcaps\n"
1268 " -G|--sg Scatter/gather pcap file I/O\n"
1269 " -c|--clrw Use slower read(2)/write(2) I/O\n"
1270 " -S|--ring-size <size> Specify ring size to: <num>KiB/MiB/GiB\n"
1271 " -k|--kernel-pull <uint> Kernel pull from user interval in us (def: 10us)\n"
1272 " -J|--jumbo-support Support replay/fwd 64KB Super Jumbo Frames (def: 2048B)\n"
1273 " -b|--bind-cpu <cpu> Bind to specific CPU\n"
1274 " -u|--user <userid> Drop privileges and change to userid\n"
1275 " -g|--group <groupid> Drop privileges and change to groupid\n"
1276 " -H|--prio-high Make this high priority process\n"
1277 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
1278 " -s|--silent Do not print captured packets\n"
1279 " -q|--less Print less-verbose packet information\n"
1280 " -X|--hex Print packet data in hex format\n"
1281 " -l|--ascii Print human-readable packet data\n"
1282 " -U|--update Update GeoIP databases\n"
1283 " -V|--verbose Be more verbose\n"
1284 " -v|--version Show version and exit\n"
1285 " -h|--help Guess what?!\n\n"
1286 "Examples:\n"
1287 " netsniff-ng --in eth0 --out dump.pcap -s -T 0xa1b2c3d4 --bind-cpu 0 tcp or udp\n"
1288 " netsniff-ng --in wlan0 --rfraw --out dump.pcap --silent --bind-cpu 0\n"
1289 " netsniff-ng --in dump.pcap --mmap --out eth0 -k1000 --silent --bind-cpu 0\n"
1290 " netsniff-ng --in dump.pcap --out dump.cfg --silent --bind-cpu 0\n"
1291 " netsniff-ng --in dump.pcap --out dump2.pcap --silent tcp\n"
1292 " netsniff-ng --in eth0 --out eth1 --silent --bind-cpu 0 -J --type host\n"
1293 " netsniff-ng --in eth1 --out /opt/probe/ -s -m --interval 100MiB -b 0\n"
1294 " netsniff-ng --in vlan0 --out dump.pcap -c -u `id -u bob` -g `id -g bob`\n"
1295 " netsniff-ng --in any --filter http.bpf --jumbo-support --ascii -V\n\n"
1296 "Note:\n"
1297 " For introducing bit errors, delays with random variation and more\n"
1298 " while replaying pcaps, make use of tc(8) with its disciplines (e.g. netem).\n");
1299 puts(copyright);
1300 die();
1303 static void __noreturn version(void)
1305 printf("netsniff-ng %s, Git id: %s\n", VERSION_LONG, GITVERSION);
1306 puts("the packet sniffing beast\n"
1307 "http://www.netsniff-ng.org\n");
1308 puts(copyright);
1309 die();
1312 int main(int argc, char **argv)
1314 char *ptr;
1315 int c, i, j, cpu_tmp, ops_touched = 0, vals[4] = {0};
1316 bool prio_high = false, setsockmem = true;
1317 void (*main_loop)(struct ctx *ctx) = NULL;
1318 struct ctx ctx;
1320 init_ctx(&ctx);
1321 start_time = time(NULL);
1322 srand(start_time);
1324 while ((c = getopt_long(argc, argv, short_options, long_options,
1325 NULL)) != EOF) {
1326 switch (c) {
1327 case 'd':
1328 case 'i':
1329 ctx.device_in = xstrdup(optarg);
1330 break;
1331 case 'o':
1332 ctx.device_out = xstrdup(optarg);
1333 break;
1334 case 'P':
1335 ctx.prefix = xstrdup(optarg);
1336 break;
1337 case 'O':
1338 ctx.overwrite_interval = strtoul(optarg, NULL, 0);
1339 break;
1340 case 'R':
1341 ctx.rfraw = 1;
1342 break;
1343 case 'r':
1344 ctx.randomize = true;
1345 break;
1346 case 'J':
1347 ctx.jumbo = true;
1348 break;
1349 case 'T':
1350 ctx.magic = (uint32_t) strtoul(optarg, NULL, 0);
1351 pcap_check_magic(ctx.magic);
1352 break;
1353 case 'f':
1354 ctx.filter = xstrdup(optarg);
1355 break;
1356 case 'M':
1357 ctx.promiscuous = false;
1358 break;
1359 case 'N':
1360 ctx.hwtimestamp = false;
1361 break;
1362 case 'A':
1363 setsockmem = false;
1364 break;
1365 case 'u':
1366 ctx.uid = strtoul(optarg, NULL, 0);
1367 ctx.enforce = true;
1368 break;
1369 case 'g':
1370 ctx.gid = strtoul(optarg, NULL, 0);
1371 ctx.enforce = true;
1372 break;
1373 case 'C':
1374 ctx.fanout_group = strtoul(optarg, NULL, 0);
1375 if (ctx.fanout_group == 0)
1376 panic("Non-zero fanout group id required!\n");
1377 break;
1378 case 'K':
1379 if (!strncmp(optarg, "hash", strlen("hash")))
1380 ctx.fanout_type = PACKET_FANOUT_HASH;
1381 else if (!strncmp(optarg, "lb", strlen("lb")) ||
1382 !strncmp(optarg, "rr", strlen("rr")))
1383 ctx.fanout_type = PACKET_FANOUT_LB;
1384 else if (!strncmp(optarg, "cpu", strlen("cpu")))
1385 ctx.fanout_type = PACKET_FANOUT_CPU;
1386 else if (!strncmp(optarg, "rnd", strlen("rnd")))
1387 ctx.fanout_type = PACKET_FANOUT_RND;
1388 else if (!strncmp(optarg, "roll", strlen("roll")))
1389 ctx.fanout_type = PACKET_FANOUT_ROLLOVER;
1390 else if (!strncmp(optarg, "qm", strlen("qm")))
1391 ctx.fanout_type = PACKET_FANOUT_QM;
1392 else
1393 panic("Unknown fanout type!\n");
1394 break;
1395 case 'L':
1396 if (!strncmp(optarg, "defrag", strlen("defrag")))
1397 ctx.fanout_type |= PACKET_FANOUT_FLAG_DEFRAG;
1398 else if (!strncmp(optarg, "roll", strlen("roll")))
1399 ctx.fanout_type |= PACKET_FANOUT_FLAG_ROLLOVER;
1400 else
1401 panic("Unknown fanout option!\n");
1402 break;
1403 case 't':
1404 if (!strncmp(optarg, "host", strlen("host")))
1405 ctx.packet_type = PACKET_HOST;
1406 else if (!strncmp(optarg, "broadcast", strlen("broadcast")))
1407 ctx.packet_type = PACKET_BROADCAST;
1408 else if (!strncmp(optarg, "multicast", strlen("multicast")))
1409 ctx.packet_type = PACKET_MULTICAST;
1410 else if (!strncmp(optarg, "others", strlen("others")))
1411 ctx.packet_type = PACKET_OTHERHOST;
1412 else if (!strncmp(optarg, "outgoing", strlen("outgoing")))
1413 ctx.packet_type = PACKET_OUTGOING;
1414 else
1415 ctx.packet_type = -1;
1416 break;
1417 case 'S':
1418 ptr = optarg;
1419 for (j = i = strlen(optarg); i > 0; --i) {
1420 if (!isdigit(optarg[j - i]))
1421 break;
1422 ptr++;
1425 if (!strncmp(ptr, "KiB", strlen("KiB")))
1426 ctx.reserve_size = 1 << 10;
1427 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1428 ctx.reserve_size = 1 << 20;
1429 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1430 ctx.reserve_size = 1 << 30;
1431 else
1432 panic("Syntax error in ring size param!\n");
1434 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1435 break;
1436 case 'b':
1437 cpu_tmp = strtol(optarg, NULL, 0);
1439 cpu_affinity(cpu_tmp);
1440 if (ctx.cpu != -2)
1441 ctx.cpu = cpu_tmp;
1442 break;
1443 case 'H':
1444 prio_high = true;
1445 break;
1446 case 'c':
1447 ctx.pcap = PCAP_OPS_RW;
1448 ops_touched = 1;
1449 break;
1450 case 'm':
1451 ctx.pcap = PCAP_OPS_MM;
1452 ops_touched = 1;
1453 break;
1454 case 'G':
1455 ctx.pcap = PCAP_OPS_SG;
1456 ops_touched = 1;
1457 break;
1458 case 'Q':
1459 ctx.cpu = -2;
1460 break;
1461 case 's':
1462 ctx.print_mode = PRINT_NONE;
1463 break;
1464 case 'q':
1465 ctx.print_mode = PRINT_LESS;
1466 break;
1467 case 'X':
1468 ctx.print_mode =
1469 (ctx.print_mode == PRINT_ASCII) ?
1470 PRINT_HEX_ASCII : PRINT_HEX;
1471 break;
1472 case 'l':
1473 ctx.print_mode =
1474 (ctx.print_mode == PRINT_HEX) ?
1475 PRINT_HEX_ASCII : PRINT_ASCII;
1476 break;
1477 case 'k':
1478 ctx.kpull = strtoul(optarg, NULL, 0);
1479 break;
1480 case 'n':
1481 frame_count_max = strtoul(optarg, NULL, 0);
1482 break;
1483 case 'F':
1484 ptr = optarg;
1485 for (j = i = strlen(optarg); i > 0; --i) {
1486 if (!isdigit(optarg[j - i]))
1487 break;
1488 ptr++;
1491 if (!strncmp(ptr, "KiB", strlen("KiB"))) {
1492 ctx.dump_interval = 1 << 10;
1493 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1494 } else if (!strncmp(ptr, "MiB", strlen("MiB"))) {
1495 ctx.dump_interval = 1 << 20;
1496 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1497 } else if (!strncmp(ptr, "GiB", strlen("GiB"))) {
1498 ctx.dump_interval = 1 << 30;
1499 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1500 } else if (!strncmp(ptr, "sec", strlen("sec"))) {
1501 ctx.dump_interval = 1;
1502 ctx.dump_mode = DUMP_INTERVAL_TIME;
1503 } else if (!strncmp(ptr, "min", strlen("min"))) {
1504 ctx.dump_interval = 60;
1505 ctx.dump_mode = DUMP_INTERVAL_TIME;
1506 } else if (!strncmp(ptr, "hrs", strlen("hrs"))) {
1507 ctx.dump_interval = 60 * 60;
1508 ctx.dump_mode = DUMP_INTERVAL_TIME;
1509 } else if (!strncmp(ptr, "s", strlen("s"))) {
1510 ctx.dump_interval = 1;
1511 ctx.dump_mode = DUMP_INTERVAL_TIME;
1512 } else {
1513 panic("Syntax error in time/size param!\n");
1516 ctx.dump_interval *= strtoul(optarg, NULL, 0);
1517 break;
1518 case 'V':
1519 ctx.verbose = true;
1520 break;
1521 case 'B':
1522 ctx.dump_bpf = true;
1523 break;
1524 case 'D':
1525 pcap_dump_type_features();
1526 die();
1527 break;
1528 case 'U':
1529 update_geoip();
1530 die();
1531 break;
1532 case 'w':
1533 ctx.link_type = LINKTYPE_LINUX_SLL;
1534 break;
1535 case 'v':
1536 version();
1537 break;
1538 case 'h':
1539 help();
1540 break;
1541 case '?':
1542 switch (optopt) {
1543 case 'd':
1544 case 'i':
1545 case 'o':
1546 case 'f':
1547 case 't':
1548 case 'P':
1549 case 'O':
1550 case 'F':
1551 case 'n':
1552 case 'S':
1553 case 'b':
1554 case 'k':
1555 case 'T':
1556 case 'u':
1557 case 'g':
1558 case 'e':
1559 panic("Option -%c requires an argument!\n",
1560 optopt);
1561 default:
1562 if (isprint(optopt))
1563 printf("Unknown option character `0x%X\'!\n", optopt);
1564 die();
1566 default:
1567 break;
1571 if (!ctx.filter && optind != argc)
1572 ctx.filter = argv2str(optind, argc, argv);
1574 if (!ctx.device_in)
1575 ctx.device_in = xstrdup("any");
1577 if (!strcmp(ctx.device_in, "any") || !strcmp(ctx.device_in, "lo"))
1578 ctx.lo_ifindex = device_ifindex("lo");
1580 register_signal(SIGINT, signal_handler);
1581 register_signal(SIGQUIT, signal_handler);
1582 register_signal(SIGTERM, signal_handler);
1583 register_signal(SIGHUP, signal_handler);
1585 tprintf_init();
1587 if (prio_high) {
1588 set_proc_prio(-20);
1589 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1592 if (device_mtu(ctx.device_in) || !strncmp("any", ctx.device_in, strlen(ctx.device_in))) {
1593 if (ctx.rfraw)
1594 setup_rfmon_mac80211_dev(&ctx, &ctx.device_in);
1596 if (!ctx.link_type)
1597 ctx.link_type = pcap_dev_to_linktype(ctx.device_in);
1598 if (link_has_sll_hdr(ctx.link_type)) {
1599 switch (ctx.magic) {
1600 case ORIGINAL_TCPDUMP_MAGIC:
1601 ctx.magic = ORIGINAL_TCPDUMP_MAGIC_LL;
1602 break;
1603 case NSEC_TCPDUMP_MAGIC:
1604 ctx.magic = NSEC_TCPDUMP_MAGIC_LL;
1605 break;
1606 case ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC):
1607 ctx.magic = ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC_LL);
1608 break;
1609 case ___constant_swab32(NSEC_TCPDUMP_MAGIC):
1610 ctx.magic = ___constant_swab32(NSEC_TCPDUMP_MAGIC_LL);
1611 break;
1616 if (!ctx.device_out) {
1617 ctx.dump = 0;
1618 main_loop = recv_only_or_dump;
1619 } else if (device_mtu(ctx.device_out)) {
1620 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1621 main_loop = receive_to_xmit;
1622 } else {
1623 ctx.dump = 1;
1624 register_signal_f(SIGALRM, timer_next_dump, SA_SIGINFO);
1625 main_loop = recv_only_or_dump;
1626 if (!ops_touched)
1627 ctx.pcap = PCAP_OPS_SG;
1629 } else {
1630 if (ctx.device_out && device_mtu(ctx.device_out)) {
1631 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1632 main_loop = pcap_to_xmit;
1633 if (!ops_touched)
1634 ctx.pcap = PCAP_OPS_MM;
1635 } else {
1636 setsockmem = false;
1637 main_loop = read_pcap;
1638 if (!ops_touched)
1639 ctx.pcap = PCAP_OPS_SG;
1643 bug_on(!main_loop);
1645 init_geoip(0);
1646 if (setsockmem)
1647 set_system_socket_memory(vals, array_size(vals));
1648 if (!ctx.enforce)
1649 xlockme();
1651 if (ctx.verbose)
1652 printf("pcap file I/O method: %s\n", pcap_ops_group_to_str[ctx.pcap]);
1654 main_loop(&ctx);
1656 if (!ctx.enforce)
1657 xunlockme();
1658 if (setsockmem)
1659 reset_system_socket_memory(vals, array_size(vals));
1660 destroy_geoip();
1662 device_restore_irq_affinity_list();
1663 tprintf_cleanup();
1665 destroy_ctx(&ctx);
1666 return 0;