3 * Wireshark - Network traffic analyzer
4 * By Gerald Combs <gerald@wireshark.org>
5 * Copyright 1998 Gerald Combs
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include <stdlib.h> /* for exit() */
30 #ifdef HAVE_SYS_TYPES_H
31 # include <sys/types.h>
34 #ifdef HAVE_SYS_SOCKET_H
35 #include <sys/socket.h>
38 #ifdef HAVE_NETINET_IN_H
39 #include <netinet/in.h>
42 #ifdef HAVE_SYS_STAT_H
43 # include <sys/stat.h>
58 #ifdef HAVE_ARPA_INET_H
59 #include <arpa/inet.h>
62 #if defined(__APPLE__) && defined(__LP64__)
63 #include <sys/utsname.h>
67 * Linux bonding devices mishandle unknown ioctls; they fail
68 * with ENODEV rather than ENOTSUP, EOPNOTSUPP, or ENOTTY,
69 * so pcap_can_set_rfmon() returns a "no such device" indication
70 * if we try to do SIOCGIWMODE on them.
72 * So, on Linux, we check for bonding devices, if we can, before
73 * trying pcap_can_set_rfmon(), as pcap_can_set_rfmon() will
74 * end up trying SIOCGIWMODE on the device if that ioctl exists.
76 #if defined(HAVE_PCAP_CREATE) && defined(__linux__)
78 #include <sys/ioctl.h>
81 * If we're building for a Linux version that supports bonding,
82 * HAVE_BONDING will be defined.
85 #ifdef HAVE_LINUX_SOCKIOS_H
86 #include <linux/sockios.h>
89 #ifdef HAVE_LINUX_IF_BONDING_H
90 #include <linux/if_bonding.h>
93 #if defined(BOND_INFO_QUERY_OLD) || defined(SIOCBONDINFOQUERY)
97 #endif /* defined(HAVE_PCAP_CREATE) && defined(__linux__) */
103 #include <zlib.h> /* to get the libz version number */
106 #include <wsutil/cmdarg_err.h>
107 #include <wsutil/crash_info.h>
108 #include <wsutil/ws_diag_control.h>
109 #include <wsutil/ws_version_info.h>
111 #ifndef HAVE_GETOPT_LONG
112 #include "wsutil/wsgetopt.h"
120 # include <sys/prctl.h>
121 # include <sys/capability.h>
124 #include "ringbuffer.h"
126 #include "caputils/capture_ifinfo.h"
127 #include "caputils/capture-pcap-util.h"
128 #include "caputils/capture-pcap-util-int.h"
130 #include "caputils/capture-wpcap.h"
136 #include <wsutil/unicode-utils.h>
143 #ifdef NEED_INET_V6DEFS_H
144 # include "wsutil/inet_v6defs.h"
147 #include <wsutil/clopts_common.h>
148 #include <wsutil/privileges.h>
150 #include "sync_pipe.h"
152 #include "capture_opts.h"
153 #include <capchild/capture_session.h>
154 #include <capchild/capture_sync.h>
156 #include "conditions.h"
157 #include "capture_stop_conditions.h"
159 #include "wsutil/tempfile.h"
161 #include "wsutil/file_util.h"
162 #include "wsutil/os_version_info.h"
164 #include "caputils/ws80211_utils.h"
171 * Get information about libpcap format from "wiretap/libpcap.h".
172 * XXX - can we just use pcap_open_offline() to read the pipe?
174 #include "wiretap/libpcap.h"
176 /**#define DEBUG_DUMPCAP**/
177 /**#define DEBUG_CHILD_DUMPCAP**/
181 #include <conio.h> /* _getch() */
185 #ifdef DEBUG_CHILD_DUMPCAP
186 FILE *debug_log; /* for logging debug messages to */
187 /* a file if DEBUG_CHILD_DUMPCAP */
191 static GAsyncQueue *pcap_queue;
192 static gint64 pcap_queue_bytes;
193 static gint64 pcap_queue_packets;
194 static gint64 pcap_queue_byte_limit = 0;
195 static gint64 pcap_queue_packet_limit = 0;
197 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
199 static gchar *sig_pipe_name = NULL;
200 static HANDLE sig_pipe_handle = NULL;
201 static gboolean signal_pipe_check_running(void);
205 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
206 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
209 /** Stop a low-level capture (stops the capture child). */
210 static void capture_loop_stop(void);
211 /** Close a pipe, or socket if \a from_socket is TRUE */
212 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
216 * Enable kernel BPF JIT compiler if available.
217 * If any calls fail, just drive on - the JIT compiler might not be
218 * enabled, but filtering will still work, and it's not clear what
219 * we could do if the calls fail; should we just report the error
220 * and not continue to capture, should we report it as a warning, or
224 enable_kernel_bpf_jit_compiler(void)
228 static const char file[] = "/proc/sys/net/core/bpf_jit_enable";
230 fd = ws_open(file, O_WRONLY);
234 written = write(fd, "1", strlen("1"));
240 #if !defined (__linux__)
241 #ifndef HAVE_PCAP_BREAKLOOP
243 * We don't have pcap_breakloop(), which is the only way to ensure that
244 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
245 * won't, if the call to read the next packet or batch of packets is
246 * is interrupted by a signal on UN*X, just go back and try again to
249 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
250 * the signal handler, set a flag to stop capturing; however, without
251 * a guarantee of that sort, we can't guarantee that we'll stop capturing
252 * if the read will be retried and won't time out if no packets arrive.
254 * Therefore, on at least some platforms, we work around the lack of
255 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
256 * to wait for packets to arrive, so that we're probably going to be
257 * blocked in the select() when the signal arrives, and can just bail
258 * out of the loop at that point.
260 * However, we don't want to do that on BSD (because "select()" doesn't work
261 * correctly on BPF devices on at least some releases of some flavors of
262 * BSD), and we don't want to do it on Windows (because "select()" is
263 * something for sockets, not for arbitrary handles). (Note that "Windows"
264 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
265 * using WinPcap, not a UNIX libpcap.)
267 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
268 * on BSD times out even if no packets have arrived, so we'll eventually
269 * exit pcap_dispatch() with an indication that no packets have arrived,
270 * and will break out of the capture loop at that point.
272 * On Windows, we can't send a SIGINT to stop capturing, so none of this
273 * applies in any case.
275 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
276 * want to include it if it's not present on this platform, however.
278 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
279 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
281 # define MUST_DO_SELECT
282 # endif /* avoid select */
283 #endif /* HAVE_PCAP_BREAKLOOP */
285 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
286 * in pcap_dispatch(); on the other hand, select() works just fine there.
287 * Hence we use a select for that come what may.
289 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
290 * internally, and, with TPACKET_V3, once that's supported, it'll
291 * support timeouts, at least as I understand the way the code works.
293 #define MUST_DO_SELECT
296 /** init the capture filter */
299 INITFILTER_BAD_FILTER,
300 INITFILTER_OTHER_ERROR
301 } initfilter_status_t;
304 STATE_EXPECT_REC_HDR,
317 typedef struct _pcap_options {
322 #ifdef MUST_DO_SELECT
323 int pcap_fd; /**< pcap file descriptor */
330 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
331 /**< capture pipe (unix only "input file") */
332 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
333 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
334 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
335 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
337 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
339 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
340 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
341 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
343 char * cap_pipe_buf; /**< Pointer to the data buffer we read into */
344 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
345 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
347 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
348 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
350 cap_pipe_state_t cap_pipe_state;
351 cap_pipe_err_t cap_pipe_err;
354 GMutex *cap_pipe_read_mtx;
355 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
359 typedef struct _loop_data {
361 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
362 int err; /**< if non-zero, error seen while capturing */
363 gint packet_count; /**< Number of packets we have already captured */
364 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
365 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
367 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
373 guint64 bytes_written;
374 guint32 autostop_files;
377 typedef struct _pcap_queue_element {
378 pcap_options *pcap_opts;
379 struct pcap_pkthdr phdr;
381 } pcap_queue_element;
384 * Standard secondary message for unexpected errors.
386 static const char please_report[] =
387 "Please report this to the Wireshark developers.\n"
388 "https://bugs.wireshark.org/\n"
389 "(This is not a crash; please do not report it as such.)";
392 * This needs to be static, so that the SIGINT handler can clear the "go"
395 static loop_data global_ld;
399 * Timeout, in milliseconds, for reads from the stream of captured packets
400 * from a capture device.
402 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
403 * 64-bit applications, with sub-second timeouts not to work. The bug is
404 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
406 #if defined(__APPLE__) && defined(__LP64__)
407 static gboolean need_timeout_workaround;
409 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
411 #define CAP_READ_TIMEOUT 250
415 * Timeout, in microseconds, for reads from the stream of captured packets
416 * from a pipe. Pipes don't have the same problem that BPF devices do
417 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
418 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
419 * of the offending versions of Snow Leopard.
421 * On Windows this value is converted to milliseconds and passed to
422 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
423 * will return immediately.
426 #define PIPE_READ_TIMEOUT 100000
428 #define PIPE_READ_TIMEOUT 250000
431 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
434 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
435 const char *message, gpointer user_data _U_);
437 /* capture related options */
438 static capture_options global_capture_opts;
439 static gboolean quiet = FALSE;
440 static gboolean use_threads = FALSE;
441 static guint64 start_time;
443 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
445 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
447 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
448 int err, gboolean is_close);
450 static void WS_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
452 static void report_new_capture_file(const char *filename);
453 static void report_packet_count(unsigned int packet_count);
454 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
455 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
456 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
458 #define MSG_MAX_LENGTH 4096
460 /* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
462 create_timestamp(void) {
472 * Current time, represented as 100-nanosecond intervals since
473 * January 1, 1601, 00:00:00 UTC.
475 * I think DWORD might be signed, so cast both parts of "now"
476 * to guint32 so that the sign bit doesn't get treated specially.
478 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
479 * might want to use instead.
481 GetSystemTimeAsFileTime(&now);
482 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
483 (guint32)now.dwLowDateTime;
486 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
492 * Subtract difference, in microseconds, between January 1, 1601
493 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
495 timestamp -= G_GUINT64_CONSTANT(11644473600000000);
498 * Current time, represented as seconds and microseconds since
499 * January 1, 1970, 00:00:00 UTC.
501 gettimeofday(&now, NULL);
504 * Convert to delta in microseconds.
506 timestamp = (guint64)(now.tv_sec) * 1000000 +
507 (guint64)(now.tv_usec);
513 print_usage(FILE *output)
515 fprintf(output, "\nUsage: dumpcap [options] ...\n");
516 fprintf(output, "\n");
517 fprintf(output, "Capture interface:\n");
518 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
519 " or for remote capturing, use one of these formats:\n"
520 " rpcap://<host>/<interface>\n"
521 " TCP@<host>:<port>\n");
522 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
523 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
524 fprintf(output, " -p don't capture in promiscuous mode\n");
525 #ifdef HAVE_PCAP_CREATE
526 fprintf(output, " -I capture in monitor mode, if available\n");
528 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
529 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
531 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
532 fprintf(output, " -D print list of interfaces and exit\n");
533 fprintf(output, " -L print list of link-layer types of iface and exit\n");
534 #ifdef HAVE_BPF_IMAGE
535 fprintf(output, " -d print generated BPF code for capture filter\n");
537 fprintf(output, " -k set channel on wifi interface <freq>,[<type>]\n");
538 fprintf(output, " -S print statistics for each interface once per second\n");
539 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
540 fprintf(output, "\n");
541 #ifdef HAVE_PCAP_REMOTE
542 fprintf(output, "RPCAP options:\n");
543 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
544 fprintf(output, " -u use UDP for RPCAP data transfer\n");
545 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
546 #ifdef HAVE_PCAP_SETSAMPLING
547 fprintf(output, " -m <sampling type> use packet sampling\n");
548 fprintf(output, " count:NUM - capture one packet of every NUM\n");
549 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
552 fprintf(output, "Stop conditions:\n");
553 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
554 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
555 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
556 fprintf(output, " files:NUM - stop after NUM files\n");
557 /*fprintf(output, "\n");*/
558 fprintf(output, "Output (files):\n");
559 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
560 fprintf(output, " -g enable group read access on the output file(s)\n");
561 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
562 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
563 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
564 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
565 fprintf(output, " -P use libpcap format instead of pcapng\n");
566 fprintf(output, " --capture-comment <comment>\n");
567 fprintf(output, " add a capture comment to the output file\n");
568 fprintf(output, " (only for pcapng)\n");
569 fprintf(output, "\n");
570 fprintf(output, "Miscellaneous:\n");
571 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
572 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
573 fprintf(output, " within dumpcap\n");
574 fprintf(output, " -t use a separate thread per interface\n");
575 fprintf(output, " -q don't report packet capture counts\n");
576 fprintf(output, " -v print version information and exit\n");
577 fprintf(output, " -h display this help and exit\n");
578 fprintf(output, "\n");
580 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
581 fprintf(output, "You might want to reset it\n");
582 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
583 fprintf(output, "\n");
585 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
586 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
587 fprintf(output, "\n");
588 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
592 * Report an error in command-line arguments.
593 * If we're a capture child, send a message back to the parent, otherwise
597 dumpcap_cmdarg_err(const char *fmt, va_list ap)
601 /* Generate a 'special format' message back to parent */
602 msg = g_strdup_vprintf(fmt, ap);
603 sync_pipe_errmsg_to_parent(2, msg, "");
606 fprintf(stderr, "dumpcap: ");
607 vfprintf(stderr, fmt, ap);
608 fprintf(stderr, "\n");
613 * Report additional information for an error in command-line arguments.
614 * If we're a capture child, send a message back to the parent, otherwise
618 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
622 msg = g_strdup_vprintf(fmt, ap);
623 sync_pipe_errmsg_to_parent(2, msg, "");
626 vfprintf(stderr, fmt, ap);
627 fprintf(stderr, "\n");
633 #if 0 /* Set to enable capability debugging */
634 /* see 'man cap_to_text()' for explanation of output */
635 /* '=' means 'all= ' ie: no capabilities */
636 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
638 print_caps(const char *pfx) {
639 cap_t caps = cap_get_proc();
640 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
641 "%s: EUID: %d Capabilities: %s", pfx,
642 geteuid(), cap_to_text(caps, NULL));
645 print_caps(const char *pfx _U_) {
650 relinquish_all_capabilities(void)
652 /* Drop any and all capabilities this process may have. */
653 /* Allowed whether or not process has any privileges. */
654 cap_t caps = cap_init(); /* all capabilities initialized to off */
655 print_caps("Pre-clear");
656 if (cap_set_proc(caps)) {
657 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
659 print_caps("Post-clear");
665 open_capture_device(capture_options *capture_opts
666 #ifndef HAVE_PCAP_SET_TSTAMP_PRECISION
670 interface_options *interface_opts,
671 char (*open_err_str)[PCAP_ERRBUF_SIZE])
674 #ifdef HAVE_PCAP_CREATE
677 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
678 struct pcap_rmtauth auth;
681 /* Open the network interface to capture from it.
682 Some versions of libpcap may put warnings into the error buffer
683 if they succeed; to tell if that's happened, we have to clear
684 the error buffer, and check if it's still a null string. */
685 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Entering open_capture_device().");
686 (*open_err_str)[0] = '\0';
687 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
689 * If we're opening a remote device, use pcap_open(); that's currently
690 * the only open routine that supports remote devices.
692 if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
693 auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
694 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
695 auth.username = interface_opts->auth_username;
696 auth.password = interface_opts->auth_password;
698 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
699 "Calling pcap_open() using name %s, snaplen %d, promisc_mode %d, datatx_udp %d, nocap_rpcap %d.",
700 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode,
701 interface_opts->datatx_udp, interface_opts->nocap_rpcap);
702 pcap_h = pcap_open(interface_opts->name, interface_opts->snaplen,
704 (interface_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
705 (interface_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
706 (interface_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
707 CAP_READ_TIMEOUT, &auth, *open_err_str);
708 if (pcap_h == NULL) {
709 /* Error - did pcap actually supply an error message? */
710 if ((*open_err_str)[0] == '\0') {
711 /* Work around known WinPcap bug wherein no error message is
712 filled in on a failure to open an rpcap: URL. */
713 g_strlcpy(*open_err_str,
714 "Unknown error (pcap bug; actual error cause not reported)",
715 sizeof *open_err_str);
718 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
719 "pcap_open() returned %p.", (void *)pcap_h);
724 * If we're not opening a remote device, use pcap_create() and
725 * pcap_activate() if we have them, so that we can set the buffer
726 * size, otherwise use pcap_open_live().
728 #ifdef HAVE_PCAP_CREATE
729 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
730 "Calling pcap_create() using %s.", interface_opts->name);
731 pcap_h = pcap_create(interface_opts->name, *open_err_str);
732 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
733 "pcap_create() returned %p.", (void *)pcap_h);
734 if (pcap_h != NULL) {
735 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
736 "Calling pcap_set_snaplen() with snaplen %d.", interface_opts->snaplen);
737 pcap_set_snaplen(pcap_h, interface_opts->snaplen);
738 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
739 "Calling pcap_set_promisc() with promisc_mode %d.", interface_opts->promisc_mode);
740 pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
741 pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
743 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
745 * If we're writing pcap-ng files, try to enable
746 * nanosecond-resolution capture; any code that
747 * can read pcap-ng files must be able to handle
748 * nanosecond-resolution time stamps.
750 * If we're writing pcap files, don't try to enable
751 * nanosecond-resolution capture, as not all code
752 * that reads pcap files recognizes the nanosecond-
753 * resolution pcap file magic number.
755 if (capture_opts->use_pcapng)
756 request_high_resolution_timestamp(pcap_h);
757 #endif /* HAVE_PCAP_SET_TSTAMP_PRECISION */
759 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
760 "buffersize %d.", interface_opts->buffer_size);
761 if (interface_opts->buffer_size != 0) {
762 pcap_set_buffer_size(pcap_h, interface_opts->buffer_size * 1024 * 1024);
764 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
765 "monitor_mode %d.", interface_opts->monitor_mode);
766 if (interface_opts->monitor_mode)
767 pcap_set_rfmon(pcap_h, 1);
768 err = pcap_activate(pcap_h);
769 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
770 "pcap_activate() returned %d.", err);
772 /* Failed to activate, set to NULL */
773 if (err == PCAP_ERROR)
774 g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
776 g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
782 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
783 "pcap_open_live() calling using name %s, snaplen %d, promisc_mode %d.",
784 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode);
785 pcap_h = pcap_open_live(interface_opts->name, interface_opts->snaplen,
786 interface_opts->promisc_mode, CAP_READ_TIMEOUT,
788 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
789 "pcap_open_live() returned %p.", (void *)pcap_h);
791 /* Windows doesn't have pcap_create() yet */
793 /* try to set the capture buffer size -- but not for remote devices */
794 if (pcap_h && interface_opts->buffer_size > 1 &&
795 pcap_setbuff(pcap_h, interface_opts->buffer_size * 1024 * 1024) != 0) {
796 gchar *sync_secondary_msg_str;
798 sync_secondary_msg_str = g_strdup_printf(
799 "Unable to set a capture buffer size of %d MiB.\n"
800 "Capturing using the default size of %d MiB instead.",
801 interface_opts->buffer_size, DEFAULT_CAPTURE_BUFFER_SIZE);
802 report_capture_error("Couldn't set the capture buffer size.",
803 sync_secondary_msg_str);
804 g_free(sync_secondary_msg_str);
809 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_capture_device %s : %s", pcap_h ? "SUCCESS" : "FAILURE", interface_opts->name);
814 get_capture_device_open_failure_messages(const char *open_err_str,
816 char *errmsg, size_t errmsg_len,
817 char *secondary_errmsg,
818 size_t secondary_errmsg_len)
821 const char *libpcap_warn;
822 static const char ppamsg[] = "can't find PPA for ";
825 g_snprintf(errmsg, (gulong) errmsg_len,
826 "The capture session could not be initiated on interface '%s' (%s).",
827 iface, open_err_str);
830 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
832 "In order to capture packets, WinPcap must be installed; see\n"
834 " https://www.winpcap.org/\n"
836 "for a downloadable version of WinPcap and for instructions on how to install\n"
839 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
841 "Please check that \"%s\" is the proper interface.\n"
844 "Help can be found at:\n"
846 " https://wiki.wireshark.org/WinPcap\n"
847 " https://wiki.wireshark.org/CaptureSetup\n",
851 /* If we got a "can't find PPA for X" message, warn the user (who
852 is running dumpcap on HP-UX) that they don't have a version of
853 libpcap that properly handles HP-UX (libpcap 0.6.x and later
854 versions, which properly handle HP-UX, say "can't find /dev/dlpi
855 PPA for X" rather than "can't find PPA for X"). */
856 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
859 "You are running (T)Wireshark with a version of the libpcap library\n"
860 "that doesn't handle HP-UX network devices well; this means that\n"
861 "(T)Wireshark may not be able to capture packets.\n"
863 "To fix this, you should install libpcap 0.6.2, or a later version\n"
864 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
865 "packaged binary form from the Software Porting And Archive Centre\n"
866 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
867 "at the URL lists a number of mirror sites.";
871 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
872 "Please check to make sure you have sufficient permissions, and that you have "
873 "the proper interface or pipe specified.%s", libpcap_warn);
877 /* Set the data link type on a pcap. */
879 set_pcap_linktype(pcap_t *pcap_h, int linktype, char *name,
880 char *errmsg, size_t errmsg_len,
881 char *secondary_errmsg, size_t secondary_errmsg_len)
883 char *set_linktype_err_str;
886 return TRUE; /* just use the default */
887 #ifdef HAVE_PCAP_SET_DATALINK
888 if (pcap_set_datalink(pcap_h, linktype) == 0)
889 return TRUE; /* no error */
890 set_linktype_err_str = pcap_geterr(pcap_h);
892 /* Let them set it to the type it is; reject any other request. */
893 if (get_pcap_linktype(pcap_h, name) == linktype)
894 return TRUE; /* no error */
895 set_linktype_err_str =
896 "That DLT isn't one of the DLTs supported by this device";
898 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type on interface '%s' (%s).",
899 name, set_linktype_err_str);
901 * If the error isn't "XXX is not one of the DLTs supported by this device",
902 * tell the user to tell the Wireshark developers about it.
904 if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
905 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
907 secondary_errmsg[0] = '\0';
912 compile_capture_filter(const char *iface, pcap_t *pcap_h,
913 struct bpf_program *fcode, const char *cfilter)
915 bpf_u_int32 netnum, netmask;
916 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
918 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
920 * Well, we can't get the netmask for this interface; it's used
921 * only for filters that check for broadcast IP addresses, so
922 * we just punt and use 0. It might be nice to warn the user,
923 * but that's a pain in a GUI application, as it'd involve popping
924 * up a message box, and it's not clear how often this would make
925 * a difference (only filters that check for IP broadcast addresses
929 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
934 * Sigh. Older versions of libpcap don't properly declare the
935 * third argument to pcap_compile() as a const pointer. Cast
939 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
945 #ifdef HAVE_BPF_IMAGE
947 show_filter_code(capture_options *capture_opts)
949 interface_options interface_opts;
951 gchar open_err_str[PCAP_ERRBUF_SIZE];
952 char errmsg[MSG_MAX_LENGTH+1];
953 char secondary_errmsg[MSG_MAX_LENGTH+1];
954 struct bpf_program fcode;
955 struct bpf_insn *insn;
959 for (j = 0; j < capture_opts->ifaces->len; j++) {
960 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
961 pcap_h = open_capture_device(capture_opts, &interface_opts, &open_err_str);
962 if (pcap_h == NULL) {
963 /* Open failed; get messages */
964 get_capture_device_open_failure_messages(open_err_str,
966 errmsg, sizeof errmsg,
968 sizeof secondary_errmsg);
969 /* And report them */
970 report_capture_error(errmsg, secondary_errmsg);
974 /* Set the link-layer type. */
975 if (!set_pcap_linktype(pcap_h, interface_opts.linktype, interface_opts.name,
976 errmsg, sizeof errmsg,
977 secondary_errmsg, sizeof secondary_errmsg)) {
979 report_capture_error(errmsg, secondary_errmsg);
983 /* OK, try to compile the capture filter. */
984 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
985 interface_opts.cfilter)) {
987 report_cfilter_error(capture_opts, j, errmsg);
992 /* Now print the filter code. */
993 insn = fcode.bf_insns;
995 for (i = 0; i < fcode.bf_len; insn++, i++)
996 printf("%s\n", bpf_image(insn, i));
998 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
999 /* to remove any suid privileges. */
1000 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
1001 /* (euid/egid have already previously been set to ruid/rgid. */
1002 /* (See comment in main() for details) */
1004 relinquish_special_privs_perm();
1006 relinquish_all_capabilities();
1008 if (capture_child) {
1009 /* Let our parent know we succeeded. */
1010 pipe_write_block(2, SP_SUCCESS, NULL);
1017 * capture_interface_list() is expected to do the right thing to get
1018 * a list of interfaces.
1020 * In most of the programs in the Wireshark suite, "the right thing"
1021 * is to run dumpcap and ask it for the list, because dumpcap may
1022 * be the only program in the suite with enough privileges to get
1025 * In dumpcap itself, however, we obviously can't run dumpcap to
1026 * ask for the list. Therefore, our capture_interface_list() should
1027 * just call get_interface_list().
1030 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
1032 return get_interface_list(err, err_str);
1036 * Get the data-link type for a libpcap device.
1037 * This works around AIX 5.x's non-standard and incompatible-with-the-
1038 * rest-of-the-universe libpcap.
1041 get_pcap_linktype(pcap_t *pch, const char *devicename
1049 const char *ifacename;
1052 linktype = pcap_datalink(pch);
1056 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
1057 * rather than DLT_ values for link-layer types; the ifType values
1058 * for LAN devices are:
1065 * and the ifType value for a loopback device is 24.
1067 * The AIX names for LAN devices begin with:
1074 * and the AIX names for loopback devices begin with "lo".
1076 * (The difference between "Ethernet" and "802.3" is presumably
1077 * whether packets have an Ethernet header, with a packet type,
1078 * or an 802.3 header, with a packet length, followed by an 802.2
1079 * header and possibly a SNAP header.)
1081 * If the device name matches "linktype" interpreted as an ifType
1082 * value, rather than as a DLT_ value, we will assume this is AIX's
1083 * non-standard, incompatible libpcap, rather than a standard libpcap,
1084 * and will map the link-layer type to the standard DLT_ value for
1085 * that link-layer type, as that's what the rest of Wireshark expects.
1087 * (This means the capture files won't be readable by a tcpdump
1088 * linked with AIX's non-standard libpcap, but so it goes. They
1089 * *will* be readable by standard versions of tcpdump, Wireshark,
1092 * XXX - if we conclude we're using AIX libpcap, should we also
1093 * set a flag to cause us to assume the time stamps are in
1094 * seconds-and-nanoseconds form, and to convert them to
1095 * seconds-and-microseconds form before processing them and
1100 * Find the last component of the device name, which is the
1103 ifacename = strchr(devicename, '/');
1104 if (ifacename == NULL)
1105 ifacename = devicename;
1107 /* See if it matches any of the LAN device names. */
1108 if (strncmp(ifacename, "en", 2) == 0) {
1109 if (linktype == 6) {
1111 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
1115 } else if (strncmp(ifacename, "et", 2) == 0) {
1116 if (linktype == 7) {
1118 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
1119 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
1124 } else if (strncmp(ifacename, "tr", 2) == 0) {
1125 if (linktype == 9) {
1127 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
1128 * DLT_IEEE802, which is what's used for Token Ring.
1132 } else if (strncmp(ifacename, "fi", 2) == 0) {
1133 if (linktype == 15) {
1135 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
1139 } else if (strncmp(ifacename, "lo", 2) == 0) {
1140 if (linktype == 24) {
1142 * That's the RFC 1573 value for "software loopback" devices; map it
1143 * to DLT_NULL, which is what's used for loopback devices on BSD.
1153 static data_link_info_t *
1154 create_data_link_info(int dlt)
1156 data_link_info_t *data_link_info;
1159 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
1160 data_link_info->dlt = dlt;
1161 text = pcap_datalink_val_to_name(dlt);
1163 data_link_info->name = g_strdup(text);
1165 data_link_info->name = g_strdup_printf("DLT %d", dlt);
1166 text = pcap_datalink_val_to_description(dlt);
1168 data_link_info->description = g_strdup(text);
1170 data_link_info->description = NULL;
1171 return data_link_info;
1174 #if defined(HAVE_BONDING) && defined(HAVE_PCAP_CREATE)
1176 is_linux_bonding_device(const char *ifname)
1182 fd = socket(PF_INET, SOCK_DGRAM, 0);
1186 memset(&ifr, 0, sizeof ifr);
1187 g_strlcpy(ifr.ifr_name, ifname, sizeof ifr.ifr_name);
1188 memset(&ifb, 0, sizeof ifb);
1189 ifr.ifr_data = (caddr_t)&ifb;
1190 #if defined(SIOCBONDINFOQUERY)
1191 if (ioctl(fd, SIOCBONDINFOQUERY, &ifr) == 0) {
1196 if (ioctl(fd, BOND_INFO_QUERY_OLD, &ifr) == 0) {
1205 #elif defined(HAVE_PCAP_CREATE)
1207 is_linux_bonding_device(const char *ifname _U_)
1214 * Get the capabilities of a network device.
1216 static if_capabilities_t *
1217 get_if_capabilities(interface_options *interface_opts, char **err_str)
1219 if_capabilities_t *caps;
1220 char errbuf[PCAP_ERRBUF_SIZE];
1222 #ifdef HAVE_PCAP_CREATE
1226 #ifdef HAVE_PCAP_LIST_DATALINKS
1230 data_link_info_t *data_link_info;
1233 * Allocate the interface capabilities structure.
1235 caps = (if_capabilities_t *)g_malloc(sizeof *caps);
1238 * WinPcap 4.1.2, and possibly earlier versions, have a bug
1239 * wherein, when an open with an rpcap: URL fails, the error
1240 * message for the error is not copied to errbuf and whatever
1241 * on-the-stack junk is in errbuf is treated as the error
1244 * To work around that (and any other bugs of that sort, we
1245 * initialize errbuf to an empty string. If we get an error
1246 * and the string is empty, we report it as an unknown error.
1247 * (If we *don't* get an error, and the string is *non*-empty,
1248 * that could be a warning returned, such as "can't turn
1249 * promiscuous mode on"; we currently don't do so.)
1252 #ifdef HAVE_PCAP_OPEN
1253 #ifdef HAVE_PCAP_REMOTE
1254 if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
1255 struct pcap_rmtauth auth;
1257 auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
1258 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1259 auth.username = interface_opts->auth_username;
1260 auth.password = interface_opts->auth_password;
1262 pch = pcap_open(interface_opts->name, MIN_PACKET_SIZE, 0, 0, &auth, errbuf);
1265 pch = pcap_open(interface_opts->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1266 caps->can_set_rfmon = FALSE;
1268 if (err_str != NULL)
1269 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1273 #elif defined(HAVE_PCAP_CREATE)
1274 pch = pcap_create(interface_opts->name, errbuf);
1276 if (err_str != NULL)
1277 *err_str = g_strdup(errbuf);
1281 if (is_linux_bonding_device(interface_opts->name)) {
1283 * Linux bonding device; not Wi-Fi, so no monitor mode, and
1284 * calling pcap_can_set_rfmon() might get a "no such device"
1290 * Not a Linux bonding device, so go ahead.
1292 status = pcap_can_set_rfmon(pch);
1296 if (status == PCAP_ERROR)
1297 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1300 *err_str = g_strdup(pcap_statustostr(status));
1306 caps->can_set_rfmon = FALSE;
1307 else if (status == 1) {
1308 caps->can_set_rfmon = TRUE;
1309 if (interface_opts->monitor_mode)
1310 pcap_set_rfmon(pch, 1);
1312 if (err_str != NULL) {
1313 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1321 status = pcap_activate(pch);
1323 /* Error. We ignore warnings (status > 0). */
1324 if (err_str != NULL) {
1325 if (status == PCAP_ERROR)
1326 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1329 *err_str = g_strdup(pcap_statustostr(status));
1336 pch = pcap_open_live(interface_opts->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1337 caps->can_set_rfmon = FALSE;
1339 if (err_str != NULL)
1340 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1345 deflt = get_pcap_linktype(pch, interface_opts->name);
1346 #ifdef HAVE_PCAP_LIST_DATALINKS
1347 nlt = pcap_list_datalinks(pch, &linktypes);
1348 if (nlt == 0 || linktypes == NULL) {
1350 if (err_str != NULL)
1351 *err_str = NULL; /* an empty list doesn't mean an error */
1355 caps->data_link_types = NULL;
1356 for (i = 0; i < nlt; i++) {
1357 data_link_info = create_data_link_info(linktypes[i]);
1360 * XXX - for 802.11, make the most detailed 802.11
1361 * version the default, rather than the one the
1362 * device has as the default?
1364 if (linktypes[i] == deflt)
1365 caps->data_link_types = g_list_prepend(caps->data_link_types,
1368 caps->data_link_types = g_list_append(caps->data_link_types,
1371 #ifdef HAVE_PCAP_FREE_DATALINKS
1372 pcap_free_datalinks(linktypes);
1375 * In Windows, there's no guarantee that if you have a library
1376 * built with one version of the MSVC++ run-time library, and
1377 * it returns a pointer to allocated data, you can free that
1378 * data from a program linked with another version of the
1379 * MSVC++ run-time library.
1381 * This is not an issue on UN*X.
1383 * See the mail threads starting at
1385 * https://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1389 * https://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1392 #define xx_free free /* hack so checkAPIs doesn't complain */
1395 #endif /* HAVE_PCAP_FREE_DATALINKS */
1396 #else /* HAVE_PCAP_LIST_DATALINKS */
1398 data_link_info = create_data_link_info(deflt);
1399 caps->data_link_types = g_list_append(caps->data_link_types,
1401 #endif /* HAVE_PCAP_LIST_DATALINKS */
1405 if (err_str != NULL)
1410 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1412 * Output a machine readable list of the interfaces
1413 * This list is retrieved by the sync_interface_list_open() function
1414 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
1417 print_machine_readable_interfaces(GList *if_list)
1424 char addr_str[ADDRSTRLEN];
1426 if (capture_child) {
1427 /* Let our parent know we succeeded. */
1428 pipe_write_block(2, SP_SUCCESS, NULL);
1431 i = 1; /* Interface id number */
1432 for (if_entry = g_list_first(if_list); if_entry != NULL;
1433 if_entry = g_list_next(if_entry)) {
1434 if_info = (if_info_t *)if_entry->data;
1435 printf("%d. %s\t", i++, if_info->name);
1438 * Print the contents of the if_entry struct in a parseable format.
1439 * Each if_entry element is tab-separated. Addresses are comma-
1442 /* XXX - Make sure our description doesn't contain a tab */
1443 if (if_info->vendor_description != NULL)
1444 printf("%s\t", if_info->vendor_description);
1448 /* XXX - Make sure our friendly name doesn't contain a tab */
1449 if (if_info->friendly_name != NULL)
1450 printf("%s\t", if_info->friendly_name);
1454 printf("%i\t", if_info->type);
1456 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1457 addr = g_slist_next(addr)) {
1458 if (addr != g_slist_nth(if_info->addrs, 0))
1461 if_addr = (if_addr_t *)addr->data;
1462 switch(if_addr->ifat_type) {
1464 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1466 printf("%s", addr_str);
1468 printf("<unknown IPv4>");
1472 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1473 addr_str, ADDRSTRLEN)) {
1474 printf("%s", addr_str);
1476 printf("<unknown IPv6>");
1480 printf("<type unknown %i>", if_addr->ifat_type);
1484 if (if_info->loopback)
1485 printf("\tloopback");
1487 printf("\tnetwork");
1489 printf("\t%s", if_info->extcap);
1496 * If you change the machine-readable output format of this function,
1497 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1500 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1503 data_link_info_t *data_link_info;
1504 const gchar *desc_str;
1506 if (capture_child) {
1507 /* Let our parent know we succeeded. */
1508 pipe_write_block(2, SP_SUCCESS, NULL);
1511 if (caps->can_set_rfmon)
1515 for (lt_entry = caps->data_link_types; lt_entry != NULL;
1516 lt_entry = g_list_next(lt_entry)) {
1517 data_link_info = (data_link_info_t *)lt_entry->data;
1518 if (data_link_info->description != NULL)
1519 desc_str = data_link_info->description;
1521 desc_str = "(not supported)";
1522 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1532 /* Print the number of packets captured for each interface until we're killed. */
1534 print_statistics_loop(gboolean machine_readable)
1536 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1542 char errbuf[PCAP_ERRBUF_SIZE];
1543 struct pcap_stat ps;
1545 if_list = get_interface_list(&err, &err_str);
1546 if (if_list == NULL) {
1548 cmdarg_err("There are no interfaces on which a capture can be done");
1550 cmdarg_err("%s", err_str);
1556 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1557 if_info = (if_info_t *)if_entry->data;
1560 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
1561 * connections. We avoid collecting stats on them.
1563 if (!strncmp(if_info->name, "nf", 2)) {
1564 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
1570 #ifdef HAVE_PCAP_OPEN
1571 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1573 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1577 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1578 if_stat->name = g_strdup(if_info->name);
1580 stat_list = g_list_append(stat_list, if_stat);
1585 cmdarg_err("There are no interfaces on which a capture can be done");
1589 if (capture_child) {
1590 /* Let our parent know we succeeded. */
1591 pipe_write_block(2, SP_SUCCESS, NULL);
1594 if (!machine_readable) {
1595 printf("%-15s %10s %10s\n", "Interface", "Received",
1599 global_ld.go = TRUE;
1600 while (global_ld.go) {
1601 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1602 if_stat = (if_stat_t *)stat_entry->data;
1603 pcap_stats(if_stat->pch, &ps);
1605 if (!machine_readable) {
1606 printf("%-15s %10u %10u\n", if_stat->name,
1607 ps.ps_recv, ps.ps_drop);
1609 printf("%s\t%u\t%u\n", if_stat->name,
1610 ps.ps_recv, ps.ps_drop);
1615 /* If we have a dummy signal pipe check it */
1616 if (!signal_pipe_check_running()) {
1617 global_ld.go = FALSE;
1625 /* XXX - Not reached. Should we look for 'q' in stdin? */
1626 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1627 if_stat = (if_stat_t *)stat_entry->data;
1628 pcap_close(if_stat->pch);
1629 g_free(if_stat->name);
1632 g_list_free(stat_list);
1633 free_interface_list(if_list);
1641 capture_cleanup_handler(DWORD dwCtrlType)
1643 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1644 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1645 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1646 like SIGTERM at least when the machine's shutting down.
1648 For now, if we're running as a command rather than a capture child,
1649 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1650 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1651 in that way on UN*X.
1653 If we're not running as a capture child, we might be running as
1654 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1655 user logs out. (XXX - can we explicitly check whether we're
1656 running as a service?) */
1658 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1659 "Console: Control signal");
1660 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1661 "Console: Control signal, CtrlType: %u", dwCtrlType);
1663 /* Keep capture running if we're a service and a user logs off */
1664 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1665 capture_loop_stop();
1673 capture_cleanup_handler(int signum _U_)
1675 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1676 SIGTERM. We assume that if the user wanted it to keep running
1677 after they logged out, they'd have nohupped it. */
1679 /* Note: don't call g_log() in the signal handler: if we happened to be in
1680 * g_log() in process context when the signal came in, g_log will detect
1681 * the "recursion" and abort.
1684 capture_loop_stop();
1690 report_capture_count(gboolean reportit)
1692 /* Don't print this if we're a capture child. */
1693 if (!capture_child && reportit) {
1694 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packet_count);
1695 /* stderr could be line buffered */
1703 report_counts_for_siginfo(void)
1705 report_capture_count(quiet);
1706 infoprint = FALSE; /* we just reported it */
1710 report_counts_siginfo(int signum _U_)
1712 int sav_errno = errno;
1714 /* If we've been told to delay printing, just set a flag asking
1715 that we print counts (if we're supposed to), otherwise print
1716 the count of packets captured (if we're supposed to). */
1720 report_counts_for_siginfo();
1723 #endif /* SIGINFO */
1726 exit_main(int status)
1729 /* Shutdown windows sockets */
1732 /* can be helpful for debugging */
1733 #ifdef DEBUG_DUMPCAP
1734 printf("Press any key\n");
1745 * If we were linked with libcap (not related to libpcap), make sure we have
1746 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1747 * (See comment in main() for details)
1750 relinquish_privs_except_capture(void)
1752 /* If 'started_with_special_privs' (ie: suid) then enable for
1753 * ourself the NET_ADMIN and NET_RAW capabilities and then
1754 * drop our suid privileges.
1756 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1757 * stuff we don't need (and shouldn't have).
1758 * CAP_NET_RAW: Packet capture (raw sockets).
1761 if (started_with_special_privs()) {
1762 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1763 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1765 cap_t caps = cap_init(); /* all capabilities initialized to off */
1767 print_caps("Pre drop, pre set");
1769 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1770 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1773 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1774 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1776 if (cap_set_proc(caps)) {
1777 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1779 print_caps("Pre drop, post set");
1781 relinquish_special_privs_perm();
1783 print_caps("Post drop, pre set");
1784 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1785 if (cap_set_proc(caps)) {
1786 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1788 print_caps("Post drop, post set");
1794 #endif /* HAVE_LIBCAP */
1796 /* Take care of byte order in the libpcap headers read from pipes.
1797 * (function taken from wiretap/libpcap.c) */
1799 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1802 /* Byte-swap the record header fields. */
1803 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1804 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1805 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1806 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1809 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1810 swapped, in order to match the BPF header layout.
1812 Unfortunately, some files were, according to a comment in the "libpcap"
1813 source, written with version 2.3 in their headers but without the
1814 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1815 would make no sense - we assume that we need to swap them. */
1816 if (hdr->version_major == 2 &&
1817 (hdr->version_minor < 3 ||
1818 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1821 temp = rechdr->orig_len;
1822 rechdr->orig_len = rechdr->incl_len;
1823 rechdr->incl_len = temp;
1827 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1831 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1835 return recv(pipe_fd, buf, (int)sz, 0);
1840 return ws_read(pipe_fd, buf, sz);
1846 * Thread function that reads from a pipe and pushes the data
1847 * to the main application thread.
1850 * XXX Right now we use async queues for basic signaling. The main thread
1851 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1852 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1853 * Iff the read is successful cap_pipe_read pushes an item onto
1854 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1855 * the queues themselves (yet).
1857 * We might want to move some of the cap_pipe_dispatch logic here so that
1858 * we can let cap_thread_read run independently, queuing up multiple reads
1859 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1861 static void *cap_thread_read(void *arg)
1863 pcap_options *pcap_opts;
1866 DWORD b, last_err, bytes_read;
1872 pcap_opts = (pcap_options *)arg;
1873 while (pcap_opts->cap_pipe_err == PIPOK) {
1874 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1875 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1877 while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1878 if ((pcap_opts->from_cap_socket)
1884 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1885 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1888 pcap_opts->cap_pipe_err = PIPEOF;
1892 pcap_opts->cap_pipe_err = PIPERR;
1903 /* If we try to use read() on a named pipe on Windows with partial
1904 * data it appears to return EOF.
1906 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1907 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1912 last_err = GetLastError();
1913 if (last_err == ERROR_MORE_DATA) {
1915 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1916 pcap_opts->cap_pipe_err = PIPEOF;
1920 pcap_opts->cap_pipe_err = PIPERR;
1923 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1924 pcap_opts->cap_pipe_err = PIPEOF;
1931 pcap_opts->cap_pipe_bytes_read = bytes_read;
1932 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1933 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1935 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1941 /* Provide select() functionality for a single file descriptor
1942 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1944 * Returns the same values as select.
1947 cap_pipe_select(int pipe_fd)
1950 struct timeval timeout;
1953 FD_SET(pipe_fd, &rfds);
1955 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1956 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1958 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1961 #define DEF_TCP_PORT 19000
1964 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1966 char *sockname = pipename + 4;
1967 struct sockaddr_in sa;
1974 memset(&sa, 0, sizeof(sa));
1976 p = strchr(sockname, ':');
1978 len = strlen(sockname);
1979 port = DEF_TCP_PORT;
1983 port = strtoul(p + 1, &p, 10);
1984 if (*p || port > 65535) {
1993 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1995 if (inet_pton(AF_INET, buf, &sa.sin_addr) <= 0) {
1999 sa.sin_family = AF_INET;
2000 sa.sin_port = g_htons((u_short)port);
2002 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
2003 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
2005 LPTSTR errorText = NULL;
2008 lastError = WSAGetLastError();
2009 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2010 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2011 FORMAT_MESSAGE_IGNORE_INSERTS,
2012 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2013 (LPTSTR)&errorText, 0, NULL);
2015 g_snprintf(errmsg, errmsgl,
2016 "The capture session could not be initiated due to the socket error: \n"
2018 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
2020 LocalFree(errorText);
2022 " %d: %s", errno, g_strerror(errno));
2024 pcap_opts->cap_pipe_err = PIPERR;
2027 cap_pipe_close(fd, TRUE);
2031 pcap_opts->from_cap_socket = TRUE;
2035 g_snprintf(errmsg, errmsgl,
2036 "The capture session could not be initiated because\n"
2037 "\"%s\" is not a valid socket specification", pipename);
2038 pcap_opts->cap_pipe_err = PIPERR;
2042 /* Wrapper: distinguish between closesocket on Windows; use ws_close
2046 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
2050 closesocket(pipe_fd);
2057 /* Mimic pcap_open_live() for pipe captures
2059 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
2060 * open it, and read the header.
2062 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
2063 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
2065 cap_pipe_open_live(char *pipename,
2066 pcap_options *pcap_opts,
2067 struct pcap_hdr *hdr,
2068 char *errmsg, int errmsgl)
2071 ws_statb64 pipe_stat;
2072 struct sockaddr_un sa;
2076 interface_options interface_opts;
2078 char* extcap_pipe_name;
2079 gboolean extcap_pipe;
2083 int fd = -1, sel_ret;
2086 pcap_opts->cap_pipe_fd = -1;
2088 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2091 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
2094 * XXX - this blocks until a pcap per-file header has been written to
2095 * the pipe, so it could block indefinitely.
2097 if (strcmp(pipename, "-") == 0) {
2099 fd = 0; /* read from stdin */
2101 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
2103 } else if (!strncmp(pipename, "TCP@", 4)) {
2104 if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
2109 if (ws_stat64(pipename, &pipe_stat) < 0) {
2110 if (errno == ENOENT || errno == ENOTDIR)
2111 pcap_opts->cap_pipe_err = PIPNEXIST;
2113 g_snprintf(errmsg, errmsgl,
2114 "The capture session could not be initiated "
2115 "due to error getting information on pipe/socket: %s", g_strerror(errno));
2116 pcap_opts->cap_pipe_err = PIPERR;
2120 if (S_ISFIFO(pipe_stat.st_mode)) {
2121 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
2123 g_snprintf(errmsg, errmsgl,
2124 "The capture session could not be initiated "
2125 "due to error on pipe open: %s", g_strerror(errno));
2126 pcap_opts->cap_pipe_err = PIPERR;
2129 } else if (S_ISSOCK(pipe_stat.st_mode)) {
2130 fd = socket(AF_UNIX, SOCK_STREAM, 0);
2132 g_snprintf(errmsg, errmsgl,
2133 "The capture session could not be initiated "
2134 "due to error on socket create: %s", g_strerror(errno));
2135 pcap_opts->cap_pipe_err = PIPERR;
2138 sa.sun_family = AF_UNIX;
2140 * The Single UNIX Specification says:
2142 * The size of sun_path has intentionally been left undefined.
2143 * This is because different implementations use different sizes.
2144 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
2145 * of 104. Since most implementations originate from BSD versions,
2146 * the size is typically in the range 92 to 108.
2148 * Applications should not assume a particular length for sun_path
2149 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
2153 * The <sys/un.h> header shall define the sockaddr_un structure,
2154 * which shall include at least the following members:
2156 * sa_family_t sun_family Address family.
2157 * char sun_path[] Socket pathname.
2159 * so we assume that it's an array, with a specified size,
2160 * and that the size reflects the maximum path length.
2162 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
2163 /* Path name too long */
2164 g_snprintf(errmsg, errmsgl,
2165 "The capture session coud not be initiated "
2166 "due to error on socket connect: Path name too long");
2167 pcap_opts->cap_pipe_err = PIPERR;
2171 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
2173 g_snprintf(errmsg, errmsgl,
2174 "The capture session coud not be initiated "
2175 "due to error on socket connect: %s", g_strerror(errno));
2176 pcap_opts->cap_pipe_err = PIPERR;
2181 if (S_ISCHR(pipe_stat.st_mode)) {
2183 * Assume the user specified an interface on a system where
2184 * interfaces are in /dev. Pretend we haven't seen it.
2186 pcap_opts->cap_pipe_err = PIPNEXIST;
2188 g_snprintf(errmsg, errmsgl,
2189 "The capture session could not be initiated because\n"
2190 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
2191 pcap_opts->cap_pipe_err = PIPERR;
2196 #define PIPE_STR "\\pipe\\"
2197 /* Under Windows, named pipes _must_ have the form
2198 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
2200 pncopy = g_strdup(pipename);
2201 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
2202 pos = strchr(pncopy + 3, '\\');
2203 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
2210 g_snprintf(errmsg, errmsgl,
2211 "The capture session could not be initiated because\n"
2212 "\"%s\" is neither an interface nor a pipe", pipename);
2213 pcap_opts->cap_pipe_err = PIPNEXIST;
2217 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
2219 extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
2220 extcap_pipe = strstr(interface_opts.name, extcap_pipe_name) ? TRUE : FALSE;
2221 g_free(extcap_pipe_name);
2224 /* Wait for the pipe to appear */
2229 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
2232 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
2233 OPEN_EXISTING, 0, NULL);
2235 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
2238 if (GetLastError() != ERROR_PIPE_BUSY) {
2239 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2240 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2241 g_snprintf(errmsg, errmsgl,
2242 "The capture session on \"%s\" could not be started "
2243 "due to error on pipe open: %s (error %d)",
2244 pipename, utf_16to8(err_str), GetLastError());
2246 pcap_opts->cap_pipe_err = PIPERR;
2250 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
2251 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2252 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2253 g_snprintf(errmsg, errmsgl,
2254 "The capture session on \"%s\" timed out during "
2255 "pipe open: %s (error %d)",
2256 pipename, utf_16to8(err_str), GetLastError());
2258 pcap_opts->cap_pipe_err = PIPERR;
2265 pcap_opts->from_cap_pipe = TRUE;
2268 if (pcap_opts->from_cap_socket)
2271 /* read the pcap header */
2273 while (bytes_read < sizeof magic) {
2275 g_snprintf(errmsg, errmsgl, "Invalid file descriptor");
2279 sel_ret = cap_pipe_select(fd);
2281 g_snprintf(errmsg, errmsgl,
2282 "Unexpected error from select: %s", g_strerror(errno));
2284 } else if (sel_ret > 0) {
2285 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
2286 sizeof magic-bytes_read,
2287 pcap_opts->from_cap_socket);
2290 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2292 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2302 #if GLIB_CHECK_VERSION(2,31,0)
2303 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
2305 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
2308 pcap_opts->cap_pipe_buf = (char *) &magic;
2309 pcap_opts->cap_pipe_bytes_read = 0;
2310 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
2311 /* We don't have to worry about cap_pipe_read_mtx here */
2312 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2313 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2314 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2315 if (pcap_opts->cap_pipe_bytes_read == 0)
2316 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2318 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2327 case PCAP_NSEC_MAGIC:
2328 /* Host that wrote it has our byte order, and was running
2329 a program using either standard or ss990417 libpcap. */
2330 pcap_opts->cap_pipe_byte_swapped = FALSE;
2331 pcap_opts->cap_pipe_modified = FALSE;
2332 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
2334 case PCAP_MODIFIED_MAGIC:
2335 /* Host that wrote it has our byte order, but was running
2336 a program using either ss990915 or ss991029 libpcap. */
2337 pcap_opts->cap_pipe_byte_swapped = FALSE;
2338 pcap_opts->cap_pipe_modified = TRUE;
2340 case PCAP_SWAPPED_MAGIC:
2341 case PCAP_SWAPPED_NSEC_MAGIC:
2342 /* Host that wrote it has a byte order opposite to ours,
2343 and was running a program using either standard or
2344 ss990417 libpcap. */
2345 pcap_opts->cap_pipe_byte_swapped = TRUE;
2346 pcap_opts->cap_pipe_modified = FALSE;
2347 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2349 case PCAP_SWAPPED_MODIFIED_MAGIC:
2350 /* Host that wrote it out has a byte order opposite to
2351 ours, and was running a program using either ss990915
2352 or ss991029 libpcap. */
2353 pcap_opts->cap_pipe_byte_swapped = TRUE;
2354 pcap_opts->cap_pipe_modified = TRUE;
2357 /* Not a "libpcap" type we know about. */
2358 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2363 if (pcap_opts->from_cap_socket)
2366 /* Read the rest of the header */
2368 while (bytes_read < sizeof(struct pcap_hdr)) {
2369 sel_ret = cap_pipe_select(fd);
2371 g_snprintf(errmsg, errmsgl,
2372 "Unexpected error from select: %s", g_strerror(errno));
2374 } else if (sel_ret > 0) {
2375 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2376 sizeof(struct pcap_hdr) - bytes_read,
2377 pcap_opts->from_cap_socket);
2380 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2382 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
2392 pcap_opts->cap_pipe_buf = (char *) hdr;
2393 pcap_opts->cap_pipe_bytes_read = 0;
2394 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
2395 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2396 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2397 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2398 if (pcap_opts->cap_pipe_bytes_read == 0)
2399 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2401 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
2408 if (pcap_opts->cap_pipe_byte_swapped) {
2409 /* Byte-swap the header fields about which we care. */
2410 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
2411 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
2412 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
2413 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
2415 pcap_opts->linktype = hdr->network;
2417 if (hdr->version_major < 2) {
2418 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2422 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2423 pcap_opts->cap_pipe_err = PIPOK;
2424 pcap_opts->cap_pipe_fd = fd;
2428 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2429 pcap_opts->cap_pipe_err = PIPERR;
2430 cap_pipe_close(fd, pcap_opts->from_cap_socket);
2431 pcap_opts->cap_pipe_fd = -1;
2435 /* We read one record from the pipe, take care of byte order in the record
2436 * header, write the record to the capture file, and update capture statistics. */
2438 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2440 struct pcap_pkthdr phdr;
2441 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2444 #if !GLIB_CHECK_VERSION(2,31,18)
2452 #ifdef LOG_CAPTURE_VERBOSE
2453 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2456 switch (pcap_opts->cap_pipe_state) {
2458 case STATE_EXPECT_REC_HDR:
2460 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2463 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2464 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2465 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2466 pcap_opts->cap_pipe_bytes_read = 0;
2469 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2470 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2471 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2476 case STATE_READ_REC_HDR:
2478 if (pcap_opts->from_cap_socket)
2481 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2482 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
2485 result = PD_PIPE_EOF;
2487 result = PD_PIPE_ERR;
2490 pcap_opts->cap_pipe_bytes_read += b;
2494 #if GLIB_CHECK_VERSION(2,31,18)
2495 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2497 g_get_current_time(&wait_time);
2498 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2499 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2501 if (pcap_opts->cap_pipe_err == PIPEOF) {
2502 result = PD_PIPE_EOF;
2504 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2505 result = PD_PIPE_ERR;
2513 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2515 result = PD_REC_HDR_READ;
2518 case STATE_EXPECT_DATA:
2520 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2523 pcap_opts->cap_pipe_state = STATE_READ_DATA;
2524 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2525 pcap_opts->cap_pipe_bytes_read = 0;
2528 pcap_opts->cap_pipe_buf = (char *) data;
2529 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2530 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2535 case STATE_READ_DATA:
2537 if (pcap_opts->from_cap_socket)
2540 b = cap_pipe_read(pcap_opts->cap_pipe_fd,
2541 data+pcap_opts->cap_pipe_bytes_read,
2542 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
2543 pcap_opts->from_cap_socket);
2546 result = PD_PIPE_EOF;
2548 result = PD_PIPE_ERR;
2551 pcap_opts->cap_pipe_bytes_read += b;
2556 #if GLIB_CHECK_VERSION(2,31,18)
2557 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2559 g_get_current_time(&wait_time);
2560 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2561 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2562 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2563 if (pcap_opts->cap_pipe_err == PIPEOF) {
2564 result = PD_PIPE_EOF;
2566 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2567 result = PD_PIPE_ERR;
2575 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2577 result = PD_DATA_READ;
2581 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2584 } /* switch (pcap_opts->cap_pipe_state) */
2587 * We've now read as much data as we were expecting, so process it.
2591 case PD_REC_HDR_READ:
2592 /* We've read the header. Take care of byte order. */
2593 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2594 &pcap_opts->cap_pipe_rechdr.hdr);
2595 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2596 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2597 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2601 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2602 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2605 /* no data to read? fall through */
2608 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2609 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2610 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2611 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2612 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2615 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2617 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2619 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2623 pcap_opts->cap_pipe_err = PIPEOF;
2628 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2629 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2630 g_snprintf(errmsg, errmsgl,
2631 "Error reading from pipe: %s (error %d)",
2632 utf_16to8(err_str), GetLastError());
2635 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2643 pcap_opts->cap_pipe_err = PIPERR;
2644 /* Return here rather than inside the switch to prevent GCC warning */
2649 /** Open the capture input file (pcap or capture pipe).
2650 * Returns TRUE if it succeeds, FALSE otherwise. */
2652 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2653 char *errmsg, size_t errmsg_len,
2654 char *secondary_errmsg, size_t secondary_errmsg_len)
2656 gchar open_err_str[PCAP_ERRBUF_SIZE];
2657 gchar *sync_msg_str;
2658 interface_options interface_opts;
2659 pcap_options *pcap_opts;
2663 WORD wVersionRequested;
2667 /* XXX - opening Winsock on tshark? */
2669 /* Initialize Windows Socket if we are in a Win32 OS
2670 This needs to be done before querying the interface for network/netmask */
2672 /* XXX - do we really require 1.1 or earlier?
2673 Are there any versions that support only 2.0 or higher? */
2674 wVersionRequested = MAKEWORD(1, 1);
2675 err = WSAStartup(wVersionRequested, &wsaData);
2679 case WSASYSNOTREADY:
2680 g_snprintf(errmsg, (gulong) errmsg_len,
2681 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2684 case WSAVERNOTSUPPORTED:
2685 g_snprintf(errmsg, (gulong) errmsg_len,
2686 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2687 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2690 case WSAEINPROGRESS:
2691 g_snprintf(errmsg, (gulong) errmsg_len,
2692 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2696 g_snprintf(errmsg, (gulong) errmsg_len,
2697 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2701 g_snprintf(errmsg, (gulong) errmsg_len,
2702 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2706 g_snprintf(errmsg, (gulong) errmsg_len,
2707 "Couldn't initialize Windows Sockets: error %d", err);
2710 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2714 if ((use_threads == FALSE) &&
2715 (capture_opts->ifaces->len > 1)) {
2716 g_snprintf(errmsg, (gulong) errmsg_len,
2717 "Using threads is required for capturing on multiple interfaces.");
2721 for (i = 0; i < capture_opts->ifaces->len; i++) {
2722 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2723 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2724 if (pcap_opts == NULL) {
2725 g_snprintf(errmsg, (gulong) errmsg_len,
2726 "Could not allocate memory.");
2729 pcap_opts->received = 0;
2730 pcap_opts->dropped = 0;
2731 pcap_opts->flushed = 0;
2732 pcap_opts->pcap_h = NULL;
2733 #ifdef MUST_DO_SELECT
2734 pcap_opts->pcap_fd = -1;
2736 pcap_opts->pcap_err = FALSE;
2737 pcap_opts->interface_id = i;
2738 pcap_opts->tid = NULL;
2739 pcap_opts->snaplen = 0;
2740 pcap_opts->linktype = -1;
2741 pcap_opts->ts_nsec = FALSE;
2742 pcap_opts->from_cap_pipe = FALSE;
2743 pcap_opts->from_cap_socket = FALSE;
2744 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2745 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2747 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2749 pcap_opts->cap_pipe_fd = -1;
2750 pcap_opts->cap_pipe_modified = FALSE;
2751 pcap_opts->cap_pipe_byte_swapped = FALSE;
2753 pcap_opts->cap_pipe_buf = NULL;
2755 pcap_opts->cap_pipe_bytes_to_read = 0;
2756 pcap_opts->cap_pipe_bytes_read = 0;
2757 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2758 pcap_opts->cap_pipe_err = PIPOK;
2760 #if GLIB_CHECK_VERSION(2,31,0)
2761 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2762 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2764 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2766 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2767 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2769 g_array_append_val(ld->pcaps, pcap_opts);
2771 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2772 pcap_opts->pcap_h = open_capture_device(capture_opts, &interface_opts, &open_err_str);
2774 if (pcap_opts->pcap_h != NULL) {
2775 /* we've opened "iface" as a network device */
2777 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2778 /* Find out if we're getting nanosecond-precision time stamps */
2779 pcap_opts->ts_nsec = have_high_resolution_timestamp(pcap_opts->pcap_h);
2782 #if defined(HAVE_PCAP_SETSAMPLING)
2783 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2784 struct pcap_samp *samp;
2786 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2787 switch (interface_opts.sampling_method) {
2788 case CAPTURE_SAMP_BY_COUNT:
2789 samp->method = PCAP_SAMP_1_EVERY_N;
2792 case CAPTURE_SAMP_BY_TIMER:
2793 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2797 sync_msg_str = g_strdup_printf(
2798 "Unknown sampling method %d specified,\n"
2799 "continue without packet sampling",
2800 interface_opts.sampling_method);
2801 report_capture_error("Couldn't set the capture "
2802 "sampling", sync_msg_str);
2803 g_free(sync_msg_str);
2805 samp->value = interface_opts.sampling_param;
2807 report_capture_error("Couldn't set the capture sampling",
2808 "Cannot get packet sampling data structure");
2813 /* setting the data link type only works on real interfaces */
2814 if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2816 secondary_errmsg, secondary_errmsg_len)) {
2819 pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2821 /* We couldn't open "iface" as a network device. */
2822 /* Try to open it as a pipe */
2823 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2826 if (pcap_opts->cap_pipe_fd == -1) {
2828 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2830 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2831 /* Pipe doesn't exist, so output message for interface */
2832 get_capture_device_open_failure_messages(open_err_str,
2833 interface_opts.name,
2837 secondary_errmsg_len);
2840 * Else pipe (or file) does exist and cap_pipe_open_live() has
2845 /* cap_pipe_open_live() succeeded; don't want
2846 error message from pcap_open_live() */
2847 open_err_str[0] = '\0';
2851 /* XXX - will this work for tshark? */
2852 #ifdef MUST_DO_SELECT
2853 if (!pcap_opts->from_cap_pipe) {
2854 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2855 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2857 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2862 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2863 returned a warning; print it, but keep capturing. */
2864 if (open_err_str[0] != '\0') {
2865 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2866 report_capture_error(sync_msg_str, "");
2867 g_free(sync_msg_str);
2869 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2870 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2873 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2874 /* to remove any suid privileges. */
2875 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2876 /* (euid/egid have already previously been set to ruid/rgid. */
2877 /* (See comment in main() for details) */
2879 relinquish_special_privs_perm();
2881 relinquish_all_capabilities();
2886 /* close the capture input file (pcap or capture pipe) */
2887 static void capture_loop_close_input(loop_data *ld)
2890 pcap_options *pcap_opts;
2892 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2894 for (i = 0; i < ld->pcaps->len; i++) {
2895 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2896 /* if open, close the capture pipe "input file" */
2897 if (pcap_opts->cap_pipe_fd >= 0) {
2898 g_assert(pcap_opts->from_cap_pipe);
2899 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2900 pcap_opts->cap_pipe_fd = -1;
2903 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2904 CloseHandle(pcap_opts->cap_pipe_h);
2905 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2908 /* if open, close the pcap "input file" */
2909 if (pcap_opts->pcap_h != NULL) {
2910 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2911 pcap_close(pcap_opts->pcap_h);
2912 pcap_opts->pcap_h = NULL;
2919 /* Shut down windows sockets */
2925 /* init the capture filter */
2926 static initfilter_status_t
2927 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2928 const gchar * name, const gchar * cfilter)
2930 struct bpf_program fcode;
2932 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2934 /* capture filters only work on real interfaces */
2935 if (cfilter && !from_cap_pipe) {
2936 /* A capture filter was specified; set it up. */
2937 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2938 /* Treat this specially - our caller might try to compile this
2939 as a display filter and, if that succeeds, warn the user that
2940 the display and capture filter syntaxes are different. */
2941 return INITFILTER_BAD_FILTER;
2943 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2944 #ifdef HAVE_PCAP_FREECODE
2945 pcap_freecode(&fcode);
2947 return INITFILTER_OTHER_ERROR;
2949 #ifdef HAVE_PCAP_FREECODE
2950 pcap_freecode(&fcode);
2954 return INITFILTER_NO_ERROR;
2958 /* set up to write to the already-opened capture output file/files */
2960 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2964 pcap_options *pcap_opts;
2965 interface_options interface_opts;
2966 gboolean successful;
2968 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2970 if ((capture_opts->use_pcapng == FALSE) &&
2971 (capture_opts->ifaces->len > 1)) {
2972 g_snprintf(errmsg, errmsg_len,
2973 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
2977 /* Set up to write to the capture file. */
2978 if (capture_opts->multi_files_on) {
2979 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2981 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2982 if (ld->pdh == NULL) {
2987 if (capture_opts->use_pcapng) {
2989 GString *os_info_str;
2991 os_info_str = g_string_new("");
2992 get_os_version_info(os_info_str);
2994 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2995 successful = pcapng_write_session_header_block(ld->pdh,
2996 (const char *)capture_opts->capture_comment, /* Comment*/
2998 os_info_str->str, /* OS*/
3000 -1, /* section_length */
3005 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3006 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3007 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
3008 if (pcap_opts->from_cap_pipe) {
3009 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
3011 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
3013 successful = pcapng_write_interface_description_block(global_ld.pdh,
3014 NULL, /* OPT_COMMENT 1 */
3015 interface_opts.name, /* IDB_NAME 2 */
3016 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3017 interface_opts.cfilter, /* IDB_FILTER 11 */
3018 os_info_str->str, /* IDB_OS 12 */
3019 pcap_opts->linktype,
3021 &(global_ld.bytes_written),
3022 0, /* IDB_IF_SPEED 8 */
3023 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3027 g_string_free(os_info_str, TRUE);
3030 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
3031 if (pcap_opts->from_cap_pipe) {
3032 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
3034 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
3036 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
3037 pcap_opts->ts_nsec, &ld->bytes_written, &err);
3045 if (ld->pdh == NULL) {
3046 /* We couldn't set up to write to the capture file. */
3047 /* XXX - use cf_open_error_message from tshark instead? */
3052 g_snprintf(errmsg, errmsg_len,
3053 "The file to which the capture would be"
3054 " saved (\"%s\") could not be opened: Error %d.",
3055 capture_opts->save_file, err);
3057 g_snprintf(errmsg, errmsg_len,
3058 "The file to which the capture would be"
3059 " saved (\"%s\") could not be opened: %s.",
3060 capture_opts->save_file, g_strerror(err));
3072 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
3076 pcap_options *pcap_opts;
3077 guint64 end_time = create_timestamp();
3079 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
3081 if (capture_opts->multi_files_on) {
3082 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
3084 if (capture_opts->use_pcapng) {
3085 for (i = 0; i < global_ld.pcaps->len; i++) {
3086 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3087 if (!pcap_opts->from_cap_pipe) {
3088 guint64 isb_ifrecv, isb_ifdrop;
3089 struct pcap_stat stats;
3091 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
3092 isb_ifrecv = pcap_opts->received;
3093 isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
3095 isb_ifrecv = G_MAXUINT64;
3096 isb_ifdrop = G_MAXUINT64;
3098 pcapng_write_interface_statistics_block(ld->pdh,
3101 "Counters provided by dumpcap",
3110 if (fclose(ld->pdh) == EOF) {
3111 if (err_close != NULL) {
3121 /* dispatch incoming packets (pcap or capture pipe)
3123 * Waits for incoming packets to be available, and calls pcap_dispatch()
3124 * to cause them to be processed.
3126 * Returns the number of packets which were processed.
3128 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3129 * packet-batching behaviour does not cause packets to get held back
3133 capture_loop_dispatch(loop_data *ld,
3134 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
3137 gint packet_count_before;
3138 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
3143 packet_count_before = ld->packet_count;
3144 if (pcap_opts->from_cap_pipe) {
3145 /* dispatch from capture pipe */
3146 #ifdef LOG_CAPTURE_VERBOSE
3147 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3150 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
3152 if (sel_ret < 0 && errno != EINTR) {
3153 g_snprintf(errmsg, errmsg_len,
3154 "Unexpected error from select: %s", g_strerror(errno));
3155 report_capture_error(errmsg, please_report);
3160 * "select()" says we can read from the pipe without blocking
3163 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
3173 /* dispatch from pcap */
3174 #ifdef MUST_DO_SELECT
3176 * If we have "pcap_get_selectable_fd()", we use it to get the
3177 * descriptor on which to select; if that's -1, it means there
3178 * is no descriptor on which you can do a "select()" (perhaps
3179 * because you're capturing on a special device, and that device's
3180 * driver unfortunately doesn't support "select()", in which case
3181 * we don't do the select - which means it might not be possible
3182 * to stop a capture until a packet arrives. If that's unacceptable,
3183 * plead with whoever supplies the software for that device to add
3184 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3185 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3186 * later, so it can use pcap_breakloop().
3188 #ifdef LOG_CAPTURE_VERBOSE
3189 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3191 if (pcap_opts->pcap_fd != -1) {
3192 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
3195 * "select()" says we can read from it without blocking; go for
3198 * We don't have pcap_breakloop(), so we only process one packet
3199 * per pcap_dispatch() call, to allow a signal to stop the
3200 * processing immediately, rather than processing all packets
3201 * in a batch before quitting.
3204 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3206 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3210 /* Error, rather than pcap_breakloop(). */
3211 pcap_opts->pcap_err = TRUE;
3213 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3216 if (sel_ret < 0 && errno != EINTR) {
3217 g_snprintf(errmsg, errmsg_len,
3218 "Unexpected error from select: %s", g_strerror(errno));
3219 report_capture_error(errmsg, please_report);
3225 #endif /* MUST_DO_SELECT */
3227 /* dispatch from pcap without select */
3229 #ifdef LOG_CAPTURE_VERBOSE
3230 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3234 * On Windows, we don't support asynchronously telling a process to
3235 * stop capturing; instead, we check for an indication on a pipe
3236 * after processing packets. We therefore process only one packet
3237 * at a time, so that we can check the pipe after every packet.
3240 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3242 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3246 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3248 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3253 /* Error, rather than pcap_breakloop(). */
3254 pcap_opts->pcap_err = TRUE;
3256 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3258 #else /* pcap_next_ex */
3259 #ifdef LOG_CAPTURE_VERBOSE
3260 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3262 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3265 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3266 * see https://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
3267 * This should be fixed in the WinPcap 4.0 alpha release.
3269 * For reference, an example remote interface:
3270 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3273 /* emulate dispatch from pcap */
3276 struct pcap_pkthdr *pkt_header;
3281 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
3283 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3285 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3290 pcap_opts->pcap_err = TRUE;
3294 #endif /* pcap_next_ex */
3298 #ifdef LOG_CAPTURE_VERBOSE
3299 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3302 return ld->packet_count - packet_count_before;
3306 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3307 * want to grab only the characters between the '{' and '}' delimiters.
3309 * Returns a GString that must be freed with g_string_free(). */
3311 isolate_uuid(const char *iface)
3316 ptr = strchr(iface, '{');
3318 return g_string_new(iface);
3319 gstr = g_string_new(ptr + 1);
3321 ptr = strchr(gstr->str, '}');
3325 gstr = g_string_truncate(gstr, ptr - gstr->str);
3330 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3331 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3333 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3334 char *errmsg, int errmsg_len)
3337 gchar *capfile_name;
3339 gboolean is_tempfile;
3341 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3342 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3344 if (capture_opts->save_file != NULL) {
3345 /* We return to the caller while the capture is in progress.
3346 * Therefore we need to take a copy of save_file in
3347 * case the caller destroys it after we return.
3349 capfile_name = g_strdup(capture_opts->save_file);
3351 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3352 if (capture_opts->multi_files_on) {
3353 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3354 g_snprintf(errmsg, errmsg_len,
3355 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3356 g_free(capfile_name);
3359 if (strcmp(capfile_name, "-") == 0) {
3360 /* write to stdout */
3363 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3364 _setmode(1, O_BINARY);
3367 } /* if (...output_to_pipe ... */
3370 if (capture_opts->multi_files_on) {
3371 /* ringbuffer is enabled */
3372 *save_file_fd = ringbuf_init(capfile_name,
3373 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3374 capture_opts->group_read_access);
3376 /* we need the ringbuf name */
3377 if (*save_file_fd != -1) {
3378 g_free(capfile_name);
3379 capfile_name = g_strdup(ringbuf_current_filename());
3382 /* Try to open/create the specified file for use as a capture buffer. */
3383 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
3384 (capture_opts->group_read_access) ? 0640 : 0600);
3387 is_tempfile = FALSE;
3389 /* Choose a random name for the temporary capture buffer */
3390 if (global_capture_opts.ifaces->len > 1) {
3391 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3394 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
3396 /* use the generic portion of the interface guid to form the basis of the filename */
3397 if (strncmp("NPF_{", basename, 5)==0)
3399 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3401 iface = isolate_uuid(basename);
3403 basename = g_strdup(iface->str);
3404 g_string_free(iface, TRUE);
3407 /* generate the temp file name prefix...
3408 * It would be nice if we could specify a pcapng/pcap filename suffix,
3409 * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
3410 if (capture_opts->use_pcapng) {
3411 prefix = g_strconcat("wireshark_pcapng_", basename, NULL);
3413 prefix = g_strconcat("wireshark_pcap_", basename, NULL);
3417 *save_file_fd = create_tempfile(&tmpname, prefix);
3419 capfile_name = g_strdup(tmpname);
3423 /* did we fail to open the output file? */
3424 if (*save_file_fd == -1) {
3426 g_snprintf(errmsg, errmsg_len,
3427 "The temporary file to which the capture would be saved (\"%s\") "
3428 "could not be opened: %s.", capfile_name, g_strerror(errno));
3430 if (capture_opts->multi_files_on) {
3431 ringbuf_error_cleanup();
3434 g_snprintf(errmsg, errmsg_len,
3435 "The file to which the capture would be saved (\"%s\") "
3436 "could not be opened: %s.", capfile_name,
3439 g_free(capfile_name);
3443 if (capture_opts->save_file != NULL) {
3444 g_free(capture_opts->save_file);
3446 capture_opts->save_file = capfile_name;
3447 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3448 "g_free(capfile_name)". */
3454 /* Do the work of handling either the file size or file duration capture
3455 conditions being reached, and switching files or stopping. */
3457 do_file_switch_or_stop(capture_options *capture_opts,
3458 condition *cnd_autostop_files,
3459 condition *cnd_autostop_size,
3460 condition *cnd_file_duration)
3463 pcap_options *pcap_opts;
3464 interface_options interface_opts;
3465 gboolean successful;
3467 if (capture_opts->multi_files_on) {
3468 if (cnd_autostop_files != NULL &&
3469 cnd_eval(cnd_autostop_files, (guint64)++global_ld.autostop_files)) {
3470 /* no files left: stop here */
3471 global_ld.go = FALSE;
3475 /* Switch to the next ringbuffer file */
3476 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3477 &global_ld.save_file_fd, &global_ld.err)) {
3479 /* File switch succeeded: reset the conditions */
3480 global_ld.bytes_written = 0;
3481 if (capture_opts->use_pcapng) {
3483 GString *os_info_str;
3485 os_info_str = g_string_new("");
3486 get_os_version_info(os_info_str);
3488 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
3489 successful = pcapng_write_session_header_block(global_ld.pdh,
3492 os_info_str->str, /* OS */
3494 -1, /* section_length */
3495 &(global_ld.bytes_written),
3499 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3500 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3501 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3502 successful = pcapng_write_interface_description_block(global_ld.pdh,
3503 NULL, /* OPT_COMMENT 1 */
3504 interface_opts.name, /* IDB_NAME 2 */
3505 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3506 interface_opts.cfilter, /* IDB_FILTER 11 */
3507 os_info_str->str, /* IDB_OS 12 */
3508 pcap_opts->linktype,
3510 &(global_ld.bytes_written),
3511 0, /* IDB_IF_SPEED 8 */
3512 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3516 g_string_free(os_info_str, TRUE);
3519 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3520 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3521 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3524 fclose(global_ld.pdh);
3525 global_ld.pdh = NULL;
3526 global_ld.go = FALSE;
3529 if (cnd_autostop_size)
3530 cnd_reset(cnd_autostop_size);
3531 if (cnd_file_duration)
3532 cnd_reset(cnd_file_duration);
3533 fflush(global_ld.pdh);
3535 report_packet_count(global_ld.inpkts_to_sync_pipe);
3536 global_ld.inpkts_to_sync_pipe = 0;
3537 report_new_capture_file(capture_opts->save_file);
3539 /* File switch failed: stop here */
3540 global_ld.go = FALSE;
3544 /* single file, stop now */
3545 global_ld.go = FALSE;
3552 pcap_read_handler(void* arg)
3554 pcap_options *pcap_opts;
3555 char errmsg[MSG_MAX_LENGTH+1];
3557 pcap_opts = (pcap_options *)arg;
3559 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3560 pcap_opts->interface_id);
3562 while (global_ld.go) {
3563 /* dispatch incoming packets */
3564 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3566 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3567 pcap_opts->interface_id);
3568 g_thread_exit(NULL);
3572 /* Do the low-level work of a capture.
3573 Returns TRUE if it succeeds, FALSE otherwise. */
3575 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3578 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3580 struct timeval upd_time, cur_time;
3584 condition *cnd_file_duration = NULL;
3585 condition *cnd_autostop_files = NULL;
3586 condition *cnd_autostop_size = NULL;
3587 condition *cnd_autostop_duration = NULL;
3590 gboolean cfilter_error = FALSE;
3591 char errmsg[MSG_MAX_LENGTH+1];
3592 char secondary_errmsg[MSG_MAX_LENGTH+1];
3593 pcap_options *pcap_opts;
3594 interface_options interface_opts;
3595 guint i, error_index = 0;
3598 *secondary_errmsg = '\0';
3600 /* init the loop data */
3601 global_ld.go = TRUE;
3602 global_ld.packet_count = 0;
3604 global_ld.report_packet_count = FALSE;
3606 if (capture_opts->has_autostop_packets)
3607 global_ld.packet_max = capture_opts->autostop_packets;
3609 global_ld.packet_max = 0; /* no limit */
3610 global_ld.inpkts_to_sync_pipe = 0;
3611 global_ld.err = 0; /* no error seen yet */
3612 global_ld.pdh = NULL;
3613 global_ld.autostop_files = 0;
3614 global_ld.save_file_fd = -1;
3616 /* We haven't yet gotten the capture statistics. */
3617 *stats_known = FALSE;
3619 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3620 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3622 /* open the "input file" from network interface or capture pipe */
3623 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3624 secondary_errmsg, sizeof(secondary_errmsg))) {
3627 for (i = 0; i < capture_opts->ifaces->len; i++) {
3628 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3629 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3630 /* init the input filter from the network interface (capture pipe will do nothing) */
3632 * When remote capturing WinPCap crashes when the capture filter
3633 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3636 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3637 interface_opts.name,
3638 interface_opts.cfilter?interface_opts.cfilter:"")) {
3640 case INITFILTER_NO_ERROR:
3643 case INITFILTER_BAD_FILTER:
3644 cfilter_error = TRUE;
3646 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3649 case INITFILTER_OTHER_ERROR:
3650 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3651 pcap_geterr(pcap_opts->pcap_h));
3652 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3657 /* If we're supposed to write to a capture file, open it for output
3658 (temporary/specified name/ringbuffer) */
3659 if (capture_opts->saving_to_file) {
3660 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3661 errmsg, sizeof(errmsg))) {
3665 /* set up to write to the already-opened capture output file/files */
3666 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3671 /* XXX - capture SIGTERM and close the capture, in case we're on a
3672 Linux 2.0[.x] system and you have to explicitly close the capture
3673 stream in order to turn promiscuous mode off? We need to do that
3674 in other places as well - and I don't think that works all the
3675 time in any case, due to libpcap bugs. */
3677 /* Well, we should be able to start capturing.
3679 Sync out the capture file, so the header makes it to the file system,
3680 and send a "capture started successfully and capture file created"
3681 message to our parent so that they'll open the capture file and
3682 update its windows to indicate that we have a live capture in
3684 fflush(global_ld.pdh);
3685 report_new_capture_file(capture_opts->save_file);
3688 /* initialize capture stop (and alike) conditions */
3689 init_capture_stop_conditions();
3690 /* create stop conditions */
3691 if (capture_opts->has_autostop_filesize) {
3692 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3693 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3696 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3698 if (capture_opts->has_autostop_duration)
3699 cnd_autostop_duration =
3700 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3702 if (capture_opts->multi_files_on) {
3703 if (capture_opts->has_file_duration)
3705 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3707 if (capture_opts->has_autostop_files)
3708 cnd_autostop_files =
3709 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_files);
3712 /* init the time values */
3714 upd_time = GetTickCount();
3716 gettimeofday(&upd_time, NULL);
3718 start_time = create_timestamp();
3719 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3721 /* WOW, everything is prepared! */
3722 /* please fasten your seat belts, we will enter now the actual capture loop */
3724 pcap_queue = g_async_queue_new();
3725 pcap_queue_bytes = 0;
3726 pcap_queue_packets = 0;
3727 for (i = 0; i < global_ld.pcaps->len; i++) {
3728 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3729 #if GLIB_CHECK_VERSION(2,31,0)
3730 /* XXX - Add an interface name here? */
3731 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3733 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3737 while (global_ld.go) {
3738 /* dispatch incoming packets */
3740 pcap_queue_element *queue_element;
3741 #if GLIB_CHECK_VERSION(2,31,18)
3743 g_async_queue_lock(pcap_queue);
3744 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3746 GTimeVal write_thread_time;
3748 g_get_current_time(&write_thread_time);
3749 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3750 g_async_queue_lock(pcap_queue);
3751 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3753 if (queue_element) {
3754 pcap_queue_bytes -= queue_element->phdr.caplen;
3755 pcap_queue_packets -= 1;
3757 g_async_queue_unlock(pcap_queue);
3758 if (queue_element) {
3759 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3760 "Dequeued a packet of length %d captured on interface %d.",
3761 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3763 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3764 &queue_element->phdr,
3766 g_free(queue_element->pd);
3767 g_free(queue_element);
3773 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3774 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3775 sizeof(errmsg), pcap_opts);
3778 /* Were we asked to print packet counts by the SIGINFO handler? */
3779 if (global_ld.report_packet_count) {
3780 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3781 plurality(global_ld.packet_count, "", "s"));
3782 global_ld.report_packet_count = FALSE;
3787 /* any news from our parent (signal pipe)? -> just stop the capture */
3788 if (!signal_pipe_check_running()) {
3789 global_ld.go = FALSE;
3794 global_ld.inpkts_to_sync_pipe += inpkts;
3796 /* check capture size condition */
3797 if (cnd_autostop_size != NULL &&
3798 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3799 /* Capture size limit reached, do we have another file? */
3800 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3801 cnd_autostop_size, cnd_file_duration))
3803 } /* cnd_autostop_size */
3804 if (capture_opts->output_to_pipe) {
3805 fflush(global_ld.pdh);
3809 /* Only update once every 500ms so as not to overload slow displays.
3810 * This also prevents too much context-switching between the dumpcap
3811 * and wireshark processes.
3813 #define DUMPCAP_UPD_TIME 500
3816 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3817 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3819 gettimeofday(&cur_time, NULL);
3820 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3821 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3824 upd_time = cur_time;
3827 if (pcap_stats(pch, stats) >= 0) {
3828 *stats_known = TRUE;
3831 /* Let the parent process know. */
3832 if (global_ld.inpkts_to_sync_pipe) {
3834 fflush(global_ld.pdh);
3836 /* Send our parent a message saying we've written out
3837 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3839 report_packet_count(global_ld.inpkts_to_sync_pipe);
3841 global_ld.inpkts_to_sync_pipe = 0;
3844 /* check capture duration condition */
3845 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3846 /* The maximum capture time has elapsed; stop the capture. */
3847 global_ld.go = FALSE;
3851 /* check capture file duration condition */
3852 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3853 /* duration limit reached, do we have another file? */
3854 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3855 cnd_autostop_size, cnd_file_duration))
3857 } /* cnd_file_duration */
3861 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3863 pcap_queue_element *queue_element;
3865 for (i = 0; i < global_ld.pcaps->len; i++) {
3866 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3867 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3868 pcap_opts->interface_id);
3869 g_thread_join(pcap_opts->tid);
3870 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3871 pcap_opts->interface_id);
3874 g_async_queue_lock(pcap_queue);
3875 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3876 if (queue_element) {
3877 pcap_queue_bytes -= queue_element->phdr.caplen;
3878 pcap_queue_packets -= 1;
3880 g_async_queue_unlock(pcap_queue);
3881 if (queue_element == NULL) {
3884 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3885 "Dequeued a packet of length %d captured on interface %d.",
3886 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3887 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3888 &queue_element->phdr,
3890 g_free(queue_element->pd);
3891 g_free(queue_element);
3892 global_ld.inpkts_to_sync_pipe += 1;
3893 if (capture_opts->output_to_pipe) {
3894 fflush(global_ld.pdh);
3900 /* delete stop conditions */
3901 if (cnd_file_duration != NULL)
3902 cnd_delete(cnd_file_duration);
3903 if (cnd_autostop_files != NULL)
3904 cnd_delete(cnd_autostop_files);
3905 if (cnd_autostop_size != NULL)
3906 cnd_delete(cnd_autostop_size);
3907 if (cnd_autostop_duration != NULL)
3908 cnd_delete(cnd_autostop_duration);
3910 /* did we have a pcap (input) error? */
3911 for (i = 0; i < capture_opts->ifaces->len; i++) {
3912 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3913 if (pcap_opts->pcap_err) {
3914 /* On Linux, if an interface goes down while you're capturing on it,
3915 you'll get a "recvfrom: Network is down" or
3916 "The interface went down" error (ENETDOWN).
3917 (At least you will if g_strerror() doesn't show a local translation
3920 On FreeBSD and OS X, if a network adapter disappears while
3921 you're capturing on it, you'll get a "read: Device not configured"
3922 error (ENXIO). (See previous parenthetical note.)
3924 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3926 These should *not* be reported to the Wireshark developers. */
3929 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3930 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3931 strcmp(cap_err_str, "The interface went down") == 0 ||
3932 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3933 strcmp(cap_err_str, "read: I/O error") == 0 ||
3934 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3935 report_capture_error("The network adapter on which the capture was being done "
3936 "is no longer running; the capture has stopped.",
3939 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3941 report_capture_error(errmsg, please_report);
3944 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3945 report_capture_error(errmsg, "");
3949 /* did we have an output error while capturing? */
3950 if (global_ld.err == 0) {
3953 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3954 global_ld.err, FALSE);
3955 report_capture_error(errmsg, please_report);
3959 if (capture_opts->saving_to_file) {
3960 /* close the output file */
3961 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3965 /* there might be packets not yet notified to the parent */
3966 /* (do this after closing the file, so all packets are already flushed) */
3967 if (global_ld.inpkts_to_sync_pipe) {
3969 report_packet_count(global_ld.inpkts_to_sync_pipe);
3970 global_ld.inpkts_to_sync_pipe = 0;
3973 /* If we've displayed a message about a write error, there's no point
3974 in displaying another message about an error on close. */
3975 if (!close_ok && write_ok) {
3976 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3978 report_capture_error(errmsg, "");
3982 * XXX We exhibit different behaviour between normal mode and sync mode
3983 * when the pipe is stdin and not already at EOF. If we're a child, the
3984 * parent's stdin isn't closed, so if the user starts another capture,
3985 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3986 * will say "Unrecognized libpcap format". On the other hand, in normal
3987 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3990 report_capture_count(TRUE);
3992 /* get packet drop statistics from pcap */
3993 for (i = 0; i < capture_opts->ifaces->len; i++) {
3995 guint32 pcap_dropped = 0;
3997 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3998 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3999 received = pcap_opts->received;
4000 if (pcap_opts->pcap_h != NULL) {
4001 g_assert(!pcap_opts->from_cap_pipe);
4002 /* Get the capture statistics, so we know how many packets were dropped. */
4004 * Older versions of libpcap didn't set ps_ifdrop on some
4005 * platforms; initialize it to 0 to handle that.
4007 stats->ps_ifdrop = 0;
4008 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
4009 *stats_known = TRUE;
4010 /* Let the parent process know. */
4011 pcap_dropped += stats->ps_drop;
4013 g_snprintf(errmsg, sizeof(errmsg),
4014 "Can't get packet-drop statistics: %s",
4015 pcap_geterr(pcap_opts->pcap_h));
4016 report_capture_error(errmsg, please_report);
4019 report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
4022 /* close the input file (pcap or capture pipe) */
4023 capture_loop_close_input(&global_ld);
4025 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
4027 /* ok, if the write and the close were successful. */
4028 return write_ok && close_ok;
4031 if (capture_opts->multi_files_on) {
4032 /* cleanup ringbuffer */
4033 ringbuf_error_cleanup();
4035 /* We can't use the save file, and we have no FILE * for the stream
4036 to close in order to close it, so close the FD directly. */
4037 if (global_ld.save_file_fd != -1) {
4038 ws_close(global_ld.save_file_fd);
4041 /* We couldn't even start the capture, so get rid of the capture
4043 if (capture_opts->save_file != NULL) {
4044 ws_unlink(capture_opts->save_file);
4045 g_free(capture_opts->save_file);
4048 capture_opts->save_file = NULL;
4050 report_cfilter_error(capture_opts, error_index, errmsg);
4052 report_capture_error(errmsg, secondary_errmsg);
4054 /* close the input file (pcap or cap_pipe) */
4055 capture_loop_close_input(&global_ld);
4057 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
4064 capture_loop_stop(void)
4066 #ifdef HAVE_PCAP_BREAKLOOP
4068 pcap_options *pcap_opts;
4070 for (i = 0; i < global_ld.pcaps->len; i++) {
4071 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
4072 if (pcap_opts->pcap_h != NULL)
4073 pcap_breakloop(pcap_opts->pcap_h);
4076 global_ld.go = FALSE;
4081 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
4082 int err, gboolean is_close)
4087 g_snprintf(errmsg, errmsglen,
4088 "Not all the packets could be written to the file"
4089 " to which the capture was being saved\n"
4090 "(\"%s\") because there is no space left on the file system\n"
4091 "on which that file resides.",
4097 g_snprintf(errmsg, errmsglen,
4098 "Not all the packets could be written to the file"
4099 " to which the capture was being saved\n"
4100 "(\"%s\") because you are too close to, or over,"
4101 " your disk quota\n"
4102 "on the file system on which that file resides.",
4109 g_snprintf(errmsg, errmsglen,
4110 "The file to which the capture was being saved\n"
4111 "(\"%s\") could not be closed: %s.",
4112 fname, g_strerror(err));
4114 g_snprintf(errmsg, errmsglen,
4115 "An error occurred while writing to the file"
4116 " to which the capture was being saved\n"
4118 fname, g_strerror(err));
4125 /* one packet was captured, process it */
4127 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4130 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4132 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
4134 /* We may be called multiple times from pcap_dispatch(); if we've set
4135 the "stop capturing" flag, ignore this packet, as we're not
4136 supposed to be saving any more packets. */
4137 if (!global_ld.go) {
4138 pcap_opts->flushed++;
4142 if (global_ld.pdh) {
4143 gboolean successful;
4145 /* We're supposed to write the packet to a file; do so.
4146 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4147 "ld->err" to the error. */
4148 if (global_capture_opts.use_pcapng) {
4149 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4151 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4152 phdr->caplen, phdr->len,
4153 pcap_opts->interface_id,
4156 &global_ld.bytes_written, &err);
4158 successful = libpcap_write_packet(global_ld.pdh,
4159 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4160 phdr->caplen, phdr->len,
4162 &global_ld.bytes_written, &err);
4165 global_ld.go = FALSE;
4166 global_ld.err = err;
4167 pcap_opts->dropped++;
4169 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4170 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4171 "Wrote a packet of length %d captured on interface %u.",
4172 phdr->caplen, pcap_opts->interface_id);
4174 global_ld.packet_count++;
4175 pcap_opts->received++;
4176 /* if the user told us to stop after x packets, do we already have enough? */
4177 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4178 global_ld.go = FALSE;
4184 /* one packet was captured, queue it */
4186 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4189 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4190 pcap_queue_element *queue_element;
4191 gboolean limit_reached;
4193 /* We may be called multiple times from pcap_dispatch(); if we've set
4194 the "stop capturing" flag, ignore this packet, as we're not
4195 supposed to be saving any more packets. */
4196 if (!global_ld.go) {
4197 pcap_opts->flushed++;
4201 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4202 if (queue_element == NULL) {
4203 pcap_opts->dropped++;
4206 queue_element->pcap_opts = pcap_opts;
4207 queue_element->phdr = *phdr;
4208 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4209 if (queue_element->pd == NULL) {
4210 pcap_opts->dropped++;
4211 g_free(queue_element);
4214 memcpy(queue_element->pd, pd, phdr->caplen);
4215 g_async_queue_lock(pcap_queue);
4216 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4217 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4218 limit_reached = FALSE;
4219 g_async_queue_push_unlocked(pcap_queue, queue_element);
4220 pcap_queue_bytes += phdr->caplen;
4221 pcap_queue_packets += 1;
4223 limit_reached = TRUE;
4225 g_async_queue_unlock(pcap_queue);
4226 if (limit_reached) {
4227 pcap_opts->dropped++;
4228 g_free(queue_element->pd);
4229 g_free(queue_element);
4230 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4231 "Dropped a packet of length %d captured on interface %u.",
4232 phdr->caplen, pcap_opts->interface_id);
4234 pcap_opts->received++;
4235 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4236 "Queued a packet of length %d captured on interface %u.",
4237 phdr->caplen, pcap_opts->interface_id);
4239 /* I don't want to hold the mutex over the debug output. So the
4240 output may be wrong */
4241 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4242 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4243 pcap_queue_bytes, pcap_queue_packets);
4247 set_80211_channel(const char *iface, const char *opt)
4249 int freq = 0, type, ret;
4250 gchar **options = NULL;
4252 options = g_strsplit_set(opt, ",", 2);
4255 freq = atoi(options[0]);
4258 type = ws80211_str_to_chan_type(options[1]);
4267 ret = ws80211_init();
4269 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4273 ret = ws80211_set_freq(iface, freq, type);
4276 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4282 pipe_write_block(2, SP_SUCCESS, NULL);
4286 g_strfreev(options);
4291 get_dumpcap_compiled_info(GString *str)
4293 /* Capture libraries */
4294 g_string_append(str, ", ");
4295 get_compiled_caplibs_version(str);
4298 g_string_append(str, ", ");
4300 g_string_append(str, "with libz ");
4302 g_string_append(str, ZLIB_VERSION);
4303 #else /* ZLIB_VERSION */
4304 g_string_append(str, "(version unknown)");
4305 #endif /* ZLIB_VERSION */
4306 #else /* HAVE_LIBZ */
4307 g_string_append(str, "without libz");
4308 #endif /* HAVE_LIBZ */
4312 get_dumpcap_runtime_info(GString *str)
4314 /* Capture libraries */
4315 g_string_append(str, ", ");
4316 get_runtime_caplibs_version(str);
4319 #if defined(HAVE_LIBZ) && !defined(_WIN32)
4320 g_string_append_printf(str, ", with libz %s", zlibVersion());
4324 /* And now our feature presentation... [ fade to music ] */
4326 main(int argc, char *argv[])
4328 GString *comp_info_str;
4329 GString *runtime_info_str;
4332 static const struct option long_options[] = {
4333 {(char *)"help", no_argument, NULL, 'h'},
4334 {(char *)"version", no_argument, NULL, 'v'},
4335 LONGOPT_CAPTURE_COMMON
4340 gboolean arg_error = FALSE;
4345 struct sigaction action, oldaction;
4348 gboolean start_capture = TRUE;
4349 gboolean stats_known;
4350 struct pcap_stat stats;
4351 GLogLevelFlags log_flags;
4352 gboolean list_interfaces = FALSE;
4353 gboolean list_link_layer_types = FALSE;
4354 #ifdef HAVE_BPF_IMAGE
4355 gboolean print_bpf_code = FALSE;
4357 gboolean set_chan = FALSE;
4358 gchar *set_chan_arg = NULL;
4359 gboolean machine_readable = FALSE;
4360 gboolean print_statistics = FALSE;
4361 int status, run_once_args = 0;
4364 #if defined(__APPLE__) && defined(__LP64__)
4365 struct utsname osinfo;
4369 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
4371 /* Get the compile-time version information string */
4372 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4374 /* Get the run-time version information string */
4375 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4377 /* Add it to the information to be reported on a crash. */
4378 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
4383 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
4386 arg_list_utf_16to8(argc, argv);
4387 create_app_running_mutex();
4390 * Initialize our DLL search path. MUST be called before LoadLibrary
4393 ws_init_dll_search_path();
4396 #ifdef HAVE_BPF_IMAGE
4397 #define OPTSTRING_d "d"
4399 #define OPTSTRING_d ""
4402 #ifdef HAVE_PCAP_REMOTE
4403 #define OPTSTRING_r "r"
4404 #define OPTSTRING_u "u"
4406 #define OPTSTRING_r ""
4407 #define OPTSTRING_u ""
4410 #ifdef HAVE_PCAP_SETSAMPLING
4411 #define OPTSTRING_m "m:"
4413 #define OPTSTRING_m ""
4416 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
4418 #ifdef DEBUG_CHILD_DUMPCAP
4419 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4420 fprintf (stderr, "Unable to open debug log file .\n");
4425 #if defined(__APPLE__) && defined(__LP64__)
4427 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4428 * a bug workaround - timeouts less than 1 second don't work with libpcap
4429 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4430 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4431 * The problem is extremely unlikely to be reintroduced in a future
4434 if (uname(&osinfo) == 0) {
4436 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
4437 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4438 * number of 10.0.0, not 10.1.0 - go figure).
4440 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4441 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4442 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4443 need_timeout_workaround = TRUE;
4448 * Determine if dumpcap is being requested to run in a special
4449 * capture_child mode by going thru the command line args to see if
4450 * a -Z is present. (-Z is a hidden option).
4452 * The primary result of running in capture_child mode is that
4453 * all messages sent out on stderr are in a special type/len/string
4454 * format to allow message processing by type. These messages include
4455 * error messages if dumpcap fails to start the operation it was
4456 * requested to do, as well as various "status" messages which are sent
4457 * when an actual capture is in progress, and a "success" message sent
4458 * if dumpcap was requested to perform an operation other than a
4461 * Capture_child mode would normally be requested by a parent process
4462 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4463 * to which dumpcap stderr has been redirected. It might also have
4464 * another pipe to obtain dumpcap stdout output; for operations other
4465 * than a capture, that information is formatted specially for easier
4466 * parsing by the parent process.
4468 * Capture_child mode needs to be determined immediately upon
4469 * startup so that any messages generated by dumpcap in this mode
4470 * (eg: during initialization) will be formatted properly.
4473 for (i=1; i<argc; i++) {
4474 if (strcmp("-Z", argv[i]) == 0) {
4475 capture_child = TRUE;
4476 machine_readable = TRUE; /* request machine-readable output */
4478 /* set output pipe to binary mode, to avoid ugly text conversions */
4479 _setmode(2, O_BINARY);
4484 /* The default_log_handler will use stdout, which makes trouble in */
4485 /* capture child mode, as it uses stdout for its sync_pipe. */
4486 /* So: the filtering is done in the console_log_handler and not here.*/
4487 /* We set the log handlers right up front to make sure that any log */
4488 /* messages when running as child will be sent back to the parent */
4489 /* with the correct format. */
4494 G_LOG_LEVEL_CRITICAL|
4495 G_LOG_LEVEL_WARNING|
4496 G_LOG_LEVEL_MESSAGE|
4500 G_LOG_FLAG_RECURSION);
4502 g_log_set_handler(NULL,
4504 console_log_handler, NULL /* user_data */);
4505 g_log_set_handler(LOG_DOMAIN_MAIN,
4507 console_log_handler, NULL /* user_data */);
4508 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4510 console_log_handler, NULL /* user_data */);
4511 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4513 console_log_handler, NULL /* user_data */);
4515 /* Initialize the pcaps list */
4516 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
4518 #if !GLIB_CHECK_VERSION(2,31,0)
4519 /* Initialize the thread system */
4520 g_thread_init(NULL);
4524 /* Load wpcap if possible. Do this before collecting the run-time version information */
4527 /* ... and also load the packet.dll from wpcap */
4528 /* XXX - currently not required, may change later. */
4529 /*wpcap_packet_load();*/
4531 /* Start windows sockets */
4532 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4534 /* Set handler for Ctrl+C key */
4535 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4537 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4538 and exit. Do the same with SIGPIPE, in case, for example,
4539 we're writing to our standard output and it's a pipe.
4540 Do the same with SIGHUP if it's not being ignored (if we're
4541 being run under nohup, it might be ignored, in which case we
4542 should leave it ignored).
4544 XXX - apparently, Coverity complained that part of action
4545 wasn't initialized. Perhaps it's running on Linux, where
4546 struct sigaction has an ignored "sa_restorer" element and
4547 where "sa_handler" and "sa_sigaction" might not be two
4548 members of a union. */
4549 memset(&action, 0, sizeof(action));
4550 action.sa_handler = capture_cleanup_handler;
4552 * Arrange that system calls not get restarted, because when
4553 * our signal handler returns we don't want to restart
4554 * a call that was waiting for packets to arrive.
4556 action.sa_flags = 0;
4557 sigemptyset(&action.sa_mask);
4558 sigaction(SIGTERM, &action, NULL);
4559 sigaction(SIGINT, &action, NULL);
4560 sigaction(SIGPIPE, &action, NULL);
4561 sigaction(SIGHUP, NULL, &oldaction);
4562 if (oldaction.sa_handler == SIG_DFL)
4563 sigaction(SIGHUP, &action, NULL);
4566 /* Catch SIGINFO and, if we get it and we're capturing in
4567 quiet mode, report the number of packets we've captured. */
4568 action.sa_handler = report_counts_siginfo;
4569 action.sa_flags = SA_RESTART;
4570 sigemptyset(&action.sa_mask);
4571 sigaction(SIGINFO, &action, NULL);
4572 #endif /* SIGINFO */
4576 enable_kernel_bpf_jit_compiler();
4579 /* ----------------------------------------------------------------- */
4580 /* Privilege and capability handling */
4582 /* 1. Running not as root or suid root; no special capabilities. */
4585 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4588 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4590 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4591 /* capabilities; Drop all other capabilities; */
4592 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4593 /* else: after pcap_open_live() in capture_loop_open_input() */
4594 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4595 /* (Note: this means that the process, although logged in */
4596 /* as root, does not have various permissions such as the */
4597 /* ability to bypass file access permissions). */
4598 /* XXX: Should we just leave capabilities alone in this case */
4599 /* so that user gets expected effect that root can do */
4602 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4604 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4605 /* else: after pcap_open_live() in capture_loop_open_input() */
4606 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4607 /* pcap_open_live). */
4609 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4611 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4612 /* capabilities; Drop all other capabilities; */
4613 /* Drop suid privileges (euid=ruid); */
4614 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4615 /* else: after pcap_open_live() in capture_loop_open_input() */
4616 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4618 /* XXX: For some Linux versions/distros with capabilities */
4619 /* a 'normal' process with any capabilities cannot be */
4620 /* 'killed' (signaled) from another (same uid) non-privileged */
4622 /* For example: If (non-suid) Wireshark forks a */
4623 /* child suid dumpcap which acts as described here (case 5), */
4624 /* Wireshark will be unable to kill (signal) the child */
4625 /* dumpcap process until the capabilities have been dropped */
4626 /* (after pcap_open_live()). */
4627 /* This behaviour will apparently be changed in the kernel */
4628 /* to allow the kill (signal) in this case. */
4629 /* See the following for details: */
4630 /* https://www.mail-archive.com/ [wrapped] */
4631 /* linux-security-module@vger.kernel.org/msg02913.html */
4633 /* It is therefore conceivable that if dumpcap somehow hangs */
4634 /* in pcap_open_live or before that wireshark will not */
4635 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4636 /* In this case, exiting wireshark will kill the child */
4637 /* dumpcap process. */
4639 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4640 /* capabilities; Using libcap. Note: capset cmd (which see) */
4641 /* used to assign capabilities to file. */
4643 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4644 /* else: after pcap_open_live() in capture_loop_open_input() */
4645 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4647 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4648 /* longer required (similar to capture). */
4650 /* ----------------------------------------------------------------- */
4652 init_process_policies();
4655 /* If 'started with special privileges' (and using libcap) */
4656 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4657 /* Set euid/egid = ruid/rgid to remove suid privileges */
4658 relinquish_privs_except_capture();
4661 /* Set the initial values in the capture options. This might be overwritten
4662 by the command line parameters. */
4663 capture_opts_init(&global_capture_opts);
4664 /* We always save to a file - if no file was specified, we save to a
4666 global_capture_opts.saving_to_file = TRUE;
4667 global_capture_opts.has_ring_num_files = TRUE;
4669 /* Pass on capture_child mode for capture_opts */
4670 global_capture_opts.capture_child = capture_child;
4672 /* Now get our args */
4673 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4675 case 'h': /* Print help and exit */
4676 printf("Dumpcap (Wireshark) %s\n"
4677 "Capture network packets and dump them into a pcapng or pcap file.\n"
4678 "See https://www.wireshark.org for more information.\n",
4679 get_ws_vcs_version_info());
4680 print_usage(stdout);
4683 case 'v': /* Show version and exit */
4685 show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4686 g_string_free(comp_info_str, TRUE);
4687 g_string_free(runtime_info_str, TRUE);
4691 /*** capture option specific ***/
4692 case 'a': /* autostop criteria */
4693 case 'b': /* Ringbuffer option */
4694 case 'c': /* Capture x packets */
4695 case 'f': /* capture filter */
4696 case 'g': /* enable group read access on file(s) */
4697 case 'i': /* Use interface x */
4698 case 'n': /* Use pcapng format */
4699 case 'p': /* Don't capture in promiscuous mode */
4700 case 'P': /* Use pcap format */
4701 case 's': /* Set the snapshot (capture) length */
4702 case 'w': /* Write to capture file x */
4703 case 'y': /* Set the pcap data link type */
4704 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4705 #ifdef HAVE_PCAP_REMOTE
4706 case 'u': /* Use UDP for data transfer */
4707 case 'r': /* Capture own RPCAP traffic too */
4708 case 'A': /* Authentication */
4710 #ifdef HAVE_PCAP_SETSAMPLING
4711 case 'm': /* Sampling */
4713 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4714 case 'B': /* Buffer size */
4716 #ifdef HAVE_PCAP_CREATE
4717 case 'I': /* Monitor mode */
4719 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4724 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4726 capture_child = TRUE;
4728 /* set output pipe to binary mode, to avoid ugly text conversions */
4729 _setmode(2, O_BINARY);
4731 * optarg = the control ID, aka the PPID, currently used for the
4734 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4735 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4736 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4737 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4739 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4740 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4741 "Signal pipe: Unable to open %s. Dead parent?",
4749 case 'q': /* Quiet */
4755 /*** all non capture option specific ***/
4756 case 'D': /* Print a list of capture devices and exit */
4757 if (!list_interfaces) {
4758 list_interfaces = TRUE;
4762 case 'L': /* Print list of link-layer types and exit */
4763 if (!list_link_layer_types) {
4764 list_link_layer_types = TRUE;
4768 #ifdef HAVE_BPF_IMAGE
4769 case 'd': /* Print BPF code for capture filter and exit */
4770 if (!print_bpf_code) {
4771 print_bpf_code = TRUE;
4776 case 'S': /* Print interface statistics once a second */
4777 if (!print_statistics) {
4778 print_statistics = TRUE;
4782 case 'k': /* Set wireless channel */
4785 set_chan_arg = optarg;
4788 cmdarg_err("Only one -k flag may be specified");
4792 case 'M': /* For -D, -L, and -S, print machine-readable output */
4793 machine_readable = TRUE;
4796 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4799 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4802 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4804 case '?': /* Bad flag - print usage message */
4813 /* user specified file name as regular command-line argument */
4814 /* XXX - use it as the capture file name (or something else)? */
4820 * Extra command line arguments were specified; complain.
4821 * XXX - interpret as capture filter, as tcpdump and tshark do?
4823 cmdarg_err("Invalid argument: %s", argv[0]);
4828 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4831 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4832 /* Use some default if the user hasn't specified some */
4833 /* XXX: Are these defaults good enough? */
4834 pcap_queue_byte_limit = 1000 * 1000;
4835 pcap_queue_packet_limit = 1000;
4838 print_usage(stderr);
4842 if (run_once_args > 1) {
4843 #ifdef HAVE_BPF_IMAGE
4844 cmdarg_err("Only one of -D, -L, -d, -k, or -S may be supplied.");
4846 cmdarg_err("Only one of -D, -L, -k, or -S may be supplied.");
4849 } else if (run_once_args == 1) {
4850 /* We're supposed to print some information, rather than
4851 to capture traffic; did they specify a ring buffer option? */
4852 if (global_capture_opts.multi_files_on) {
4853 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4857 /* We're supposed to capture traffic; */
4859 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4860 if (global_capture_opts.ifaces->len > 1) {
4862 global_capture_opts.use_pcapng = TRUE;
4865 if (global_capture_opts.capture_comment &&
4866 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4867 /* XXX - for ringbuffer, should we apply the comment to each file? */
4868 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4872 /* Was the ring buffer option specified and, if so, does it make sense? */
4873 if (global_capture_opts.multi_files_on) {
4874 /* Ring buffer works only under certain conditions:
4875 a) ring buffer does not work with temporary files;
4876 b) it makes no sense to enable the ring buffer if the maximum
4877 file size is set to "infinite". */
4878 if (global_capture_opts.save_file == NULL) {
4879 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4880 global_capture_opts.multi_files_on = FALSE;
4882 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4883 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4885 /* XXX - this must be redesigned as the conditions changed */
4886 global_capture_opts.multi_files_on = FALSE;
4893 * "-D" requires no interface to be selected; it's supposed to list
4896 if (list_interfaces) {
4897 /* Get the list of interfaces */
4902 if_list = capture_interface_list(&err, &err_str,NULL);
4903 if (if_list == NULL) {
4906 * If we're being run by another program, just give them
4907 * an empty list of interfaces, don't report this as
4908 * an error; that lets them decide whether to report
4909 * this as an error or not.
4911 if (!machine_readable) {
4912 cmdarg_err("There are no interfaces on which a capture can be done");
4916 cmdarg_err("%s", err_str);
4922 if (machine_readable) /* tab-separated values to stdout */
4923 print_machine_readable_interfaces(if_list);
4925 capture_opts_print_interfaces(if_list);
4926 free_interface_list(if_list);
4931 * "-S" requires no interface to be selected; it gives statistics
4932 * for all interfaces.
4934 if (print_statistics) {
4935 status = print_statistics_loop(machine_readable);
4940 interface_options interface_opts;
4942 if (global_capture_opts.ifaces->len != 1) {
4943 cmdarg_err("Need one interface");
4947 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4948 status = set_80211_channel(interface_opts.name, set_chan_arg);
4953 * "-L", "-d", and capturing act on a particular interface, so we have to
4954 * have an interface; if none was specified, pick a default.
4956 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4958 /* cmdarg_err() already called .... */
4962 if (list_link_layer_types) {
4963 /* Get the list of link-layer types for the capture device. */
4964 if_capabilities_t *caps;
4968 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4969 interface_options interface_opts;
4971 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4973 caps = get_if_capabilities(&interface_opts, &err_str);
4975 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4976 "Please check to make sure you have sufficient permissions, and that\n"
4977 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4981 if (caps->data_link_types == NULL) {
4982 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4985 if (machine_readable) /* tab-separated values to stdout */
4986 /* XXX: We need to change the format and adopt consumers */
4987 print_machine_readable_if_capabilities(caps);
4989 /* XXX: We might want to print also the interface name */
4990 capture_opts_print_if_capabilities(caps, interface_opts.name,
4991 interface_opts.monitor_mode);
4992 free_if_capabilities(caps);
4997 /* We're supposed to do a capture, or print the BPF code for a filter. */
4999 /* Let the user know what interfaces were chosen. */
5000 if (capture_child) {
5001 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5002 interface_options interface_opts;
5004 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
5005 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
5006 interface_opts.name);
5009 str = g_string_new("");
5011 if (global_capture_opts.ifaces->len < 2)
5013 if (global_capture_opts.ifaces->len < 4)
5016 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5017 interface_options interface_opts;
5019 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
5021 if (global_capture_opts.ifaces->len > 2) {
5022 g_string_append_printf(str, ",");
5024 g_string_append_printf(str, " ");
5025 if (j == global_capture_opts.ifaces->len - 1) {
5026 g_string_append_printf(str, "and ");
5029 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
5032 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
5034 fprintf(stderr, "Capturing on %s\n", str->str);
5035 g_string_free(str, TRUE);
5038 /* Process the snapshot length, as that affects the generated BPF code. */
5039 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
5041 #ifdef HAVE_BPF_IMAGE
5042 if (print_bpf_code) {
5043 show_filter_code(&global_capture_opts);
5048 /* We're supposed to do a capture. Process the ring buffer arguments. */
5049 capture_opts_trim_ring_num_files(&global_capture_opts);
5051 /* flush stderr prior to starting the main capture loop */
5054 /* Now start the capture. */
5055 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
5059 /* capture failed */
5062 return 0; /* never here, make compiler happy */
5067 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
5068 const char *message, gpointer user_data _U_)
5075 /* ignore log message, if log_level isn't interesting */
5076 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5077 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
5082 /* create a "timestamp" */
5084 today = localtime(&curr);
5086 switch(log_level & G_LOG_LEVEL_MASK) {
5087 case G_LOG_LEVEL_ERROR:
5090 case G_LOG_LEVEL_CRITICAL:
5093 case G_LOG_LEVEL_WARNING:
5096 case G_LOG_LEVEL_MESSAGE:
5099 case G_LOG_LEVEL_INFO:
5102 case G_LOG_LEVEL_DEBUG:
5106 fprintf(stderr, "unknown log_level %d\n", log_level);
5108 g_assert_not_reached();
5111 /* Generate the output message */
5112 if (log_level & G_LOG_LEVEL_MESSAGE) {
5113 /* normal user messages without additional infos */
5114 msg = g_strdup_printf("%s\n", message);
5116 /* info/debug messages with additional infos */
5117 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
5118 today->tm_hour, today->tm_min, today->tm_sec,
5119 log_domain != NULL ? log_domain : "",
5123 /* DEBUG & INFO msgs (if we're debugging today) */
5124 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
5125 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5126 #ifdef DEBUG_DUMPCAP
5127 fprintf(stderr, "%s", msg);
5130 #ifdef DEBUG_CHILD_DUMPCAP
5131 fprintf(debug_log, "%s", msg);
5139 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
5140 /* to parent especially formatted if dumpcap running as child. */
5141 if (capture_child) {
5142 sync_pipe_errmsg_to_parent(2, msg, "");
5144 fprintf(stderr, "%s", msg);
5151 /****************************************************************************************************************/
5152 /* indication report routines */
5156 report_packet_count(unsigned int packet_count)
5158 char tmp[SP_DECISIZE+1+1];
5159 static unsigned int count = 0;
5161 if (capture_child) {
5162 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
5163 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
5164 pipe_write_block(2, SP_PACKET_COUNT, tmp);
5166 count += packet_count;
5167 fprintf(stderr, "\rPackets: %u ", count);
5168 /* stderr could be line buffered */
5174 report_new_capture_file(const char *filename)
5176 if (capture_child) {
5177 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
5178 pipe_write_block(2, SP_FILE, filename);
5182 * Prevent a SIGINFO handler from writing to the standard error
5183 * while we're doing so; instead, have it just set a flag telling
5184 * us to print that information when we're done.
5187 #endif /* SIGINFO */
5188 fprintf(stderr, "File: %s\n", filename);
5189 /* stderr could be line buffered */
5194 * Allow SIGINFO handlers to write.
5199 * If a SIGINFO handler asked us to write out capture counts, do so.
5202 report_counts_for_siginfo();
5203 #endif /* SIGINFO */
5208 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5210 interface_options interface_opts;
5211 char tmp[MSG_MAX_LENGTH+1+6];
5213 if (i < capture_opts->ifaces->len) {
5214 if (capture_child) {
5215 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5216 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5217 pipe_write_block(2, SP_BAD_FILTER, tmp);
5220 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5221 * the error message below.
5223 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
5225 "Invalid capture filter \"%s\" for interface '%s'.\n"
5227 "That string isn't a valid capture filter (%s).\n"
5228 "See the User's Guide for a description of the capture filter syntax.",
5229 interface_opts.cfilter, interface_opts.name, errmsg);
5235 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5237 if (capture_child) {
5238 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5239 "Primary Error: %s", error_msg);
5240 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5241 "Secondary Error: %s", secondary_error_msg);
5242 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5244 cmdarg_err("%s", error_msg);
5245 if (secondary_error_msg[0] != '\0')
5246 cmdarg_err_cont("%s", secondary_error_msg);
5251 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
5253 char tmp[SP_DECISIZE+1+1];
5254 guint32 total_drops = pcap_drops + drops + flushed;
5256 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5258 if (capture_child) {
5259 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5260 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5261 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
5262 /* XXX: Need to provide interface id, changes to consumers required. */
5263 pipe_write_block(2, SP_DROPS, tmp);
5266 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5267 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
5268 received ? 100.0 * received / (received + total_drops) : 0.0);
5269 /* stderr could be line buffered */
5275 /************************************************************************************************/
5276 /* signal_pipe handling */
5281 signal_pipe_check_running(void)
5283 /* any news from our parent? -> just stop the capture */
5287 /* if we are running standalone, no check required */
5288 if (!capture_child) {
5292 if (!sig_pipe_name || !sig_pipe_handle) {
5293 /* This shouldn't happen */
5294 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5295 "Signal pipe: No name or handle");
5300 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5301 * at this point. Should we check to see if the parent is still alive,
5302 * e.g. by using OpenProcess?
5305 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5307 if (!result || avail > 0) {
5308 /* peek failed or some bytes really available */
5309 /* (if not piping from stdin this would fail) */
5310 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5311 "Signal pipe: Stop capture: %s", sig_pipe_name);
5312 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5313 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
5314 sig_pipe_handle, result, avail);
5317 /* pipe ok and no bytes available */
5328 * Editor modelines - https://www.wireshark.org/tools/modelines.html
5333 * indent-tabs-mode: nil
5336 * vi: set shiftwidth=4 tabstop=8 expandtab:
5337 * :indentSize=4:tabSize=8:noTabs=true: