mz: Check device argument by ifindex instead of name prefix
[netsniff-ng.git] / netsniff-ng.c
blobce37e108827683c411884120555c0acac7cdf50d
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2009-2013 Daniel Borkmann.
4 * Copyright 2010 Emmanuel Roullit.
5 * Subject to the GPL, version 2.
6 */
8 #define _GNU_SOURCE
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <signal.h>
12 #include <getopt.h>
13 #include <ctype.h>
14 #include <time.h>
15 #include <string.h>
16 #include <sys/socket.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <sys/time.h>
20 #include <sys/fsuid.h>
21 #include <unistd.h>
22 #include <stdbool.h>
23 #include <pthread.h>
24 #include <fcntl.h>
25 #include <inttypes.h>
27 #include "ring_rx.h"
28 #include "ring_tx.h"
29 #include "mac80211.h"
30 #include "dev.h"
31 #include "built_in.h"
32 #include "pcap_io.h"
33 #include "privs.h"
34 #include "proc.h"
35 #include "bpf.h"
36 #include "ioops.h"
37 #include "die.h"
38 #include "irq.h"
39 #include "str.h"
40 #include "sig.h"
41 #include "config.h"
42 #include "sock.h"
43 #include "geoip.h"
44 #include "lockme.h"
45 #include "tprintf.h"
46 #include "timer.h"
47 #include "tstamping.h"
48 #include "dissector.h"
49 #include "xmalloc.h"
51 enum dump_mode {
52 DUMP_INTERVAL_TIME,
53 DUMP_INTERVAL_SIZE,
56 struct ctx {
57 char *device_in, *device_out, *device_trans, *filter, *prefix;
58 int cpu, rfraw, dump, print_mode, dump_dir, packet_type, lo_ifindex;
59 unsigned long kpull, dump_interval, tx_bytes, tx_packets;
60 size_t reserve_size;
61 bool randomize, promiscuous, enforce, jumbo, dump_bpf, hwtimestamp, verbose;
62 enum pcap_ops_groups pcap;
63 enum dump_mode dump_mode;
64 uid_t uid;
65 gid_t gid;
66 uint32_t link_type, magic;
67 uint32_t fanout_group, fanout_type;
68 uint64_t pkts_seen, pkts_recvd, pkts_drops;
69 uint64_t pkts_recvd_last, pkts_drops_last, pkts_skipd_last;
72 static volatile sig_atomic_t sigint = 0, sighup = 0;
73 static volatile bool next_dump = false;
74 static volatile sig_atomic_t sighup_time = 0;
76 static const char *short_options =
77 "d:i:o:rf:MNJt:S:k:n:b:HQmcsqXlvhF:RGAP:Vu:g:T:DBUC:K:L:w";
78 static const struct option long_options[] = {
79 {"dev", required_argument, NULL, 'd'},
80 {"in", required_argument, NULL, 'i'},
81 {"out", required_argument, NULL, 'o'},
82 {"filter", required_argument, NULL, 'f'},
83 {"num", required_argument, NULL, 'n'},
84 {"type", required_argument, NULL, 't'},
85 {"interval", required_argument, NULL, 'F'},
86 {"ring-size", required_argument, NULL, 'S'},
87 {"kernel-pull", required_argument, NULL, 'k'},
88 {"bind-cpu", required_argument, NULL, 'b'},
89 {"prefix", required_argument, NULL, 'P'},
90 {"user", required_argument, NULL, 'u'},
91 {"group", required_argument, NULL, 'g'},
92 {"magic", required_argument, NULL, 'T'},
93 {"fanout-group", required_argument, NULL, 'C'},
94 {"fanout-type", required_argument, NULL, 'K'},
95 {"fanout-opts", required_argument, NULL, 'L'},
96 {"rand", no_argument, NULL, 'r'},
97 {"rfraw", no_argument, NULL, 'R'},
98 {"mmap", no_argument, NULL, 'm'},
99 {"sg", no_argument, NULL, 'G'},
100 {"clrw", no_argument, NULL, 'c'},
101 {"jumbo-support", no_argument, NULL, 'J'},
102 {"no-promisc", no_argument, NULL, 'M'},
103 {"no-hwtimestamp", no_argument, NULL, 'N'},
104 {"prio-high", no_argument, NULL, 'H'},
105 {"notouch-irq", no_argument, NULL, 'Q'},
106 {"dump-pcap-types", no_argument, NULL, 'D'},
107 {"dump-bpf", no_argument, NULL, 'B'},
108 {"silent", no_argument, NULL, 's'},
109 {"less", no_argument, NULL, 'q'},
110 {"hex", no_argument, NULL, 'X'},
111 {"ascii", no_argument, NULL, 'l'},
112 {"no-sock-mem", no_argument, NULL, 'A'},
113 {"update", no_argument, NULL, 'U'},
114 {"cooked", no_argument, NULL, 'w'},
115 {"verbose", no_argument, NULL, 'V'},
116 {"version", no_argument, NULL, 'v'},
117 {"help", no_argument, NULL, 'h'},
118 {NULL, 0, NULL, 0}
121 static const char *copyright = "Please report bugs to <netsniff-ng@googlegroups.com>\n"
122 "Copyright (C) 2009-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
123 "Copyright (C) 2009-2012 Emmanuel Roullit <emmanuel.roullit@gmail.com>\n"
124 "Copyright (C) 2012 Markus Amend <markus@netsniff-ng.org>\n"
125 "Swiss federal institute of technology (ETH Zurich)\n"
126 "License: GNU GPL version 2.0\n"
127 "This is free software: you are free to change and redistribute it.\n"
128 "There is NO WARRANTY, to the extent permitted by law.";
130 static int tx_sock;
131 static struct itimerval itimer;
132 static unsigned long frame_count_max = 0, interval = TX_KERNEL_PULL_INT;
133 static time_t start_time;
135 #define __pcap_io pcap_ops[ctx->pcap]
137 static void signal_handler(int number)
139 switch (number) {
140 case SIGINT:
141 case SIGQUIT:
142 case SIGTERM:
143 sigint = 1;
144 break;
145 case SIGHUP:
146 sighup = 1;
147 sighup_time = (sig_atomic_t)(time(NULL) - start_time);
148 break;
149 default:
150 break;
154 static void timer_elapsed(int unused __maybe_unused)
156 int ret;
158 set_itimer_interval_value(&itimer, 0, interval);
160 ret = pull_and_flush_tx_ring(tx_sock);
161 if (unlikely(ret < 0)) {
162 /* We could hit EBADF if the socket has been closed before
163 * the timer was triggered.
165 if (errno != EBADF && errno != ENOBUFS)
166 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
169 setitimer(ITIMER_REAL, &itimer, NULL);
172 static void timer_purge(void)
174 int ret;
176 ret = pull_and_flush_tx_ring_wait(tx_sock);
177 if (unlikely(ret < 0)) {
178 if (errno != EBADF && errno != ENOBUFS)
179 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
182 set_itimer_interval_value(&itimer, 0, 0);
183 setitimer(ITIMER_REAL, &itimer, NULL);
186 static void timer_next_dump(int unused __maybe_unused)
188 set_itimer_interval_value(&itimer, interval, 0);
189 next_dump = true;
190 setitimer(ITIMER_REAL, &itimer, NULL);
193 static inline bool dump_to_pcap(struct ctx *ctx)
195 return ctx->dump;
198 static void on_panic_del_rfmon(void *arg)
200 leave_rfmon_mac80211(arg);
203 static inline void setup_rfmon_mac80211_dev(struct ctx *ctx, char **rfmon_dev)
205 ctx->device_trans = xstrdup(*rfmon_dev);
206 xfree(*rfmon_dev);
208 enter_rfmon_mac80211(ctx->device_trans, rfmon_dev);
209 panic_handler_add(on_panic_del_rfmon, *rfmon_dev);
212 static int update_rx_stats(struct ctx *ctx, int sock, bool is_v3)
214 uint64_t packets, drops;
215 int ret;
217 ret = get_rx_net_stats(sock, &packets, &drops, is_v3);
218 if (ret)
219 return ret;
221 drops += ctx->pkts_skipd_last;
222 ctx->pkts_seen += ctx->pkts_skipd_last;
223 ctx->pkts_recvd += packets;
224 ctx->pkts_drops += drops;
225 ctx->pkts_recvd_last = packets;
226 ctx->pkts_drops_last = drops;
227 ctx->pkts_skipd_last = 0;
229 return 0;
232 static void dump_rx_stats(struct ctx *ctx, int sock, bool is_v3)
234 if (update_rx_stats(ctx, sock, is_v3))
235 return;
237 printf("\r%12"PRIu64" packets incoming (%"PRIu64" unread on exit)\n",
238 is_v3 ? ctx->pkts_seen : ctx->pkts_recvd,
239 is_v3 ? ctx->pkts_recvd - ctx->pkts_seen : 0);
240 printf("\r%12"PRIu64" packets passed filter\n",
241 ctx->pkts_recvd - ctx->pkts_drops);
242 printf("\r%12"PRIu64" packets failed filter (out of space)\n",
243 ctx->pkts_drops);
245 if (ctx->pkts_recvd > 0)
246 printf("\r%12.4lf%% packet droprate\n",
247 (1.0 * ctx->pkts_drops / ctx->pkts_recvd) * 100.0);
250 static void pcap_to_xmit(struct ctx *ctx)
252 uint8_t *out = NULL;
253 int ifindex, fd = 0, ret;
254 size_t size;
255 unsigned int it = 0;
256 unsigned long trunced = 0;
257 struct ring tx_ring;
258 struct frame_map *hdr;
259 struct sock_fprog bpf_ops;
260 struct timeval start, end, diff;
261 pcap_pkthdr_t phdr;
263 if (!device_up_and_running(ctx->device_out) && !ctx->rfraw)
264 panic("Device not up and running!\n");
266 bug_on(!__pcap_io);
268 tx_sock = pf_socket();
270 if (!strncmp("-", ctx->device_in, strlen("-"))) {
271 fd = dup_or_die(fileno(stdin));
272 close(fileno(stdin));
273 if (ctx->pcap == PCAP_OPS_MM)
274 ctx->pcap = PCAP_OPS_SG;
275 } else {
276 fd = open_or_die(ctx->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
279 if (__pcap_io->init_once_pcap)
280 __pcap_io->init_once_pcap(true);
282 ret = __pcap_io->pull_fhdr_pcap(fd, &ctx->magic, &ctx->link_type);
283 if (ret)
284 panic("Error reading pcap header!\n");
286 if (__pcap_io->prepare_access_pcap) {
287 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_RD, ctx->jumbo);
288 if (ret)
289 panic("Error prepare reading pcap!\n");
292 if (ctx->rfraw) {
293 setup_rfmon_mac80211_dev(ctx, &ctx->device_out);
295 if (ctx->link_type != LINKTYPE_IEEE802_11 &&
296 ctx->link_type != LINKTYPE_IEEE802_11_RADIOTAP)
297 panic("Wrong linktype of pcap!\n");
300 ifindex = device_ifindex(ctx->device_out);
301 size = ring_size(ctx->device_out, ctx->reserve_size);
303 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
304 if (ctx->dump_bpf)
305 bpf_dump_all(&bpf_ops);
307 ring_tx_setup(&tx_ring, tx_sock, size, ifindex, ctx->jumbo, ctx->verbose);
309 dissector_init_all(ctx->print_mode);
311 if (ctx->cpu >= 0 && ifindex > 0) {
312 int irq = device_irq_number(ctx->device_out);
313 device_set_irq_affinity(irq, ctx->cpu);
315 if (ctx->verbose)
316 printf("IRQ: %s:%d > CPU%d\n",
317 ctx->device_out, irq, ctx->cpu);
320 if (ctx->kpull)
321 interval = ctx->kpull;
323 set_itimer_interval_value(&itimer, 0, interval);
324 setitimer(ITIMER_REAL, &itimer, NULL);
326 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
328 printf("Running! Hang up with ^C!\n\n");
329 fflush(stdout);
331 bug_on(gettimeofday(&start, NULL));
333 while (likely(sigint == 0)) {
334 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
335 hdr = tx_ring.frames[it].iov_base;
336 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
338 do {
339 ret = __pcap_io->read_pcap(fd, &phdr, ctx->magic, out,
340 ring_frame_size(&tx_ring));
341 if (unlikely(ret <= 0))
342 goto out;
344 if (ring_frame_size(&tx_ring) <
345 pcap_get_length(&phdr, ctx->magic)) {
346 pcap_set_length(&phdr, ctx->magic,
347 ring_frame_size(&tx_ring));
348 trunced++;
350 } while (ctx->filter &&
351 !bpf_run_filter(&bpf_ops, out,
352 pcap_get_length(&phdr, ctx->magic)));
354 pcap_pkthdr_to_tpacket_hdr(&phdr, ctx->magic, &hdr->tp_h, NULL);
356 ctx->tx_bytes += hdr->tp_h.tp_len;;
357 ctx->tx_packets++;
359 show_frame_hdr(out, hdr->tp_h.tp_snaplen,
360 ctx->link_type, hdr, ctx->print_mode,
361 ctx->tx_packets);
363 dissector_entry_point(out, hdr->tp_h.tp_snaplen,
364 ctx->link_type, ctx->print_mode,
365 &hdr->s_ll);
367 kernel_may_pull_from_tx(&hdr->tp_h);
369 it++;
370 if (it >= tx_ring.layout.tp_frame_nr)
371 it = 0;
373 if (unlikely(sigint == 1))
374 break;
376 if (frame_count_max != 0) {
377 if (ctx->tx_packets >= frame_count_max) {
378 sigint = 1;
379 break;
385 out:
386 bug_on(gettimeofday(&end, NULL));
387 timersub(&end, &start, &diff);
389 timer_purge();
391 bpf_release(&bpf_ops);
393 dissector_cleanup_all();
394 destroy_tx_ring(tx_sock, &tx_ring);
396 if (ctx->rfraw)
397 leave_rfmon_mac80211(ctx->device_out);
399 if (__pcap_io->prepare_close_pcap)
400 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_RD);
402 if (!strncmp("-", ctx->device_in, strlen("-")))
403 dup2(fd, fileno(stdin));
404 close(fd);
406 close(tx_sock);
408 fflush(stdout);
409 printf("\n");
410 printf("\r%12lu packets outgoing\n", ctx->tx_packets);
411 printf("\r%12lu packets truncated in file\n", trunced);
412 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
413 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
416 static inline bool __skip_packet(struct ctx *ctx, struct sockaddr_ll *sll)
418 if (ctx->packet_type != -1)
419 return ctx->packet_type != sll->sll_pkttype;
421 /* when receving from the loopback device, each packet is seen twice,
422 * so drop the outgoing ones to avoid duplicates
424 return (sll->sll_ifindex == ctx->lo_ifindex) &&
425 (sll->sll_pkttype == PACKET_OUTGOING);
428 static inline bool skip_packet(struct ctx *ctx, struct sockaddr_ll *sll)
430 bool skip = __skip_packet(ctx, sll);
432 if (skip)
433 ctx->pkts_skipd_last++;
434 return skip;
437 static void receive_to_xmit(struct ctx *ctx)
439 short ifflags = 0;
440 uint8_t *in, *out;
441 int rx_sock, ifindex_in, ifindex_out, ret;
442 size_t size_in, size_out;
443 unsigned int it_in = 0, it_out = 0;
444 struct frame_map *hdr_in, *hdr_out;
445 struct ring tx_ring, rx_ring;
446 struct pollfd rx_poll;
447 struct sock_fprog bpf_ops;
449 if (!strncmp(ctx->device_in, ctx->device_out, IFNAMSIZ))
450 panic("Ingress/egress devices must be different!\n");
451 if (!device_up_and_running(ctx->device_out))
452 panic("Egress device not up and running!\n");
454 rx_sock = pf_socket();
455 tx_sock = pf_socket();
457 ifindex_in = device_ifindex(ctx->device_in);
458 ifindex_out = device_ifindex(ctx->device_out);
460 size_in = ring_size(ctx->device_in, ctx->reserve_size);
461 size_out = ring_size(ctx->device_out, ctx->reserve_size);
463 enable_kernel_bpf_jit_compiler();
465 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
466 if (ctx->dump_bpf)
467 bpf_dump_all(&bpf_ops);
468 bpf_attach_to_sock(rx_sock, &bpf_ops);
470 ring_rx_setup(&rx_ring, rx_sock, size_in, ifindex_in, &rx_poll, false, ctx->jumbo,
471 ctx->verbose, ctx->fanout_group, ctx->fanout_type);
472 ring_tx_setup(&tx_ring, tx_sock, size_out, ifindex_out, ctx->jumbo, ctx->verbose);
474 dissector_init_all(ctx->print_mode);
476 if (ctx->promiscuous)
477 ifflags = device_enter_promiscuous_mode(ctx->device_in);
479 if (ctx->kpull)
480 interval = ctx->kpull;
482 set_itimer_interval_value(&itimer, 0, interval);
483 setitimer(ITIMER_REAL, &itimer, NULL);
485 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
487 printf("Running! Hang up with ^C!\n\n");
488 fflush(stdout);
490 while (likely(sigint == 0)) {
491 while (user_may_pull_from_rx(rx_ring.frames[it_in].iov_base)) {
492 hdr_in = rx_ring.frames[it_in].iov_base;
493 in = ((uint8_t *) hdr_in) + hdr_in->tp_h.tp_mac;
495 if (skip_packet(ctx, &hdr_in->s_ll))
496 goto next;
498 ctx->pkts_seen++;
500 hdr_out = tx_ring.frames[it_out].iov_base;
501 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
503 while (!user_may_pull_from_tx(tx_ring.frames[it_out].iov_base) &&
504 likely(!sigint)) {
505 if (ctx->randomize)
506 next_rnd_slot(&it_out, &tx_ring);
507 else {
508 it_out++;
509 if (it_out >= tx_ring.layout.tp_frame_nr)
510 it_out = 0;
513 hdr_out = tx_ring.frames[it_out].iov_base;
514 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
517 tpacket_hdr_clone(&hdr_out->tp_h, &hdr_in->tp_h);
518 fmemcpy(out, in, hdr_in->tp_h.tp_len);
520 kernel_may_pull_from_tx(&hdr_out->tp_h);
521 if (ctx->randomize)
522 next_rnd_slot(&it_out, &tx_ring);
523 else {
524 it_out++;
525 if (it_out >= tx_ring.layout.tp_frame_nr)
526 it_out = 0;
529 show_frame_hdr(in, hdr_in->tp_h.tp_snaplen,
530 ctx->link_type, hdr_in, ctx->print_mode,
531 ctx->pkts_seen);
533 dissector_entry_point(in, hdr_in->tp_h.tp_snaplen,
534 ctx->link_type, ctx->print_mode,
535 &hdr_in->s_ll);
537 if (frame_count_max != 0) {
538 if (ctx->pkts_seen >= frame_count_max) {
539 sigint = 1;
540 break;
544 next:
545 kernel_may_pull_from_rx(&hdr_in->tp_h);
547 it_in++;
548 if (it_in >= rx_ring.layout.tp_frame_nr)
549 it_in = 0;
551 if (unlikely(sigint == 1))
552 goto out;
555 ret = poll(&rx_poll, 1, -1);
556 if (unlikely(ret < 0)) {
557 if (errno != EINTR)
558 panic("Poll failed!\n");
562 out:
563 timer_purge();
565 dump_rx_stats(ctx, rx_sock, false);
567 bpf_release(&bpf_ops);
569 dissector_cleanup_all();
571 destroy_tx_ring(tx_sock, &tx_ring);
572 destroy_rx_ring(rx_sock, &rx_ring);
574 if (ctx->promiscuous)
575 device_leave_promiscuous_mode(ctx->device_in, ifflags);
577 close(tx_sock);
578 close(rx_sock);
581 static void translate_pcap_to_txf(int fdo, uint8_t *out, size_t len)
583 size_t bytes_done = 0;
584 char bout[80];
586 slprintf(bout, sizeof(bout), "{\n ");
587 write_or_die(fdo, bout, strlen(bout));
589 while (bytes_done < len) {
590 slprintf(bout, sizeof(bout), "0x%02x,", out[bytes_done]);
591 write_or_die(fdo, bout, strlen(bout));
593 bytes_done++;
595 if (bytes_done % 10 == 0) {
596 slprintf(bout, sizeof(bout), "\n");
597 write_or_die(fdo, bout, strlen(bout));
599 if (bytes_done < len) {
600 slprintf(bout, sizeof(bout), " ");
601 write_or_die(fdo, bout, strlen(bout));
603 } else if (bytes_done < len) {
604 slprintf(bout, sizeof(bout), " ");
605 write_or_die(fdo, bout, strlen(bout));
608 if (bytes_done % 10 != 0) {
609 slprintf(bout, sizeof(bout), "\n");
610 write_or_die(fdo, bout, strlen(bout));
613 slprintf(bout, sizeof(bout), "}\n\n");
614 write_or_die(fdo, bout, strlen(bout));
617 static void read_pcap(struct ctx *ctx)
619 uint8_t *out;
620 int ret, fd, fdo = 0;
621 unsigned long trunced = 0;
622 size_t out_len;
623 pcap_pkthdr_t phdr;
624 struct sock_fprog bpf_ops;
625 struct frame_map fm;
626 struct timeval start, end, diff;
627 bool is_out_pcap = ctx->device_out && strstr(ctx->device_out, ".pcap");
628 const struct pcap_file_ops *pcap_out_ops = pcap_ops[PCAP_OPS_RW];
630 bug_on(!__pcap_io);
632 if (!strncmp("-", ctx->device_in, strlen("-"))) {
633 fd = dup_or_die(fileno(stdin));
634 close(fileno(stdin));
635 if (ctx->pcap == PCAP_OPS_MM)
636 ctx->pcap = PCAP_OPS_SG;
637 } else {
638 /* O_NOATIME requires privileges, in case we don't have
639 * them, retry without them at a minor cost of updating
640 * atime in case the fs has been mounted as such.
642 fd = open(ctx->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
643 if (fd < 0 && errno == EPERM)
644 fd = open_or_die(ctx->device_in, O_RDONLY | O_LARGEFILE);
645 if (fd < 0)
646 panic("Cannot open file %s! %s.\n", ctx->device_in,
647 strerror(errno));
650 if (__pcap_io->init_once_pcap)
651 __pcap_io->init_once_pcap(false);
653 ret = __pcap_io->pull_fhdr_pcap(fd, &ctx->magic, &ctx->link_type);
654 if (ret)
655 panic("Error reading pcap header!\n");
657 if (__pcap_io->prepare_access_pcap) {
658 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_RD, ctx->jumbo);
659 if (ret)
660 panic("Error prepare reading pcap!\n");
663 fmemset(&fm, 0, sizeof(fm));
665 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
666 if (ctx->dump_bpf)
667 bpf_dump_all(&bpf_ops);
669 dissector_init_all(ctx->print_mode);
671 out_len = round_up(1024 * 1024, RUNTIME_PAGE_SIZE);
672 out = xmalloc_aligned(out_len, CO_CACHE_LINE_SIZE);
674 if (ctx->device_out) {
675 if (!strncmp("-", ctx->device_out, strlen("-"))) {
676 fdo = dup_or_die(fileno(stdout));
677 close(fileno(stdout));
678 } else {
679 fdo = open_or_die_m(ctx->device_out, O_RDWR | O_CREAT |
680 O_TRUNC | O_LARGEFILE, DEFFILEMODE);
684 if (is_out_pcap) {
685 ret = pcap_out_ops->push_fhdr_pcap(fdo, ctx->magic,
686 ctx->link_type);
687 if (ret)
688 panic("Error writing pcap header!\n");
691 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
693 printf("Running! Hang up with ^C!\n\n");
694 fflush(stdout);
696 bug_on(gettimeofday(&start, NULL));
698 while (likely(sigint == 0)) {
699 do {
700 ret = __pcap_io->read_pcap(fd, &phdr, ctx->magic,
701 out, out_len);
702 if (unlikely(ret < 0))
703 goto out;
705 if (unlikely(pcap_get_length(&phdr, ctx->magic) == 0)) {
706 trunced++;
707 continue;
710 if (unlikely(pcap_get_length(&phdr, ctx->magic) > out_len)) {
711 pcap_set_length(&phdr, ctx->magic, out_len);
712 trunced++;
714 } while (ctx->filter &&
715 !bpf_run_filter(&bpf_ops, out,
716 pcap_get_length(&phdr, ctx->magic)));
718 pcap_pkthdr_to_tpacket_hdr(&phdr, ctx->magic, &fm.tp_h, &fm.s_ll);
720 ctx->tx_bytes += fm.tp_h.tp_len;
721 ctx->tx_packets++;
723 show_frame_hdr(out, fm.tp_h.tp_snaplen, ctx->link_type, &fm,
724 ctx->print_mode, ctx->tx_packets);
726 dissector_entry_point(out, fm.tp_h.tp_snaplen,
727 ctx->link_type, ctx->print_mode,
728 &fm.s_ll);
730 if (is_out_pcap) {
731 size_t pcap_len = pcap_get_length(&phdr, ctx->magic);
732 int wlen = pcap_out_ops->write_pcap(fdo, &phdr,
733 ctx->magic, out,
734 pcap_len);
735 if (unlikely(wlen != (int)pcap_get_total_length(&phdr, ctx->magic)))
736 panic("Error writing to pcap!\n");
737 } else if (ctx->device_out) {
738 translate_pcap_to_txf(fdo, out, fm.tp_h.tp_snaplen);
741 if (frame_count_max != 0) {
742 if (ctx->tx_packets >= frame_count_max) {
743 sigint = 1;
744 break;
749 out:
750 bug_on(gettimeofday(&end, NULL));
751 timersub(&end, &start, &diff);
753 bpf_release(&bpf_ops);
755 dissector_cleanup_all();
757 if (__pcap_io->prepare_close_pcap)
758 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_RD);
760 xfree(out);
762 fflush(stdout);
763 printf("\n");
764 printf("\r%12lu packets outgoing\n", ctx->tx_packets);
765 printf("\r%12lu packets truncated in file\n", trunced);
766 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
767 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
769 if (!strncmp("-", ctx->device_in, strlen("-")))
770 dup2(fd, fileno(stdin));
771 close(fd);
773 if (ctx->device_out) {
774 if (!strncmp("-", ctx->device_out, strlen("-")))
775 dup2(fdo, fileno(stdout));
776 close(fdo);
780 static void finish_multi_pcap_file(struct ctx *ctx, int fd)
782 __pcap_io->fsync_pcap(fd);
784 if (__pcap_io->prepare_close_pcap)
785 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
787 close(fd);
789 fmemset(&itimer, 0, sizeof(itimer));
790 setitimer(ITIMER_REAL, &itimer, NULL);
793 static int next_multi_pcap_file(struct ctx *ctx, int fd)
795 int ret;
796 char fname[512];
797 time_t ftime;
799 __pcap_io->fsync_pcap(fd);
801 if (__pcap_io->prepare_close_pcap)
802 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
804 close(fd);
806 if (sighup_time > 0) {
807 ftime = (time_t)(start_time + sighup_time);
808 sighup_time = 0;
809 } else
810 ftime = time(NULL);
812 slprintf(fname, sizeof(fname), "%s/%s%lu.pcap", ctx->device_out,
813 ctx->prefix ? : "dump-", ftime);
815 fd = open_or_die_m(fname, O_RDWR | O_CREAT | O_TRUNC |
816 O_LARGEFILE, DEFFILEMODE);
818 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
819 if (ret)
820 panic("Error writing pcap header!\n");
822 if (__pcap_io->prepare_access_pcap) {
823 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
824 if (ret)
825 panic("Error prepare writing pcap!\n");
828 return fd;
831 static void reset_interval(struct ctx *ctx)
833 if (ctx->dump_mode == DUMP_INTERVAL_TIME) {
834 interval = ctx->dump_interval;
836 set_itimer_interval_value(&itimer, interval, 0);
837 setitimer(ITIMER_REAL, &itimer, NULL);
838 } else {
839 interval = 0;
843 static int begin_multi_pcap_file(struct ctx *ctx)
845 int fd, ret;
846 char fname[256];
848 bug_on(!__pcap_io);
850 if (ctx->device_out[strlen(ctx->device_out) - 1] == '/')
851 ctx->device_out[strlen(ctx->device_out) - 1] = 0;
853 slprintf(fname, sizeof(fname), "%s/%s%lu.pcap", ctx->device_out,
854 ctx->prefix ? : "dump-", time(NULL));
856 fd = open_or_die_m(fname, O_RDWR | O_CREAT | O_TRUNC |
857 O_LARGEFILE, DEFFILEMODE);
859 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
860 if (ret)
861 panic("Error writing pcap header!\n");
863 if (__pcap_io->prepare_access_pcap) {
864 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
865 if (ret)
866 panic("Error prepare writing pcap!\n");
869 reset_interval(ctx);
871 return fd;
874 static void finish_single_pcap_file(struct ctx *ctx, int fd)
876 __pcap_io->fsync_pcap(fd);
878 if (__pcap_io->prepare_close_pcap)
879 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
881 if (strncmp("-", ctx->device_out, strlen("-")))
882 close(fd);
883 else
884 dup2(fd, fileno(stdout));
887 static int begin_single_pcap_file(struct ctx *ctx)
889 int fd, ret;
891 bug_on(!__pcap_io);
893 if (!strncmp("-", ctx->device_out, strlen("-"))) {
894 fd = dup_or_die(fileno(stdout));
895 close(fileno(stdout));
896 if (ctx->pcap == PCAP_OPS_MM)
897 ctx->pcap = PCAP_OPS_SG;
898 } else {
899 fd = open_or_die_m(ctx->device_out,
900 O_RDWR | O_CREAT | O_TRUNC |
901 O_LARGEFILE, DEFFILEMODE);
904 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
905 if (ret)
906 panic("Error writing pcap header!\n");
908 if (__pcap_io->prepare_access_pcap) {
909 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
910 if (ret)
911 panic("Error prepare writing pcap!\n");
914 return fd;
917 static void update_pcap_next_dump(struct ctx *ctx, unsigned long snaplen,
918 int *fd, int sock, bool is_v3)
920 if (!dump_to_pcap(ctx))
921 return;
923 if (ctx->dump_mode == DUMP_INTERVAL_SIZE) {
924 interval += snaplen;
925 if (interval > ctx->dump_interval) {
926 next_dump = true;
927 interval = 0;
931 if (sighup) {
932 if (ctx->verbose)
933 printf("SIGHUP received, prematurely rotating pcap\n");
934 sighup = 0;
935 next_dump = true;
936 reset_interval(ctx);
939 if (next_dump) {
940 *fd = next_multi_pcap_file(ctx, *fd);
941 next_dump = false;
943 if (update_rx_stats(ctx, sock, is_v3))
944 return;
946 if (ctx->verbose && ctx->print_mode == PRINT_NONE)
947 printf(".(+%"PRIu64"/-%"PRIu64")",
948 ctx->pkts_recvd_last - ctx->pkts_drops_last,
949 ctx->pkts_drops_last);
953 #ifdef HAVE_TPACKET3
954 static void walk_t3_block(struct block_desc *pbd, struct ctx *ctx,
955 int sock, int *fd)
957 int num_pkts = pbd->h1.num_pkts, i;
958 struct tpacket3_hdr *hdr;
959 struct sockaddr_ll *sll;
961 hdr = (void *) ((uint8_t *) pbd + pbd->h1.offset_to_first_pkt);
962 sll = (void *) ((uint8_t *) hdr + TPACKET_ALIGN(sizeof(*hdr)));
964 for (i = 0; i < num_pkts && likely(sigint == 0); ++i) {
965 uint8_t *packet = ((uint8_t *) hdr + hdr->tp_mac);
966 pcap_pkthdr_t phdr;
968 if (skip_packet(ctx, sll))
969 goto next;
971 ctx->pkts_seen++;
973 if (dump_to_pcap(ctx)) {
974 int ret;
976 tpacket3_hdr_to_pcap_pkthdr(hdr, sll, &phdr, ctx->magic);
978 ret = __pcap_io->write_pcap(*fd, &phdr, ctx->magic, packet,
979 pcap_get_length(&phdr, ctx->magic));
980 if (unlikely(ret != (int) pcap_get_total_length(&phdr, ctx->magic)))
981 panic("Write error to pcap!\n");
984 __show_frame_hdr(packet, hdr->tp_snaplen, ctx->link_type, sll,
985 hdr, ctx->print_mode, true, ctx->pkts_seen);
987 dissector_entry_point(packet, hdr->tp_snaplen, ctx->link_type,
988 ctx->print_mode, sll);
989 next:
990 hdr = (void *) ((uint8_t *) hdr + hdr->tp_next_offset);
991 sll = (void *) ((uint8_t *) hdr + TPACKET_ALIGN(sizeof(*hdr)));
993 if (frame_count_max != 0) {
994 if (unlikely(ctx->pkts_seen >= frame_count_max)) {
995 sigint = 1;
996 break;
1000 update_pcap_next_dump(ctx, hdr->tp_snaplen, fd, sock, true);
1003 #endif /* HAVE_TPACKET3 */
1005 static void recv_only_or_dump(struct ctx *ctx)
1007 short ifflags = 0;
1008 int sock, ifindex, fd = 0, ret;
1009 size_t size;
1010 unsigned int it = 0;
1011 struct ring rx_ring;
1012 struct pollfd rx_poll;
1013 struct sock_fprog bpf_ops;
1014 struct timeval start, end, diff;
1015 bool is_v3 = is_defined(HAVE_TPACKET3);
1017 sock = pf_socket_type(ctx->link_type);
1019 ifindex = device_ifindex(ctx->device_in);
1020 size = ring_size(ctx->device_in, ctx->reserve_size);
1022 enable_kernel_bpf_jit_compiler();
1024 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
1025 if (ctx->dump_bpf)
1026 bpf_dump_all(&bpf_ops);
1027 bpf_attach_to_sock(sock, &bpf_ops);
1029 if (ctx->hwtimestamp) {
1030 ret = set_sockopt_hwtimestamp(sock, ctx->device_in);
1031 if (ret == 0 && ctx->verbose)
1032 printf("HW timestamping enabled\n");
1035 ring_rx_setup(&rx_ring, sock, size, ifindex, &rx_poll, is_v3, true,
1036 ctx->verbose, ctx->fanout_group, ctx->fanout_type);
1038 dissector_init_all(ctx->print_mode);
1040 if (ctx->cpu >= 0 && ifindex > 0) {
1041 int irq = device_irq_number(ctx->device_in);
1042 device_set_irq_affinity(irq, ctx->cpu);
1044 if (ctx->verbose)
1045 printf("IRQ: %s:%d > CPU%d\n",
1046 ctx->device_in, irq, ctx->cpu);
1049 if (ctx->promiscuous)
1050 ifflags = device_enter_promiscuous_mode(ctx->device_in);
1052 if (dump_to_pcap(ctx) && __pcap_io->init_once_pcap)
1053 __pcap_io->init_once_pcap(true);
1055 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
1057 if (dump_to_pcap(ctx)) {
1058 struct stat stats;
1060 ret = stat(ctx->device_out, &stats);
1061 if (ret < 0)
1062 ctx->dump_dir = 0;
1063 else
1064 ctx->dump_dir = S_ISDIR(stats.st_mode);
1066 if (ctx->dump_dir)
1067 fd = begin_multi_pcap_file(ctx);
1068 else
1069 fd = begin_single_pcap_file(ctx);
1072 printf("Running! Hang up with ^C!\n\n");
1073 fflush(stdout);
1075 bug_on(gettimeofday(&start, NULL));
1077 while (likely(sigint == 0)) {
1078 #ifdef HAVE_TPACKET3
1079 struct block_desc *pbd;
1081 while (user_may_pull_from_rx_block((pbd = rx_ring.frames[it].iov_base))) {
1082 walk_t3_block(pbd, ctx, sock, &fd);
1084 kernel_may_pull_from_rx_block(pbd);
1085 it = (it + 1) % rx_ring.layout3.tp_block_nr;
1087 if (unlikely(sigint == 1))
1088 break;
1090 #else
1091 while (user_may_pull_from_rx(rx_ring.frames[it].iov_base)) {
1092 struct frame_map *hdr = rx_ring.frames[it].iov_base;
1093 uint8_t *packet = ((uint8_t *) hdr) + hdr->tp_h.tp_mac;
1094 pcap_pkthdr_t phdr;
1096 if (skip_packet(ctx, &hdr->s_ll))
1097 goto next;
1099 ctx->pkts_seen++;
1101 if (unlikely(ring_frame_size(&rx_ring) < hdr->tp_h.tp_snaplen)) {
1102 /* XXX: silently ignore for now. We used to
1103 * report them with dump_rx_stats() */
1104 goto next;
1107 if (dump_to_pcap(ctx)) {
1108 tpacket_hdr_to_pcap_pkthdr(&hdr->tp_h, &hdr->s_ll, &phdr, ctx->magic);
1110 ret = __pcap_io->write_pcap(fd, &phdr, ctx->magic, packet,
1111 pcap_get_length(&phdr, ctx->magic));
1112 if (unlikely(ret != (int) pcap_get_total_length(&phdr, ctx->magic)))
1113 panic("Write error to pcap!\n");
1116 show_frame_hdr(packet, hdr->tp_h.tp_snaplen,
1117 ctx->link_type, hdr, ctx->print_mode,
1118 ctx->pkts_seen);
1120 dissector_entry_point(packet, hdr->tp_h.tp_snaplen,
1121 ctx->link_type, ctx->print_mode,
1122 &hdr->s_ll);
1124 if (frame_count_max != 0) {
1125 if (unlikely(ctx->pkts_seen >= frame_count_max)) {
1126 sigint = 1;
1127 break;
1131 next:
1132 kernel_may_pull_from_rx(&hdr->tp_h);
1133 it = (it + 1) % rx_ring.layout.tp_frame_nr;
1135 if (unlikely(sigint == 1))
1136 break;
1138 update_pcap_next_dump(ctx, hdr->tp_h.tp_snaplen, &fd,
1139 sock, is_v3);
1141 #endif /* HAVE_TPACKET3 */
1143 ret = poll(&rx_poll, 1, -1);
1144 if (unlikely(ret < 0)) {
1145 if (errno != EINTR)
1146 panic("Poll failed!\n");
1150 bug_on(gettimeofday(&end, NULL));
1151 timersub(&end, &start, &diff);
1153 dump_rx_stats(ctx, sock, is_v3);
1154 printf("\r%12lu sec, %lu usec in total\n",
1155 diff.tv_sec, diff.tv_usec);
1157 bpf_release(&bpf_ops);
1158 dissector_cleanup_all();
1159 destroy_rx_ring(sock, &rx_ring);
1161 if (ctx->promiscuous)
1162 device_leave_promiscuous_mode(ctx->device_in, ifflags);
1164 if (ctx->rfraw)
1165 leave_rfmon_mac80211(ctx->device_in);
1167 if (dump_to_pcap(ctx)) {
1168 if (ctx->dump_dir)
1169 finish_multi_pcap_file(ctx, fd);
1170 else
1171 finish_single_pcap_file(ctx, fd);
1174 close(sock);
1177 static void init_ctx(struct ctx *ctx)
1179 memset(ctx, 0, sizeof(*ctx));
1181 ctx->uid = getuid();
1182 ctx->gid = getgid();
1184 ctx->cpu = -1;
1185 ctx->packet_type = -1;
1187 ctx->fanout_type = PACKET_FANOUT_ROLLOVER;
1189 ctx->magic = ORIGINAL_TCPDUMP_MAGIC;
1190 ctx->print_mode = PRINT_NORM;
1191 ctx->pcap = PCAP_OPS_SG;
1193 ctx->dump_mode = DUMP_INTERVAL_TIME;
1194 ctx->dump_interval = 60;
1196 ctx->promiscuous = true;
1197 ctx->randomize = false;
1198 ctx->hwtimestamp = true;
1200 ctx->pkts_recvd = 0;
1201 ctx->pkts_seen = 0;
1202 ctx->pkts_drops = 0;
1203 ctx->pkts_recvd_last = 0;
1204 ctx->pkts_drops_last = 0;
1207 static void destroy_ctx(struct ctx *ctx)
1209 free(ctx->device_in);
1210 free(ctx->device_out);
1211 free(ctx->device_trans);
1213 free(ctx->prefix);
1216 static void __noreturn help(void)
1218 printf("netsniff-ng %s, the packet sniffing beast\n", VERSION_STRING);
1219 puts("http://www.netsniff-ng.org\n\n"
1220 "Usage: netsniff-ng [options] [filter-expression]\n"
1221 "Options:\n"
1222 " -i|-d|--dev|--in <dev|pcap|-> Input source as netdev, pcap or pcap stdin\n"
1223 " -o|--out <dev|pcap|dir|cfg|-> Output sink as netdev, pcap, directory, trafgen, or stdout\n"
1224 " -C|--fanout-group <id> Join packet fanout group\n"
1225 " -K|--fanout-type <type> Apply fanout discipline: hash|lb|cpu|rnd|roll|qm\n"
1226 " -L|--fanout-opts <opts> Additional fanout options: defrag|roll\n"
1227 " -f|--filter <bpf-file|-|expr> Use BPF filter from bpfc file/stdin or tcpdump-like expression\n"
1228 " -t|--type <type> Filter for: host|broadcast|multicast|others|outgoing\n"
1229 " -F|--interval <size|time> Dump interval if -o is a dir: <num>KiB/MiB/GiB/s/sec/min/hrs\n"
1230 " -R|--rfraw Capture or inject raw 802.11 frames\n"
1231 " -n|--num <0|uint> Number of packets until exit (def: 0)\n"
1232 " -P|--prefix <name> Prefix for pcaps stored in directory\n"
1233 " -T|--magic <pcap-magic> Pcap magic number/pcap format to store, see -D\n"
1234 " -w|--cooked Use Linux \"cooked\" header instead of link header\n"
1235 " -D|--dump-pcap-types Dump pcap types and magic numbers and quit\n"
1236 " -B|--dump-bpf Dump generated BPF assembly\n"
1237 " -r|--rand Randomize packet forwarding order (dev->dev)\n"
1238 " -M|--no-promisc No promiscuous mode for netdev\n"
1239 " -A|--no-sock-mem Don't tune core socket memory\n"
1240 " -N|--no-hwtimestamp Disable hardware time stamping\n"
1241 " -m|--mmap Mmap(2) pcap file I/O, e.g. for replaying pcaps\n"
1242 " -G|--sg Scatter/gather pcap file I/O\n"
1243 " -c|--clrw Use slower read(2)/write(2) I/O\n"
1244 " -S|--ring-size <size> Specify ring size to: <num>KiB/MiB/GiB\n"
1245 " -k|--kernel-pull <uint> Kernel pull from user interval in us (def: 10us)\n"
1246 " -J|--jumbo-support Support replay/fwd 64KB Super Jumbo Frames (def: 2048B)\n"
1247 " -b|--bind-cpu <cpu> Bind to specific CPU\n"
1248 " -u|--user <userid> Drop privileges and change to userid\n"
1249 " -g|--group <groupid> Drop privileges and change to groupid\n"
1250 " -H|--prio-high Make this high priority process\n"
1251 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
1252 " -s|--silent Do not print captured packets\n"
1253 " -q|--less Print less-verbose packet information\n"
1254 " -X|--hex Print packet data in hex format\n"
1255 " -l|--ascii Print human-readable packet data\n"
1256 " -U|--update Update GeoIP databases\n"
1257 " -V|--verbose Be more verbose\n"
1258 " -v|--version Show version and exit\n"
1259 " -h|--help Guess what?!\n\n"
1260 "Examples:\n"
1261 " netsniff-ng --in eth0 --out dump.pcap -s -T 0xa1b2c3d4 --b 0 tcp or udp\n"
1262 " netsniff-ng --in wlan0 --rfraw --out dump.pcap --silent --bind-cpu 0\n"
1263 " netsniff-ng --in dump.pcap --mmap --out eth0 -k1000 --silent --bind-cpu 0\n"
1264 " netsniff-ng --in dump.pcap --out dump.cfg --silent --bind-cpu 0\n"
1265 " netsniff-ng --in dump.pcap --out dump2.pcap --silent tcp\n"
1266 " netsniff-ng --in eth0 --out eth1 --silent --bind-cpu 0 -J --type host\n"
1267 " netsniff-ng --in eth1 --out /opt/probe/ -s -m --interval 100MiB -b 0\n"
1268 " netsniff-ng --in vlan0 --out dump.pcap -c -u `id -u bob` -g `id -g bob`\n"
1269 " netsniff-ng --in any --filter http.bpf --jumbo-support --ascii -V\n\n"
1270 "Note:\n"
1271 " For introducing bit errors, delays with random variation and more\n"
1272 " while replaying pcaps, make use of tc(8) with its disciplines (e.g. netem).\n");
1273 puts(copyright);
1274 die();
1277 static void __noreturn version(void)
1279 printf("netsniff-ng %s, Git id: %s\n", VERSION_LONG, GITVERSION);
1280 puts("the packet sniffing beast\n"
1281 "http://www.netsniff-ng.org\n");
1282 puts(copyright);
1283 die();
1286 int main(int argc, char **argv)
1288 char *ptr;
1289 int c, i, j, cpu_tmp, opt_index, ops_touched = 0, vals[4] = {0};
1290 bool prio_high = false, setsockmem = true;
1291 void (*main_loop)(struct ctx *ctx) = NULL;
1292 struct ctx ctx;
1294 init_ctx(&ctx);
1295 start_time = time(NULL);
1296 srand(start_time);
1298 while ((c = getopt_long(argc, argv, short_options, long_options,
1299 &opt_index)) != EOF) {
1300 switch (c) {
1301 case 'd':
1302 case 'i':
1303 ctx.device_in = xstrdup(optarg);
1304 break;
1305 case 'o':
1306 ctx.device_out = xstrdup(optarg);
1307 break;
1308 case 'P':
1309 ctx.prefix = xstrdup(optarg);
1310 break;
1311 case 'R':
1312 ctx.rfraw = 1;
1313 break;
1314 case 'r':
1315 ctx.randomize = true;
1316 break;
1317 case 'J':
1318 ctx.jumbo = true;
1319 break;
1320 case 'T':
1321 ctx.magic = (uint32_t) strtoul(optarg, NULL, 0);
1322 pcap_check_magic(ctx.magic);
1323 break;
1324 case 'f':
1325 ctx.filter = xstrdup(optarg);
1326 break;
1327 case 'M':
1328 ctx.promiscuous = false;
1329 break;
1330 case 'N':
1331 ctx.hwtimestamp = false;
1332 break;
1333 case 'A':
1334 setsockmem = false;
1335 break;
1336 case 'u':
1337 ctx.uid = strtoul(optarg, NULL, 0);
1338 ctx.enforce = true;
1339 break;
1340 case 'g':
1341 ctx.gid = strtoul(optarg, NULL, 0);
1342 ctx.enforce = true;
1343 break;
1344 case 'C':
1345 ctx.fanout_group = strtoul(optarg, NULL, 0);
1346 if (ctx.fanout_group == 0)
1347 panic("Non-zero fanout group id required!\n");
1348 break;
1349 case 'K':
1350 if (!strncmp(optarg, "hash", strlen("hash")))
1351 ctx.fanout_type = PACKET_FANOUT_HASH;
1352 else if (!strncmp(optarg, "lb", strlen("lb")) ||
1353 !strncmp(optarg, "rr", strlen("rr")))
1354 ctx.fanout_type = PACKET_FANOUT_LB;
1355 else if (!strncmp(optarg, "cpu", strlen("cpu")))
1356 ctx.fanout_type = PACKET_FANOUT_CPU;
1357 else if (!strncmp(optarg, "rnd", strlen("rnd")))
1358 ctx.fanout_type = PACKET_FANOUT_RND;
1359 else if (!strncmp(optarg, "roll", strlen("roll")))
1360 ctx.fanout_type = PACKET_FANOUT_ROLLOVER;
1361 else if (!strncmp(optarg, "qm", strlen("qm")))
1362 ctx.fanout_type = PACKET_FANOUT_QM;
1363 else
1364 panic("Unknown fanout type!\n");
1365 break;
1366 case 'L':
1367 if (!strncmp(optarg, "defrag", strlen("defrag")))
1368 ctx.fanout_type |= PACKET_FANOUT_FLAG_DEFRAG;
1369 else if (!strncmp(optarg, "roll", strlen("roll")))
1370 ctx.fanout_type |= PACKET_FANOUT_FLAG_ROLLOVER;
1371 else
1372 panic("Unknown fanout option!\n");
1373 break;
1374 case 't':
1375 if (!strncmp(optarg, "host", strlen("host")))
1376 ctx.packet_type = PACKET_HOST;
1377 else if (!strncmp(optarg, "broadcast", strlen("broadcast")))
1378 ctx.packet_type = PACKET_BROADCAST;
1379 else if (!strncmp(optarg, "multicast", strlen("multicast")))
1380 ctx.packet_type = PACKET_MULTICAST;
1381 else if (!strncmp(optarg, "others", strlen("others")))
1382 ctx.packet_type = PACKET_OTHERHOST;
1383 else if (!strncmp(optarg, "outgoing", strlen("outgoing")))
1384 ctx.packet_type = PACKET_OUTGOING;
1385 else
1386 ctx.packet_type = -1;
1387 break;
1388 case 'S':
1389 ptr = optarg;
1390 for (j = i = strlen(optarg); i > 0; --i) {
1391 if (!isdigit(optarg[j - i]))
1392 break;
1393 ptr++;
1396 if (!strncmp(ptr, "KiB", strlen("KiB")))
1397 ctx.reserve_size = 1 << 10;
1398 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1399 ctx.reserve_size = 1 << 20;
1400 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1401 ctx.reserve_size = 1 << 30;
1402 else
1403 panic("Syntax error in ring size param!\n");
1405 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1406 break;
1407 case 'b':
1408 cpu_tmp = strtol(optarg, NULL, 0);
1410 cpu_affinity(cpu_tmp);
1411 if (ctx.cpu != -2)
1412 ctx.cpu = cpu_tmp;
1413 break;
1414 case 'H':
1415 prio_high = true;
1416 break;
1417 case 'c':
1418 ctx.pcap = PCAP_OPS_RW;
1419 ops_touched = 1;
1420 break;
1421 case 'm':
1422 ctx.pcap = PCAP_OPS_MM;
1423 ops_touched = 1;
1424 break;
1425 case 'G':
1426 ctx.pcap = PCAP_OPS_SG;
1427 ops_touched = 1;
1428 break;
1429 case 'Q':
1430 ctx.cpu = -2;
1431 break;
1432 case 's':
1433 ctx.print_mode = PRINT_NONE;
1434 break;
1435 case 'q':
1436 ctx.print_mode = PRINT_LESS;
1437 break;
1438 case 'X':
1439 ctx.print_mode =
1440 (ctx.print_mode == PRINT_ASCII) ?
1441 PRINT_HEX_ASCII : PRINT_HEX;
1442 break;
1443 case 'l':
1444 ctx.print_mode =
1445 (ctx.print_mode == PRINT_HEX) ?
1446 PRINT_HEX_ASCII : PRINT_ASCII;
1447 break;
1448 case 'k':
1449 ctx.kpull = strtoul(optarg, NULL, 0);
1450 break;
1451 case 'n':
1452 frame_count_max = strtoul(optarg, NULL, 0);
1453 break;
1454 case 'F':
1455 ptr = optarg;
1456 for (j = i = strlen(optarg); i > 0; --i) {
1457 if (!isdigit(optarg[j - i]))
1458 break;
1459 ptr++;
1462 if (!strncmp(ptr, "KiB", strlen("KiB"))) {
1463 ctx.dump_interval = 1 << 10;
1464 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1465 } else if (!strncmp(ptr, "MiB", strlen("MiB"))) {
1466 ctx.dump_interval = 1 << 20;
1467 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1468 } else if (!strncmp(ptr, "GiB", strlen("GiB"))) {
1469 ctx.dump_interval = 1 << 30;
1470 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1471 } else if (!strncmp(ptr, "sec", strlen("sec"))) {
1472 ctx.dump_interval = 1;
1473 ctx.dump_mode = DUMP_INTERVAL_TIME;
1474 } else if (!strncmp(ptr, "min", strlen("min"))) {
1475 ctx.dump_interval = 60;
1476 ctx.dump_mode = DUMP_INTERVAL_TIME;
1477 } else if (!strncmp(ptr, "hrs", strlen("hrs"))) {
1478 ctx.dump_interval = 60 * 60;
1479 ctx.dump_mode = DUMP_INTERVAL_TIME;
1480 } else if (!strncmp(ptr, "s", strlen("s"))) {
1481 ctx.dump_interval = 1;
1482 ctx.dump_mode = DUMP_INTERVAL_TIME;
1483 } else {
1484 panic("Syntax error in time/size param!\n");
1487 ctx.dump_interval *= strtoul(optarg, NULL, 0);
1488 break;
1489 case 'V':
1490 ctx.verbose = true;
1491 break;
1492 case 'B':
1493 ctx.dump_bpf = true;
1494 break;
1495 case 'D':
1496 pcap_dump_type_features();
1497 die();
1498 break;
1499 case 'U':
1500 update_geoip();
1501 die();
1502 break;
1503 case 'w':
1504 ctx.link_type = LINKTYPE_LINUX_SLL;
1505 break;
1506 case 'v':
1507 version();
1508 break;
1509 case 'h':
1510 help();
1511 break;
1512 case '?':
1513 switch (optopt) {
1514 case 'd':
1515 case 'i':
1516 case 'o':
1517 case 'f':
1518 case 't':
1519 case 'P':
1520 case 'F':
1521 case 'n':
1522 case 'S':
1523 case 'b':
1524 case 'k':
1525 case 'T':
1526 case 'u':
1527 case 'g':
1528 case 'e':
1529 panic("Option -%c requires an argument!\n",
1530 optopt);
1531 default:
1532 if (isprint(optopt))
1533 printf("Unknown option character `0x%X\'!\n", optopt);
1534 die();
1536 default:
1537 break;
1541 if (!ctx.filter && optind != argc)
1542 ctx.filter = argv2str(optind, argc, argv);
1544 if (!ctx.device_in)
1545 ctx.device_in = xstrdup("any");
1547 if (!strcmp(ctx.device_in, "any") || !strcmp(ctx.device_in, "lo"))
1548 ctx.lo_ifindex = device_ifindex("lo");
1550 register_signal(SIGINT, signal_handler);
1551 register_signal(SIGQUIT, signal_handler);
1552 register_signal(SIGTERM, signal_handler);
1553 register_signal(SIGHUP, signal_handler);
1555 tprintf_init();
1557 if (prio_high) {
1558 set_proc_prio(-20);
1559 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1562 if (device_mtu(ctx.device_in) || !strncmp("any", ctx.device_in, strlen(ctx.device_in))) {
1563 if (ctx.rfraw)
1564 setup_rfmon_mac80211_dev(&ctx, &ctx.device_in);
1566 if (!ctx.link_type)
1567 ctx.link_type = pcap_dev_to_linktype(ctx.device_in);
1568 if (link_has_sll_hdr(ctx.link_type)) {
1569 switch (ctx.magic) {
1570 case ORIGINAL_TCPDUMP_MAGIC:
1571 ctx.magic = ORIGINAL_TCPDUMP_MAGIC_LL;
1572 break;
1573 case NSEC_TCPDUMP_MAGIC:
1574 ctx.magic = NSEC_TCPDUMP_MAGIC_LL;
1575 break;
1576 case ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC):
1577 ctx.magic = ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC_LL);
1578 break;
1579 case ___constant_swab32(NSEC_TCPDUMP_MAGIC):
1580 ctx.magic = ___constant_swab32(NSEC_TCPDUMP_MAGIC_LL);
1581 break;
1586 if (!ctx.device_out) {
1587 ctx.dump = 0;
1588 main_loop = recv_only_or_dump;
1589 } else if (device_mtu(ctx.device_out)) {
1590 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1591 main_loop = receive_to_xmit;
1592 } else {
1593 ctx.dump = 1;
1594 register_signal_f(SIGALRM, timer_next_dump, SA_SIGINFO);
1595 main_loop = recv_only_or_dump;
1596 if (!ops_touched)
1597 ctx.pcap = PCAP_OPS_SG;
1599 } else {
1600 if (ctx.device_out && device_mtu(ctx.device_out)) {
1601 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1602 main_loop = pcap_to_xmit;
1603 if (!ops_touched)
1604 ctx.pcap = PCAP_OPS_MM;
1605 } else {
1606 setsockmem = false;
1607 main_loop = read_pcap;
1608 if (!ops_touched)
1609 ctx.pcap = PCAP_OPS_SG;
1613 bug_on(!main_loop);
1615 init_geoip(0);
1616 if (setsockmem)
1617 set_system_socket_memory(vals, array_size(vals));
1618 if (!ctx.enforce)
1619 xlockme();
1621 if (ctx.verbose)
1622 printf("pcap file I/O method: %s\n", pcap_ops_group_to_str[ctx.pcap]);
1624 main_loop(&ctx);
1626 if (!ctx.enforce)
1627 xunlockme();
1628 if (setsockmem)
1629 reset_system_socket_memory(vals, array_size(vals));
1630 destroy_geoip();
1632 device_restore_irq_affinity_list();
1633 tprintf_cleanup();
1635 destroy_ctx(&ctx);
1636 return 0;