netsniff-ng: dissector_sll: Fix potential NULL dereference
[netsniff-ng.git] / netsniff-ng.c
blobefcba74ba5b40625895b64c70c8301119b7360ed
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>
26 #include "ring_rx.h"
27 #include "ring_tx.h"
28 #include "mac80211.h"
29 #include "dev.h"
30 #include "built_in.h"
31 #include "pcap_io.h"
32 #include "privs.h"
33 #include "proc.h"
34 #include "bpf.h"
35 #include "ioops.h"
36 #include "die.h"
37 #include "irq.h"
38 #include "str.h"
39 #include "sig.h"
40 #include "config.h"
41 #include "sock.h"
42 #include "geoip.h"
43 #include "lockme.h"
44 #include "tprintf.h"
45 #include "timer.h"
46 #include "tstamping.h"
47 #include "dissector.h"
48 #include "xmalloc.h"
50 enum dump_mode {
51 DUMP_INTERVAL_TIME,
52 DUMP_INTERVAL_SIZE,
55 struct ctx {
56 char *device_in, *device_out, *device_trans, *filter, *prefix;
57 int cpu, rfraw, dump, print_mode, dump_dir, packet_type;
58 unsigned long kpull, dump_interval, tx_bytes, tx_packets;
59 size_t reserve_size;
60 bool randomize, promiscuous, enforce, jumbo, dump_bpf, hwtimestamp, verbose;
61 enum pcap_ops_groups pcap;
62 enum dump_mode dump_mode;
63 uid_t uid;
64 gid_t gid;
65 uint32_t link_type, magic;
66 uint32_t fanout_group, fanout_type;
69 static volatile sig_atomic_t sigint = 0, sighup = 0;
70 static volatile bool next_dump = false;
72 static const char *short_options =
73 "d:i:o:rf:MNJt:S:k:n:b:HQmcsqXlvhF:RGAP:Vu:g:T:DBUC:K:L:w";
74 static const struct option long_options[] = {
75 {"dev", required_argument, NULL, 'd'},
76 {"in", required_argument, NULL, 'i'},
77 {"out", required_argument, NULL, 'o'},
78 {"filter", required_argument, NULL, 'f'},
79 {"num", required_argument, NULL, 'n'},
80 {"type", required_argument, NULL, 't'},
81 {"interval", required_argument, NULL, 'F'},
82 {"ring-size", required_argument, NULL, 'S'},
83 {"kernel-pull", required_argument, NULL, 'k'},
84 {"bind-cpu", required_argument, NULL, 'b'},
85 {"prefix", required_argument, NULL, 'P'},
86 {"user", required_argument, NULL, 'u'},
87 {"group", required_argument, NULL, 'g'},
88 {"magic", required_argument, NULL, 'T'},
89 {"fanout-group", required_argument, NULL, 'C'},
90 {"fanout-type", required_argument, NULL, 'K'},
91 {"fanout-opts", required_argument, NULL, 'L'},
92 {"rand", no_argument, NULL, 'r'},
93 {"rfraw", no_argument, NULL, 'R'},
94 {"mmap", no_argument, NULL, 'm'},
95 {"sg", no_argument, NULL, 'G'},
96 {"clrw", no_argument, NULL, 'c'},
97 {"jumbo-support", no_argument, NULL, 'J'},
98 {"no-promisc", no_argument, NULL, 'M'},
99 {"no-hwtimestamp", no_argument, NULL, 'N'},
100 {"prio-high", no_argument, NULL, 'H'},
101 {"notouch-irq", no_argument, NULL, 'Q'},
102 {"dump-pcap-types", no_argument, NULL, 'D'},
103 {"dump-bpf", no_argument, NULL, 'B'},
104 {"silent", no_argument, NULL, 's'},
105 {"less", no_argument, NULL, 'q'},
106 {"hex", no_argument, NULL, 'X'},
107 {"ascii", no_argument, NULL, 'l'},
108 {"no-sock-mem", no_argument, NULL, 'A'},
109 {"update", no_argument, NULL, 'U'},
110 {"cooked", no_argument, NULL, 'w'},
111 {"verbose", no_argument, NULL, 'V'},
112 {"version", no_argument, NULL, 'v'},
113 {"help", no_argument, NULL, 'h'},
114 {NULL, 0, NULL, 0}
117 static const char *copyright = "Please report bugs to <bugs@netsniff-ng.org>\n"
118 "Copyright (C) 2009-2013 Daniel Borkmann <dborkma@tik.ee.ethz.ch>\n"
119 "Copyright (C) 2009-2012 Emmanuel Roullit <emmanuel.roullit@gmail.com>\n"
120 "Copyright (C) 2012 Markus Amend <markus@netsniff-ng.org>\n"
121 "Swiss federal institute of technology (ETH Zurich)\n"
122 "License: GNU GPL version 2.0\n"
123 "This is free software: you are free to change and redistribute it.\n"
124 "There is NO WARRANTY, to the extent permitted by law.";
126 static int tx_sock;
127 static struct itimerval itimer;
128 static unsigned long frame_count_max = 0, interval = TX_KERNEL_PULL_INT;
130 #define __pcap_io pcap_ops[ctx->pcap]
132 static void signal_handler(int number)
134 switch (number) {
135 case SIGINT:
136 case SIGQUIT:
137 case SIGTERM:
138 sigint = 1;
139 break;
140 case SIGHUP:
141 sighup = 1;
142 break;
143 default:
144 break;
148 static void timer_elapsed(int unused __maybe_unused)
150 int ret;
152 set_itimer_interval_value(&itimer, 0, interval);
154 ret = pull_and_flush_tx_ring(tx_sock);
155 if (unlikely(ret < 0)) {
156 /* We could hit EBADF if the socket has been closed before
157 * the timer was triggered.
159 if (errno != EBADF && errno != ENOBUFS)
160 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
163 setitimer(ITIMER_REAL, &itimer, NULL);
166 static void timer_purge(void)
168 int ret;
170 ret = pull_and_flush_tx_ring_wait(tx_sock);
171 if (unlikely(ret < 0)) {
172 if (errno != EBADF && errno != ENOBUFS)
173 panic("Flushing TX_RING failed: %s!\n", strerror(errno));
176 set_itimer_interval_value(&itimer, 0, 0);
177 setitimer(ITIMER_REAL, &itimer, NULL);
180 static void timer_next_dump(int unused __maybe_unused)
182 set_itimer_interval_value(&itimer, interval, 0);
183 next_dump = true;
184 setitimer(ITIMER_REAL, &itimer, NULL);
187 static inline bool dump_to_pcap(struct ctx *ctx)
189 return ctx->dump;
192 static void on_panic_del_rfmon(void *arg)
194 leave_rfmon_mac80211(arg);
197 static inline void setup_rfmon_mac80211_dev(struct ctx *ctx, char **rfmon_dev)
199 ctx->device_trans = xstrdup(*rfmon_dev);
200 xfree(*rfmon_dev);
202 enter_rfmon_mac80211(ctx->device_trans, rfmon_dev);
203 panic_handler_add(on_panic_del_rfmon, *rfmon_dev);
206 static void pcap_to_xmit(struct ctx *ctx)
208 uint8_t *out = NULL;
209 int ifindex, fd = 0, ret;
210 size_t size;
211 unsigned int it = 0;
212 unsigned long trunced = 0;
213 struct ring tx_ring;
214 struct frame_map *hdr;
215 struct sock_fprog bpf_ops;
216 struct timeval start, end, diff;
217 pcap_pkthdr_t phdr;
219 if (!device_up_and_running(ctx->device_out) && !ctx->rfraw)
220 panic("Device not up and running!\n");
222 bug_on(!__pcap_io);
224 tx_sock = pf_socket();
226 if (!strncmp("-", ctx->device_in, strlen("-"))) {
227 fd = dup_or_die(fileno(stdin));
228 close(fileno(stdin));
229 if (ctx->pcap == PCAP_OPS_MM)
230 ctx->pcap = PCAP_OPS_SG;
231 } else {
232 fd = open_or_die(ctx->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
235 if (__pcap_io->init_once_pcap)
236 __pcap_io->init_once_pcap(true);
238 ret = __pcap_io->pull_fhdr_pcap(fd, &ctx->magic, &ctx->link_type);
239 if (ret)
240 panic("Error reading pcap header!\n");
242 if (__pcap_io->prepare_access_pcap) {
243 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_RD, ctx->jumbo);
244 if (ret)
245 panic("Error prepare reading pcap!\n");
248 if (ctx->rfraw) {
249 setup_rfmon_mac80211_dev(ctx, &ctx->device_out);
251 if (ctx->link_type != LINKTYPE_IEEE802_11 &&
252 ctx->link_type != LINKTYPE_IEEE802_11_RADIOTAP)
253 panic("Wrong linktype of pcap!\n");
256 ifindex = device_ifindex(ctx->device_out);
257 size = ring_size(ctx->device_out, ctx->reserve_size);
259 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
260 if (ctx->dump_bpf)
261 bpf_dump_all(&bpf_ops);
263 ring_tx_setup(&tx_ring, tx_sock, size, ifindex, ctx->jumbo, ctx->verbose);
265 dissector_init_all(ctx->print_mode);
267 if (ctx->cpu >= 0 && ifindex > 0) {
268 int irq = device_irq_number(ctx->device_out);
269 device_set_irq_affinity(irq, ctx->cpu);
271 if (ctx->verbose)
272 printf("IRQ: %s:%d > CPU%d\n",
273 ctx->device_out, irq, ctx->cpu);
276 if (ctx->kpull)
277 interval = ctx->kpull;
279 set_itimer_interval_value(&itimer, 0, interval);
280 setitimer(ITIMER_REAL, &itimer, NULL);
282 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
284 printf("Running! Hang up with ^C!\n\n");
285 fflush(stdout);
287 bug_on(gettimeofday(&start, NULL));
289 while (likely(sigint == 0)) {
290 while (user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
291 hdr = tx_ring.frames[it].iov_base;
292 out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
294 do {
295 ret = __pcap_io->read_pcap(fd, &phdr, ctx->magic, out,
296 ring_frame_size(&tx_ring));
297 if (unlikely(ret <= 0))
298 goto out;
300 if (ring_frame_size(&tx_ring) <
301 pcap_get_length(&phdr, ctx->magic)) {
302 pcap_set_length(&phdr, ctx->magic,
303 ring_frame_size(&tx_ring));
304 trunced++;
306 } while (ctx->filter &&
307 !bpf_run_filter(&bpf_ops, out,
308 pcap_get_length(&phdr, ctx->magic)));
310 pcap_pkthdr_to_tpacket_hdr(&phdr, ctx->magic, &hdr->tp_h, NULL);
312 ctx->tx_bytes += hdr->tp_h.tp_len;;
313 ctx->tx_packets++;
315 show_frame_hdr(out, hdr->tp_h.tp_snaplen,
316 ctx->link_type, hdr, ctx->print_mode,
317 ctx->tx_packets);
319 dissector_entry_point(out, hdr->tp_h.tp_snaplen,
320 ctx->link_type, ctx->print_mode,
321 &hdr->s_ll);
323 kernel_may_pull_from_tx(&hdr->tp_h);
325 it++;
326 if (it >= tx_ring.layout.tp_frame_nr)
327 it = 0;
329 if (unlikely(sigint == 1))
330 break;
332 if (frame_count_max != 0) {
333 if (ctx->tx_packets >= frame_count_max) {
334 sigint = 1;
335 break;
341 out:
342 bug_on(gettimeofday(&end, NULL));
343 timersub(&end, &start, &diff);
345 timer_purge();
347 bpf_release(&bpf_ops);
349 dissector_cleanup_all();
350 destroy_tx_ring(tx_sock, &tx_ring);
352 if (ctx->rfraw)
353 leave_rfmon_mac80211(ctx->device_out);
355 if (__pcap_io->prepare_close_pcap)
356 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_RD);
358 if (!strncmp("-", ctx->device_in, strlen("-")))
359 dup2(fd, fileno(stdin));
360 close(fd);
362 close(tx_sock);
364 fflush(stdout);
365 printf("\n");
366 printf("\r%12lu packets outgoing\n", ctx->tx_packets);
367 printf("\r%12lu packets truncated in file\n", trunced);
368 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
369 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
372 static void receive_to_xmit(struct ctx *ctx)
374 short ifflags = 0;
375 uint8_t *in, *out;
376 int rx_sock, ifindex_in, ifindex_out, ret;
377 size_t size_in, size_out;
378 unsigned int it_in = 0, it_out = 0;
379 unsigned long frame_count = 0;
380 struct frame_map *hdr_in, *hdr_out;
381 struct ring tx_ring, rx_ring;
382 struct pollfd rx_poll;
383 struct sock_fprog bpf_ops;
385 if (!strncmp(ctx->device_in, ctx->device_out, IFNAMSIZ))
386 panic("Ingress/egress devices must be different!\n");
387 if (!device_up_and_running(ctx->device_out))
388 panic("Egress device not up and running!\n");
390 rx_sock = pf_socket();
391 tx_sock = pf_socket();
393 ifindex_in = device_ifindex(ctx->device_in);
394 ifindex_out = device_ifindex(ctx->device_out);
396 size_in = ring_size(ctx->device_in, ctx->reserve_size);
397 size_out = ring_size(ctx->device_out, ctx->reserve_size);
399 enable_kernel_bpf_jit_compiler();
401 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
402 if (ctx->dump_bpf)
403 bpf_dump_all(&bpf_ops);
404 bpf_attach_to_sock(rx_sock, &bpf_ops);
406 ring_rx_setup(&rx_ring, rx_sock, size_in, ifindex_in, &rx_poll, false, ctx->jumbo,
407 ctx->verbose, ctx->fanout_group, ctx->fanout_type);
408 ring_tx_setup(&tx_ring, tx_sock, size_out, ifindex_out, ctx->jumbo, ctx->verbose);
410 dissector_init_all(ctx->print_mode);
412 if (ctx->promiscuous)
413 ifflags = device_enter_promiscuous_mode(ctx->device_in);
415 if (ctx->kpull)
416 interval = ctx->kpull;
418 set_itimer_interval_value(&itimer, 0, interval);
419 setitimer(ITIMER_REAL, &itimer, NULL);
421 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
423 printf("Running! Hang up with ^C!\n\n");
424 fflush(stdout);
426 while (likely(sigint == 0)) {
427 while (user_may_pull_from_rx(rx_ring.frames[it_in].iov_base)) {
428 hdr_in = rx_ring.frames[it_in].iov_base;
429 in = ((uint8_t *) hdr_in) + hdr_in->tp_h.tp_mac;
431 frame_count++;
433 if (ctx->packet_type != -1)
434 if (ctx->packet_type != hdr_in->s_ll.sll_pkttype)
435 goto next;
437 hdr_out = tx_ring.frames[it_out].iov_base;
438 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
440 while (!user_may_pull_from_tx(tx_ring.frames[it_out].iov_base) &&
441 likely(!sigint)) {
442 if (ctx->randomize)
443 next_rnd_slot(&it_out, &tx_ring);
444 else {
445 it_out++;
446 if (it_out >= tx_ring.layout.tp_frame_nr)
447 it_out = 0;
450 hdr_out = tx_ring.frames[it_out].iov_base;
451 out = ((uint8_t *) hdr_out) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);
454 tpacket_hdr_clone(&hdr_out->tp_h, &hdr_in->tp_h);
455 fmemcpy(out, in, hdr_in->tp_h.tp_len);
457 kernel_may_pull_from_tx(&hdr_out->tp_h);
458 if (ctx->randomize)
459 next_rnd_slot(&it_out, &tx_ring);
460 else {
461 it_out++;
462 if (it_out >= tx_ring.layout.tp_frame_nr)
463 it_out = 0;
466 show_frame_hdr(in, hdr_in->tp_h.tp_snaplen,
467 ctx->link_type, hdr_in, ctx->print_mode,
468 frame_count);
470 dissector_entry_point(in, hdr_in->tp_h.tp_snaplen,
471 ctx->link_type, ctx->print_mode,
472 &hdr_in->s_ll);
474 if (frame_count_max != 0) {
475 if (frame_count >= frame_count_max) {
476 sigint = 1;
477 break;
481 next:
482 kernel_may_pull_from_rx(&hdr_in->tp_h);
484 it_in++;
485 if (it_in >= rx_ring.layout.tp_frame_nr)
486 it_in = 0;
488 if (unlikely(sigint == 1))
489 goto out;
492 ret = poll(&rx_poll, 1, -1);
493 if (unlikely(ret < 0)) {
494 if (errno != EINTR)
495 panic("Poll failed!\n");
499 out:
500 timer_purge();
502 sock_rx_net_stats(rx_sock, 0);
504 bpf_release(&bpf_ops);
506 dissector_cleanup_all();
508 destroy_tx_ring(tx_sock, &tx_ring);
509 destroy_rx_ring(rx_sock, &rx_ring);
511 if (ctx->promiscuous)
512 device_leave_promiscuous_mode(ctx->device_in, ifflags);
514 close(tx_sock);
515 close(rx_sock);
518 static void translate_pcap_to_txf(int fdo, uint8_t *out, size_t len)
520 size_t bytes_done = 0;
521 char bout[80];
523 slprintf(bout, sizeof(bout), "{\n ");
524 write_or_die(fdo, bout, strlen(bout));
526 while (bytes_done < len) {
527 slprintf(bout, sizeof(bout), "0x%02x,", out[bytes_done]);
528 write_or_die(fdo, bout, strlen(bout));
530 bytes_done++;
532 if (bytes_done % 10 == 0) {
533 slprintf(bout, sizeof(bout), "\n");
534 write_or_die(fdo, bout, strlen(bout));
536 if (bytes_done < len) {
537 slprintf(bout, sizeof(bout), " ");
538 write_or_die(fdo, bout, strlen(bout));
540 } else if (bytes_done < len) {
541 slprintf(bout, sizeof(bout), " ");
542 write_or_die(fdo, bout, strlen(bout));
545 if (bytes_done % 10 != 0) {
546 slprintf(bout, sizeof(bout), "\n");
547 write_or_die(fdo, bout, strlen(bout));
550 slprintf(bout, sizeof(bout), "}\n\n");
551 write_or_die(fdo, bout, strlen(bout));
554 static void read_pcap(struct ctx *ctx)
556 uint8_t *out;
557 int ret, fd, fdo = 0;
558 unsigned long trunced = 0;
559 size_t out_len;
560 pcap_pkthdr_t phdr;
561 struct sock_fprog bpf_ops;
562 struct frame_map fm;
563 struct timeval start, end, diff;
564 bool is_out_pcap = ctx->device_out && strstr(ctx->device_out, ".pcap");
565 const struct pcap_file_ops *pcap_out_ops = pcap_ops[PCAP_OPS_RW];
567 bug_on(!__pcap_io);
569 if (!strncmp("-", ctx->device_in, strlen("-"))) {
570 fd = dup_or_die(fileno(stdin));
571 close(fileno(stdin));
572 if (ctx->pcap == PCAP_OPS_MM)
573 ctx->pcap = PCAP_OPS_SG;
574 } else {
575 /* O_NOATIME requires privileges, in case we don't have
576 * them, retry without them at a minor cost of updating
577 * atime in case the fs has been mounted as such.
579 fd = open(ctx->device_in, O_RDONLY | O_LARGEFILE | O_NOATIME);
580 if (fd < 0 && errno == EPERM)
581 fd = open_or_die(ctx->device_in, O_RDONLY | O_LARGEFILE);
582 if (fd < 0)
583 panic("Cannot open file %s! %s.\n", ctx->device_in,
584 strerror(errno));
587 if (__pcap_io->init_once_pcap)
588 __pcap_io->init_once_pcap(false);
590 ret = __pcap_io->pull_fhdr_pcap(fd, &ctx->magic, &ctx->link_type);
591 if (ret)
592 panic("Error reading pcap header!\n");
594 if (__pcap_io->prepare_access_pcap) {
595 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_RD, ctx->jumbo);
596 if (ret)
597 panic("Error prepare reading pcap!\n");
600 fmemset(&fm, 0, sizeof(fm));
602 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
603 if (ctx->dump_bpf)
604 bpf_dump_all(&bpf_ops);
606 dissector_init_all(ctx->print_mode);
608 out_len = round_up(1024 * 1024, RUNTIME_PAGE_SIZE);
609 out = xmalloc_aligned(out_len, CO_CACHE_LINE_SIZE);
611 if (ctx->device_out) {
612 if (!strncmp("-", ctx->device_out, strlen("-"))) {
613 fdo = dup_or_die(fileno(stdout));
614 close(fileno(stdout));
615 } else {
616 fdo = open_or_die_m(ctx->device_out, O_RDWR | O_CREAT |
617 O_TRUNC | O_LARGEFILE, DEFFILEMODE);
621 if (is_out_pcap) {
622 ret = pcap_out_ops->push_fhdr_pcap(fdo, ctx->magic,
623 ctx->link_type);
624 if (ret)
625 panic("Error writing pcap header!\n");
628 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
630 printf("Running! Hang up with ^C!\n\n");
631 fflush(stdout);
633 bug_on(gettimeofday(&start, NULL));
635 while (likely(sigint == 0)) {
636 do {
637 ret = __pcap_io->read_pcap(fd, &phdr, ctx->magic,
638 out, out_len);
639 if (unlikely(ret < 0))
640 goto out;
642 if (unlikely(pcap_get_length(&phdr, ctx->magic) == 0)) {
643 trunced++;
644 continue;
647 if (unlikely(pcap_get_length(&phdr, ctx->magic) > out_len)) {
648 pcap_set_length(&phdr, ctx->magic, out_len);
649 trunced++;
651 } while (ctx->filter &&
652 !bpf_run_filter(&bpf_ops, out,
653 pcap_get_length(&phdr, ctx->magic)));
655 pcap_pkthdr_to_tpacket_hdr(&phdr, ctx->magic, &fm.tp_h, &fm.s_ll);
657 ctx->tx_bytes += fm.tp_h.tp_len;
658 ctx->tx_packets++;
660 show_frame_hdr(out, fm.tp_h.tp_snaplen, ctx->link_type, &fm,
661 ctx->print_mode, ctx->tx_packets);
663 dissector_entry_point(out, fm.tp_h.tp_snaplen,
664 ctx->link_type, ctx->print_mode,
665 &fm.s_ll);
667 if (is_out_pcap) {
668 size_t pcap_len = pcap_get_length(&phdr, ctx->magic);
669 int wlen = pcap_out_ops->write_pcap(fdo, &phdr,
670 ctx->magic, out,
671 pcap_len);
672 if (unlikely(wlen != (int)pcap_get_total_length(&phdr, ctx->magic)))
673 panic("Error writing to pcap!\n");
674 } else if (ctx->device_out) {
675 translate_pcap_to_txf(fdo, out, fm.tp_h.tp_snaplen);
678 if (frame_count_max != 0) {
679 if (ctx->tx_packets >= frame_count_max) {
680 sigint = 1;
681 break;
686 out:
687 bug_on(gettimeofday(&end, NULL));
688 timersub(&end, &start, &diff);
690 bpf_release(&bpf_ops);
692 dissector_cleanup_all();
694 if (__pcap_io->prepare_close_pcap)
695 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_RD);
697 xfree(out);
699 fflush(stdout);
700 printf("\n");
701 printf("\r%12lu packets outgoing\n", ctx->tx_packets);
702 printf("\r%12lu packets truncated in file\n", trunced);
703 printf("\r%12lu bytes outgoing\n", ctx->tx_bytes);
704 printf("\r%12lu sec, %lu usec in total\n", diff.tv_sec, diff.tv_usec);
706 if (!strncmp("-", ctx->device_in, strlen("-")))
707 dup2(fd, fileno(stdin));
708 close(fd);
710 if (ctx->device_out) {
711 if (!strncmp("-", ctx->device_out, strlen("-")))
712 dup2(fdo, fileno(stdout));
713 close(fdo);
717 static void finish_multi_pcap_file(struct ctx *ctx, int fd)
719 __pcap_io->fsync_pcap(fd);
721 if (__pcap_io->prepare_close_pcap)
722 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
724 close(fd);
726 fmemset(&itimer, 0, sizeof(itimer));
727 setitimer(ITIMER_REAL, &itimer, NULL);
730 static int next_multi_pcap_file(struct ctx *ctx, int fd)
732 int ret;
733 char fname[512];
735 __pcap_io->fsync_pcap(fd);
737 if (__pcap_io->prepare_close_pcap)
738 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
740 close(fd);
742 slprintf(fname, sizeof(fname), "%s/%s%lu.pcap", ctx->device_out,
743 ctx->prefix ? : "dump-", time(NULL));
745 fd = open_or_die_m(fname, O_RDWR | O_CREAT | O_TRUNC |
746 O_LARGEFILE, DEFFILEMODE);
748 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
749 if (ret)
750 panic("Error writing pcap header!\n");
752 if (__pcap_io->prepare_access_pcap) {
753 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
754 if (ret)
755 panic("Error prepare writing pcap!\n");
758 return fd;
761 static void reset_interval(struct ctx *ctx)
763 if (ctx->dump_mode == DUMP_INTERVAL_TIME) {
764 interval = ctx->dump_interval;
766 set_itimer_interval_value(&itimer, interval, 0);
767 setitimer(ITIMER_REAL, &itimer, NULL);
768 } else {
769 interval = 0;
773 static int begin_multi_pcap_file(struct ctx *ctx)
775 int fd, ret;
776 char fname[256];
778 bug_on(!__pcap_io);
780 if (ctx->device_out[strlen(ctx->device_out) - 1] == '/')
781 ctx->device_out[strlen(ctx->device_out) - 1] = 0;
783 slprintf(fname, sizeof(fname), "%s/%s%lu.pcap", ctx->device_out,
784 ctx->prefix ? : "dump-", time(NULL));
786 fd = open_or_die_m(fname, O_RDWR | O_CREAT | O_TRUNC |
787 O_LARGEFILE, DEFFILEMODE);
789 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
790 if (ret)
791 panic("Error writing pcap header!\n");
793 if (__pcap_io->prepare_access_pcap) {
794 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
795 if (ret)
796 panic("Error prepare writing pcap!\n");
799 reset_interval(ctx);
801 return fd;
804 static void finish_single_pcap_file(struct ctx *ctx, int fd)
806 __pcap_io->fsync_pcap(fd);
808 if (__pcap_io->prepare_close_pcap)
809 __pcap_io->prepare_close_pcap(fd, PCAP_MODE_WR);
811 if (strncmp("-", ctx->device_out, strlen("-")))
812 close(fd);
813 else
814 dup2(fd, fileno(stdout));
817 static int begin_single_pcap_file(struct ctx *ctx)
819 int fd, ret;
821 bug_on(!__pcap_io);
823 if (!strncmp("-", ctx->device_out, strlen("-"))) {
824 fd = dup_or_die(fileno(stdout));
825 close(fileno(stdout));
826 if (ctx->pcap == PCAP_OPS_MM)
827 ctx->pcap = PCAP_OPS_SG;
828 } else {
829 fd = open_or_die_m(ctx->device_out,
830 O_RDWR | O_CREAT | O_TRUNC |
831 O_LARGEFILE, DEFFILEMODE);
834 ret = __pcap_io->push_fhdr_pcap(fd, ctx->magic, ctx->link_type);
835 if (ret)
836 panic("Error writing pcap header!\n");
838 if (__pcap_io->prepare_access_pcap) {
839 ret = __pcap_io->prepare_access_pcap(fd, PCAP_MODE_WR, true);
840 if (ret)
841 panic("Error prepare writing pcap!\n");
844 return fd;
847 static void print_pcap_file_stats(int sock, struct ctx *ctx)
849 int ret;
850 struct tpacket_stats kstats;
851 socklen_t slen = sizeof(kstats);
853 fmemset(&kstats, 0, sizeof(kstats));
855 ret = getsockopt(sock, SOL_PACKET, PACKET_STATISTICS, &kstats, &slen);
856 if (unlikely(ret))
857 panic("Cannot get packet statistics!\n");
859 if (ctx->print_mode == PRINT_NONE) {
860 printf(".(+%u/-%u)", kstats.tp_packets - kstats.tp_drops,
861 kstats.tp_drops);
862 fflush(stdout);
866 static void update_pcap_next_dump(struct ctx *ctx, unsigned long snaplen, int *fd, int sock)
868 if (!dump_to_pcap(ctx))
869 return;
871 if (ctx->dump_mode == DUMP_INTERVAL_SIZE) {
872 interval += snaplen;
873 if (interval > ctx->dump_interval) {
874 next_dump = true;
875 interval = 0;
879 if (sighup) {
880 if (ctx->verbose)
881 printf("SIGHUP received, prematurely rotating pcap\n");
882 sighup = 0;
883 next_dump = true;
884 reset_interval(ctx);
887 if (next_dump) {
888 *fd = next_multi_pcap_file(ctx, *fd);
889 next_dump = false;
891 if (ctx->verbose)
892 print_pcap_file_stats(sock, ctx);
896 #ifdef HAVE_TPACKET3
897 static void walk_t3_block(struct block_desc *pbd, struct ctx *ctx,
898 int sock, int *fd, unsigned long *frame_count)
900 int num_pkts = pbd->h1.num_pkts, i;
901 struct tpacket3_hdr *hdr;
902 struct sockaddr_ll *sll;
904 hdr = (void *) ((uint8_t *) pbd + pbd->h1.offset_to_first_pkt);
905 sll = (void *) ((uint8_t *) hdr + TPACKET_ALIGN(sizeof(*hdr)));
907 for (i = 0; i < num_pkts && likely(sigint == 0); ++i) {
908 uint8_t *packet = ((uint8_t *) hdr + hdr->tp_mac);
909 pcap_pkthdr_t phdr;
911 if (ctx->packet_type != -1)
912 if (ctx->packet_type != sll->sll_pkttype)
913 goto next;
915 (*frame_count)++;
917 if (dump_to_pcap(ctx)) {
918 int ret;
920 tpacket3_hdr_to_pcap_pkthdr(hdr, sll, &phdr, ctx->magic);
922 ret = __pcap_io->write_pcap(*fd, &phdr, ctx->magic, packet,
923 pcap_get_length(&phdr, ctx->magic));
924 if (unlikely(ret != (int) pcap_get_total_length(&phdr, ctx->magic)))
925 panic("Write error to pcap!\n");
928 __show_frame_hdr(packet, hdr->tp_snaplen, ctx->link_type, sll,
929 hdr, ctx->print_mode, true, *frame_count);
931 dissector_entry_point(packet, hdr->tp_snaplen, ctx->link_type,
932 ctx->print_mode, sll);
933 next:
934 hdr = (void *) ((uint8_t *) hdr + hdr->tp_next_offset);
935 sll = (void *) ((uint8_t *) hdr + TPACKET_ALIGN(sizeof(*hdr)));
937 if (frame_count_max != 0) {
938 if (unlikely(*frame_count >= frame_count_max)) {
939 sigint = 1;
940 break;
944 update_pcap_next_dump(ctx, hdr->tp_snaplen, fd, sock);
947 #endif /* HAVE_TPACKET3 */
949 static void recv_only_or_dump(struct ctx *ctx)
951 short ifflags = 0;
952 int sock, ifindex, fd = 0, ret;
953 size_t size;
954 unsigned int it = 0;
955 struct ring rx_ring;
956 struct pollfd rx_poll;
957 struct sock_fprog bpf_ops;
958 struct timeval start, end, diff;
959 unsigned long frame_count = 0;
961 sock = pf_socket_type(ctx->link_type);
963 ifindex = device_ifindex(ctx->device_in);
964 size = ring_size(ctx->device_in, ctx->reserve_size);
966 enable_kernel_bpf_jit_compiler();
968 bpf_parse_rules(ctx->filter, &bpf_ops, ctx->link_type);
969 if (ctx->dump_bpf)
970 bpf_dump_all(&bpf_ops);
971 bpf_attach_to_sock(sock, &bpf_ops);
973 if (ctx->hwtimestamp) {
974 ret = set_sockopt_hwtimestamp(sock, ctx->device_in);
975 if (ret == 0 && ctx->verbose)
976 printf("HW timestamping enabled\n");
979 ring_rx_setup(&rx_ring, sock, size, ifindex, &rx_poll, is_defined(HAVE_TPACKET3), true,
980 ctx->verbose, ctx->fanout_group, ctx->fanout_type);
982 dissector_init_all(ctx->print_mode);
984 if (ctx->cpu >= 0 && ifindex > 0) {
985 int irq = device_irq_number(ctx->device_in);
986 device_set_irq_affinity(irq, ctx->cpu);
988 if (ctx->verbose)
989 printf("IRQ: %s:%d > CPU%d\n",
990 ctx->device_in, irq, ctx->cpu);
993 if (ctx->promiscuous)
994 ifflags = device_enter_promiscuous_mode(ctx->device_in);
996 if (dump_to_pcap(ctx) && __pcap_io->init_once_pcap)
997 __pcap_io->init_once_pcap(true);
999 drop_privileges(ctx->enforce, ctx->uid, ctx->gid);
1001 if (dump_to_pcap(ctx)) {
1002 struct stat stats;
1004 ret = stat(ctx->device_out, &stats);
1005 if (ret < 0)
1006 ctx->dump_dir = 0;
1007 else
1008 ctx->dump_dir = S_ISDIR(stats.st_mode);
1010 if (ctx->dump_dir)
1011 fd = begin_multi_pcap_file(ctx);
1012 else
1013 fd = begin_single_pcap_file(ctx);
1016 printf("Running! Hang up with ^C!\n\n");
1017 fflush(stdout);
1019 bug_on(gettimeofday(&start, NULL));
1021 while (likely(sigint == 0)) {
1022 #ifdef HAVE_TPACKET3
1023 struct block_desc *pbd;
1025 while (user_may_pull_from_rx_block((pbd = rx_ring.frames[it].iov_base))) {
1026 walk_t3_block(pbd, ctx, sock, &fd, &frame_count);
1028 kernel_may_pull_from_rx_block(pbd);
1029 it = (it + 1) % rx_ring.layout3.tp_block_nr;
1031 if (unlikely(sigint == 1))
1032 break;
1034 #else
1035 while (user_may_pull_from_rx(rx_ring.frames[it].iov_base)) {
1036 struct frame_map *hdr = rx_ring.frames[it].iov_base;
1037 uint8_t *packet = ((uint8_t *) hdr) + hdr->tp_h.tp_mac;
1038 pcap_pkthdr_t phdr;
1040 if (ctx->packet_type != -1)
1041 if (ctx->packet_type != hdr->s_ll.sll_pkttype)
1042 goto next;
1044 frame_count++;
1046 if (unlikely(ring_frame_size(&rx_ring) < hdr->tp_h.tp_snaplen)) {
1047 /* XXX: silently ignore for now. We used to
1048 * report them with sock_rx_net_stats() */
1049 goto next;
1052 if (dump_to_pcap(ctx)) {
1053 tpacket_hdr_to_pcap_pkthdr(&hdr->tp_h, &hdr->s_ll, &phdr, ctx->magic);
1055 ret = __pcap_io->write_pcap(fd, &phdr, ctx->magic, packet,
1056 pcap_get_length(&phdr, ctx->magic));
1057 if (unlikely(ret != (int) pcap_get_total_length(&phdr, ctx->magic)))
1058 panic("Write error to pcap!\n");
1061 show_frame_hdr(packet, hdr->tp_h.tp_snaplen,
1062 ctx->link_type, hdr, ctx->print_mode,
1063 frame_count);
1065 dissector_entry_point(packet, hdr->tp_h.tp_snaplen,
1066 ctx->link_type, ctx->print_mode,
1067 &hdr->s_ll);
1069 if (frame_count_max != 0) {
1070 if (unlikely(frame_count >= frame_count_max)) {
1071 sigint = 1;
1072 break;
1076 next:
1077 kernel_may_pull_from_rx(&hdr->tp_h);
1078 it = (it + 1) % rx_ring.layout.tp_frame_nr;
1080 if (unlikely(sigint == 1))
1081 break;
1083 update_pcap_next_dump(ctx, hdr->tp_h.tp_snaplen, &fd, sock);
1085 #endif /* HAVE_TPACKET3 */
1087 ret = poll(&rx_poll, 1, -1);
1088 if (unlikely(ret < 0)) {
1089 if (errno != EINTR)
1090 panic("Poll failed!\n");
1094 bug_on(gettimeofday(&end, NULL));
1095 timersub(&end, &start, &diff);
1097 if (!(ctx->dump_dir && ctx->print_mode == PRINT_NONE)) {
1098 sock_rx_net_stats(sock, frame_count);
1100 printf("\r%12lu sec, %lu usec in total\n",
1101 diff.tv_sec, diff.tv_usec);
1102 } else {
1103 printf("\n\n");
1104 fflush(stdout);
1107 bpf_release(&bpf_ops);
1108 dissector_cleanup_all();
1109 destroy_rx_ring(sock, &rx_ring);
1111 if (ctx->promiscuous)
1112 device_leave_promiscuous_mode(ctx->device_in, ifflags);
1114 if (ctx->rfraw)
1115 leave_rfmon_mac80211(ctx->device_in);
1117 if (dump_to_pcap(ctx)) {
1118 if (ctx->dump_dir)
1119 finish_multi_pcap_file(ctx, fd);
1120 else
1121 finish_single_pcap_file(ctx, fd);
1124 close(sock);
1127 static void init_ctx(struct ctx *ctx)
1129 memset(ctx, 0, sizeof(*ctx));
1131 ctx->uid = getuid();
1132 ctx->gid = getgid();
1134 ctx->cpu = -1;
1135 ctx->packet_type = -1;
1137 ctx->fanout_type = PACKET_FANOUT_ROLLOVER;
1139 ctx->magic = ORIGINAL_TCPDUMP_MAGIC;
1140 ctx->print_mode = PRINT_NORM;
1141 ctx->pcap = PCAP_OPS_SG;
1143 ctx->dump_mode = DUMP_INTERVAL_TIME;
1144 ctx->dump_interval = 60;
1146 ctx->promiscuous = true;
1147 ctx->randomize = false;
1148 ctx->hwtimestamp = true;
1151 static void destroy_ctx(struct ctx *ctx)
1153 free(ctx->device_in);
1154 free(ctx->device_out);
1155 free(ctx->device_trans);
1157 free(ctx->prefix);
1160 static void __noreturn help(void)
1162 printf("netsniff-ng %s, the packet sniffing beast\n", VERSION_STRING);
1163 puts("http://www.netsniff-ng.org\n\n"
1164 "Usage: netsniff-ng [options] [filter-expression]\n"
1165 "Options:\n"
1166 " -i|-d|--dev|--in <dev|pcap|-> Input source as netdev, pcap or pcap stdin\n"
1167 " -o|--out <dev|pcap|dir|cfg|-> Output sink as netdev, pcap, directory, trafgen, or stdout\n"
1168 " -C|--fanout-group <id> Join packet fanout group\n"
1169 " -K|--fanout-type <type> Apply fanout discipline: hash|lb|cpu|rnd|roll|qm\n"
1170 " -L|--fanout-opts <opts> Additional fanout options: defrag|roll\n"
1171 " -f|--filter <bpf-file|expr> Use BPF filter file from bpfc or tcpdump-like expression\n"
1172 " -t|--type <type> Filter for: host|broadcast|multicast|others|outgoing\n"
1173 " -F|--interval <size|time> Dump interval if -o is a dir: <num>KiB/MiB/GiB/s/sec/min/hrs\n"
1174 " -R|--rfraw Capture or inject raw 802.11 frames\n"
1175 " -n|--num <0|uint> Number of packets until exit (def: 0)\n"
1176 " -P|--prefix <name> Prefix for pcaps stored in directory\n"
1177 " -T|--magic <pcap-magic> Pcap magic number/pcap format to store, see -D\n"
1178 " -w|--cooked Use Linux \"cooked\" header instead of link header\n"
1179 " -D|--dump-pcap-types Dump pcap types and magic numbers and quit\n"
1180 " -B|--dump-bpf Dump generated BPF assembly\n"
1181 " -r|--rand Randomize packet forwarding order (dev->dev)\n"
1182 " -M|--no-promisc No promiscuous mode for netdev\n"
1183 " -A|--no-sock-mem Don't tune core socket memory\n"
1184 " -N|--no-hwtimestamp Disable hardware time stamping\n"
1185 " -m|--mmap Mmap(2) pcap file I/O, e.g. for replaying pcaps\n"
1186 " -G|--sg Scatter/gather pcap file I/O\n"
1187 " -c|--clrw Use slower read(2)/write(2) I/O\n"
1188 " -S|--ring-size <size> Specify ring size to: <num>KiB/MiB/GiB\n"
1189 " -k|--kernel-pull <uint> Kernel pull from user interval in us (def: 10us)\n"
1190 " -J|--jumbo-support Support replay/fwd 64KB Super Jumbo Frames (def: 2048B)\n"
1191 " -b|--bind-cpu <cpu> Bind to specific CPU\n"
1192 " -u|--user <userid> Drop privileges and change to userid\n"
1193 " -g|--group <groupid> Drop privileges and change to groupid\n"
1194 " -H|--prio-high Make this high priority process\n"
1195 " -Q|--notouch-irq Do not touch IRQ CPU affinity of NIC\n"
1196 " -s|--silent Do not print captured packets\n"
1197 " -q|--less Print less-verbose packet information\n"
1198 " -X|--hex Print packet data in hex format\n"
1199 " -l|--ascii Print human-readable packet data\n"
1200 " -U|--update Update GeoIP databases\n"
1201 " -V|--verbose Be more verbose\n"
1202 " -v|--version Show version and exit\n"
1203 " -h|--help Guess what?!\n\n"
1204 "Examples:\n"
1205 " netsniff-ng --in eth0 --out dump.pcap -s -T 0xa1b2c3d4 --b 0 tcp or udp\n"
1206 " netsniff-ng --in wlan0 --rfraw --out dump.pcap --silent --bind-cpu 0\n"
1207 " netsniff-ng --in dump.pcap --mmap --out eth0 -k1000 --silent --bind-cpu 0\n"
1208 " netsniff-ng --in dump.pcap --out dump.cfg --silent --bind-cpu 0\n"
1209 " netsniff-ng --in dump.pcap --out dump2.pcap --silent tcp\n"
1210 " netsniff-ng --in eth0 --out eth1 --silent --bind-cpu 0 -J --type host\n"
1211 " netsniff-ng --in eth1 --out /opt/probe/ -s -m --interval 100MiB -b 0\n"
1212 " netsniff-ng --in vlan0 --out dump.pcap -c -u `id -u bob` -g `id -g bob`\n"
1213 " netsniff-ng --in any --filter http.bpf --jumbo-support --ascii -V\n\n"
1214 "Note:\n"
1215 " For introducing bit errors, delays with random variation and more\n"
1216 " while replaying pcaps, make use of tc(8) with its disciplines (e.g. netem).\n");
1217 puts(copyright);
1218 die();
1221 static void __noreturn version(void)
1223 printf("netsniff-ng %s, Git id: %s\n", VERSION_LONG, GITVERSION);
1224 puts("the packet sniffing beast\n"
1225 "http://www.netsniff-ng.org\n");
1226 puts(copyright);
1227 die();
1230 int main(int argc, char **argv)
1232 char *ptr;
1233 int c, i, j, cpu_tmp, opt_index, ops_touched = 0, vals[4] = {0};
1234 bool prio_high = false, setsockmem = true;
1235 void (*main_loop)(struct ctx *ctx) = NULL;
1236 struct ctx ctx;
1238 init_ctx(&ctx);
1239 srand(time(NULL));
1241 while ((c = getopt_long(argc, argv, short_options, long_options,
1242 &opt_index)) != EOF) {
1243 switch (c) {
1244 case 'd':
1245 case 'i':
1246 ctx.device_in = xstrdup(optarg);
1247 break;
1248 case 'o':
1249 ctx.device_out = xstrdup(optarg);
1250 break;
1251 case 'P':
1252 ctx.prefix = xstrdup(optarg);
1253 break;
1254 case 'R':
1255 ctx.rfraw = 1;
1256 break;
1257 case 'r':
1258 ctx.randomize = true;
1259 break;
1260 case 'J':
1261 ctx.jumbo = true;
1262 break;
1263 case 'T':
1264 ctx.magic = (uint32_t) strtoul(optarg, NULL, 0);
1265 pcap_check_magic(ctx.magic);
1266 break;
1267 case 'f':
1268 ctx.filter = xstrdup(optarg);
1269 break;
1270 case 'M':
1271 ctx.promiscuous = false;
1272 break;
1273 case 'N':
1274 ctx.hwtimestamp = false;
1275 break;
1276 case 'A':
1277 setsockmem = false;
1278 break;
1279 case 'u':
1280 ctx.uid = strtoul(optarg, NULL, 0);
1281 ctx.enforce = true;
1282 break;
1283 case 'g':
1284 ctx.gid = strtoul(optarg, NULL, 0);
1285 ctx.enforce = true;
1286 break;
1287 case 'C':
1288 ctx.fanout_group = strtoul(optarg, NULL, 0);
1289 if (ctx.fanout_group == 0)
1290 panic("Non-zero fanout group id required!\n");
1291 break;
1292 case 'K':
1293 if (!strncmp(optarg, "hash", strlen("hash")))
1294 ctx.fanout_type = PACKET_FANOUT_HASH;
1295 else if (!strncmp(optarg, "lb", strlen("lb")) ||
1296 !strncmp(optarg, "rr", strlen("rr")))
1297 ctx.fanout_type = PACKET_FANOUT_LB;
1298 else if (!strncmp(optarg, "cpu", strlen("cpu")))
1299 ctx.fanout_type = PACKET_FANOUT_CPU;
1300 else if (!strncmp(optarg, "rnd", strlen("rnd")))
1301 ctx.fanout_type = PACKET_FANOUT_RND;
1302 else if (!strncmp(optarg, "roll", strlen("roll")))
1303 ctx.fanout_type = PACKET_FANOUT_ROLLOVER;
1304 else if (!strncmp(optarg, "qm", strlen("qm")))
1305 ctx.fanout_type = PACKET_FANOUT_QM;
1306 else
1307 panic("Unknown fanout type!\n");
1308 break;
1309 case 'L':
1310 if (!strncmp(optarg, "defrag", strlen("defrag")))
1311 ctx.fanout_type |= PACKET_FANOUT_FLAG_DEFRAG;
1312 else if (!strncmp(optarg, "roll", strlen("roll")))
1313 ctx.fanout_type |= PACKET_FANOUT_FLAG_ROLLOVER;
1314 else
1315 panic("Unknown fanout option!\n");
1316 break;
1317 case 't':
1318 if (!strncmp(optarg, "host", strlen("host")))
1319 ctx.packet_type = PACKET_HOST;
1320 else if (!strncmp(optarg, "broadcast", strlen("broadcast")))
1321 ctx.packet_type = PACKET_BROADCAST;
1322 else if (!strncmp(optarg, "multicast", strlen("multicast")))
1323 ctx.packet_type = PACKET_MULTICAST;
1324 else if (!strncmp(optarg, "others", strlen("others")))
1325 ctx.packet_type = PACKET_OTHERHOST;
1326 else if (!strncmp(optarg, "outgoing", strlen("outgoing")))
1327 ctx.packet_type = PACKET_OUTGOING;
1328 else
1329 ctx.packet_type = -1;
1330 break;
1331 case 'S':
1332 ptr = optarg;
1333 for (j = i = strlen(optarg); i > 0; --i) {
1334 if (!isdigit(optarg[j - i]))
1335 break;
1336 ptr++;
1339 if (!strncmp(ptr, "KiB", strlen("KiB")))
1340 ctx.reserve_size = 1 << 10;
1341 else if (!strncmp(ptr, "MiB", strlen("MiB")))
1342 ctx.reserve_size = 1 << 20;
1343 else if (!strncmp(ptr, "GiB", strlen("GiB")))
1344 ctx.reserve_size = 1 << 30;
1345 else
1346 panic("Syntax error in ring size param!\n");
1348 ctx.reserve_size *= strtoul(optarg, NULL, 0);
1349 break;
1350 case 'b':
1351 cpu_tmp = strtol(optarg, NULL, 0);
1353 cpu_affinity(cpu_tmp);
1354 if (ctx.cpu != -2)
1355 ctx.cpu = cpu_tmp;
1356 break;
1357 case 'H':
1358 prio_high = true;
1359 break;
1360 case 'c':
1361 ctx.pcap = PCAP_OPS_RW;
1362 ops_touched = 1;
1363 break;
1364 case 'm':
1365 ctx.pcap = PCAP_OPS_MM;
1366 ops_touched = 1;
1367 break;
1368 case 'G':
1369 ctx.pcap = PCAP_OPS_SG;
1370 ops_touched = 1;
1371 break;
1372 case 'Q':
1373 ctx.cpu = -2;
1374 break;
1375 case 's':
1376 ctx.print_mode = PRINT_NONE;
1377 break;
1378 case 'q':
1379 ctx.print_mode = PRINT_LESS;
1380 break;
1381 case 'X':
1382 ctx.print_mode =
1383 (ctx.print_mode == PRINT_ASCII) ?
1384 PRINT_HEX_ASCII : PRINT_HEX;
1385 break;
1386 case 'l':
1387 ctx.print_mode =
1388 (ctx.print_mode == PRINT_HEX) ?
1389 PRINT_HEX_ASCII : PRINT_ASCII;
1390 break;
1391 case 'k':
1392 ctx.kpull = strtoul(optarg, NULL, 0);
1393 break;
1394 case 'n':
1395 frame_count_max = strtoul(optarg, NULL, 0);
1396 break;
1397 case 'F':
1398 ptr = optarg;
1399 for (j = i = strlen(optarg); i > 0; --i) {
1400 if (!isdigit(optarg[j - i]))
1401 break;
1402 ptr++;
1405 if (!strncmp(ptr, "KiB", strlen("KiB"))) {
1406 ctx.dump_interval = 1 << 10;
1407 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1408 } else if (!strncmp(ptr, "MiB", strlen("MiB"))) {
1409 ctx.dump_interval = 1 << 20;
1410 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1411 } else if (!strncmp(ptr, "GiB", strlen("GiB"))) {
1412 ctx.dump_interval = 1 << 30;
1413 ctx.dump_mode = DUMP_INTERVAL_SIZE;
1414 } else if (!strncmp(ptr, "sec", strlen("sec"))) {
1415 ctx.dump_interval = 1;
1416 ctx.dump_mode = DUMP_INTERVAL_TIME;
1417 } else if (!strncmp(ptr, "min", strlen("min"))) {
1418 ctx.dump_interval = 60;
1419 ctx.dump_mode = DUMP_INTERVAL_TIME;
1420 } else if (!strncmp(ptr, "hrs", strlen("hrs"))) {
1421 ctx.dump_interval = 60 * 60;
1422 ctx.dump_mode = DUMP_INTERVAL_TIME;
1423 } else if (!strncmp(ptr, "s", strlen("s"))) {
1424 ctx.dump_interval = 1;
1425 ctx.dump_mode = DUMP_INTERVAL_TIME;
1426 } else {
1427 panic("Syntax error in time/size param!\n");
1430 ctx.dump_interval *= strtoul(optarg, NULL, 0);
1431 break;
1432 case 'V':
1433 ctx.verbose = true;
1434 break;
1435 case 'B':
1436 ctx.dump_bpf = true;
1437 break;
1438 case 'D':
1439 pcap_dump_type_features();
1440 die();
1441 break;
1442 case 'U':
1443 update_geoip();
1444 die();
1445 break;
1446 case 'w':
1447 ctx.link_type = LINKTYPE_LINUX_SLL;
1448 break;
1449 case 'v':
1450 version();
1451 break;
1452 case 'h':
1453 help();
1454 break;
1455 case '?':
1456 switch (optopt) {
1457 case 'd':
1458 case 'i':
1459 case 'o':
1460 case 'f':
1461 case 't':
1462 case 'P':
1463 case 'F':
1464 case 'n':
1465 case 'S':
1466 case 'b':
1467 case 'k':
1468 case 'T':
1469 case 'u':
1470 case 'g':
1471 case 'e':
1472 panic("Option -%c requires an argument!\n",
1473 optopt);
1474 default:
1475 if (isprint(optopt))
1476 printf("Unknown option character `0x%X\'!\n", optopt);
1477 die();
1479 default:
1480 break;
1484 if (!ctx.filter && optind != argc) {
1485 int ret;
1486 off_t offset = 0;
1488 for (i = optind; i < argc; ++i) {
1489 size_t alen = strlen(argv[i]) + 2;
1490 size_t flen = ctx.filter ? strlen(ctx.filter) : 0;
1492 ctx.filter = xrealloc(ctx.filter, flen + alen);
1493 ret = slprintf(ctx.filter + offset, strlen(argv[i]) + 2, "%s ", argv[i]);
1494 if (ret < 0)
1495 panic("Cannot concatenate filter string!\n");
1496 else
1497 offset += ret;
1501 if (!ctx.device_in)
1502 ctx.device_in = xstrdup("any");
1504 register_signal(SIGINT, signal_handler);
1505 register_signal(SIGQUIT, signal_handler);
1506 register_signal(SIGTERM, signal_handler);
1507 register_signal(SIGHUP, signal_handler);
1509 tprintf_init();
1511 if (prio_high) {
1512 set_proc_prio(-20);
1513 set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
1516 if (device_mtu(ctx.device_in) || !strncmp("any", ctx.device_in, strlen(ctx.device_in))) {
1517 if (ctx.rfraw)
1518 setup_rfmon_mac80211_dev(&ctx, &ctx.device_in);
1520 if (!ctx.link_type)
1521 ctx.link_type = pcap_dev_to_linktype(ctx.device_in);
1522 if (link_has_sll_hdr(ctx.link_type)) {
1523 switch (ctx.magic) {
1524 case ORIGINAL_TCPDUMP_MAGIC:
1525 ctx.magic = ORIGINAL_TCPDUMP_MAGIC_LL;
1526 break;
1527 case NSEC_TCPDUMP_MAGIC:
1528 ctx.magic = NSEC_TCPDUMP_MAGIC_LL;
1529 break;
1530 case ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC):
1531 ctx.magic = ___constant_swab32(ORIGINAL_TCPDUMP_MAGIC_LL);
1532 break;
1533 case ___constant_swab32(NSEC_TCPDUMP_MAGIC):
1534 ctx.magic = ___constant_swab32(NSEC_TCPDUMP_MAGIC_LL);
1535 break;
1540 if (!ctx.device_out) {
1541 ctx.dump = 0;
1542 main_loop = recv_only_or_dump;
1543 } else if (device_mtu(ctx.device_out)) {
1544 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1545 main_loop = receive_to_xmit;
1546 } else {
1547 ctx.dump = 1;
1548 register_signal_f(SIGALRM, timer_next_dump, SA_SIGINFO);
1549 main_loop = recv_only_or_dump;
1550 if (!ops_touched)
1551 ctx.pcap = PCAP_OPS_SG;
1553 } else {
1554 if (ctx.device_out && device_mtu(ctx.device_out)) {
1555 register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
1556 main_loop = pcap_to_xmit;
1557 if (!ops_touched)
1558 ctx.pcap = PCAP_OPS_MM;
1559 } else {
1560 main_loop = read_pcap;
1561 if (!ops_touched)
1562 ctx.pcap = PCAP_OPS_SG;
1566 bug_on(!main_loop);
1568 init_geoip(0);
1569 if (setsockmem)
1570 set_system_socket_memory(vals, array_size(vals));
1571 if (!ctx.enforce)
1572 xlockme();
1574 if (ctx.verbose)
1575 printf("pcap file I/O method: %s\n", pcap_ops_group_to_str[ctx.pcap]);
1577 main_loop(&ctx);
1579 if (!ctx.enforce)
1580 xunlockme();
1581 if (setsockmem)
1582 reset_system_socket_memory(vals, array_size(vals));
1583 destroy_geoip();
1585 device_restore_irq_affinity_list();
1586 tprintf_cleanup();
1588 destroy_ctx(&ctx);
1589 return 0;