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(const char *devicename, gboolean monitor_mode
1218 #ifndef HAVE_PCAP_CREATE
1223 if_capabilities_t *caps;
1224 char errbuf[PCAP_ERRBUF_SIZE];
1226 #ifdef HAVE_PCAP_CREATE
1230 #ifdef HAVE_PCAP_LIST_DATALINKS
1234 data_link_info_t *data_link_info;
1237 * Allocate the interface capabilities structure.
1239 caps = (if_capabilities_t *)g_malloc(sizeof *caps);
1242 * WinPcap 4.1.2, and possibly earlier versions, have a bug
1243 * wherein, when an open with an rpcap: URL fails, the error
1244 * message for the error is not copied to errbuf and whatever
1245 * on-the-stack junk is in errbuf is treated as the error
1248 * To work around that (and any other bugs of that sort, we
1249 * initialize errbuf to an empty string. If we get an error
1250 * and the string is empty, we report it as an unknown error.
1251 * (If we *don't* get an error, and the string is *non*-empty,
1252 * that could be a warning returned, such as "can't turn
1253 * promiscuous mode on"; we currently don't do so.)
1256 #ifdef HAVE_PCAP_OPEN
1257 pch = pcap_open(devicename, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1258 caps->can_set_rfmon = FALSE;
1260 if (err_str != NULL)
1261 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1265 #elif defined(HAVE_PCAP_CREATE)
1266 pch = pcap_create(devicename, errbuf);
1268 if (err_str != NULL)
1269 *err_str = g_strdup(errbuf);
1273 if (is_linux_bonding_device(devicename)) {
1275 * Linux bonding device; not Wi-Fi, so no monitor mode, and
1276 * calling pcap_can_set_rfmon() might get a "no such device"
1282 * Not a Linux bonding device, so go ahead.
1284 status = pcap_can_set_rfmon(pch);
1288 if (status == PCAP_ERROR)
1289 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1292 *err_str = g_strdup(pcap_statustostr(status));
1298 caps->can_set_rfmon = FALSE;
1299 else if (status == 1) {
1300 caps->can_set_rfmon = TRUE;
1302 pcap_set_rfmon(pch, 1);
1304 if (err_str != NULL) {
1305 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1313 status = pcap_activate(pch);
1315 /* Error. We ignore warnings (status > 0). */
1316 if (err_str != NULL) {
1317 if (status == PCAP_ERROR)
1318 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1321 *err_str = g_strdup(pcap_statustostr(status));
1328 pch = pcap_open_live(devicename, MIN_PACKET_SIZE, 0, 0, errbuf);
1329 caps->can_set_rfmon = FALSE;
1331 if (err_str != NULL)
1332 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1337 deflt = get_pcap_linktype(pch, devicename);
1338 #ifdef HAVE_PCAP_LIST_DATALINKS
1339 nlt = pcap_list_datalinks(pch, &linktypes);
1340 if (nlt == 0 || linktypes == NULL) {
1342 if (err_str != NULL)
1343 *err_str = NULL; /* an empty list doesn't mean an error */
1347 caps->data_link_types = NULL;
1348 for (i = 0; i < nlt; i++) {
1349 data_link_info = create_data_link_info(linktypes[i]);
1352 * XXX - for 802.11, make the most detailed 802.11
1353 * version the default, rather than the one the
1354 * device has as the default?
1356 if (linktypes[i] == deflt)
1357 caps->data_link_types = g_list_prepend(caps->data_link_types,
1360 caps->data_link_types = g_list_append(caps->data_link_types,
1363 #ifdef HAVE_PCAP_FREE_DATALINKS
1364 pcap_free_datalinks(linktypes);
1367 * In Windows, there's no guarantee that if you have a library
1368 * built with one version of the MSVC++ run-time library, and
1369 * it returns a pointer to allocated data, you can free that
1370 * data from a program linked with another version of the
1371 * MSVC++ run-time library.
1373 * This is not an issue on UN*X.
1375 * See the mail threads starting at
1377 * https://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1381 * https://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1384 #define xx_free free /* hack so checkAPIs doesn't complain */
1387 #endif /* HAVE_PCAP_FREE_DATALINKS */
1388 #else /* HAVE_PCAP_LIST_DATALINKS */
1390 data_link_info = create_data_link_info(deflt);
1391 caps->data_link_types = g_list_append(caps->data_link_types,
1393 #endif /* HAVE_PCAP_LIST_DATALINKS */
1397 if (err_str != NULL)
1402 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1404 * Output a machine readable list of the interfaces
1405 * This list is retrieved by the sync_interface_list_open() function
1406 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
1409 print_machine_readable_interfaces(GList *if_list)
1416 char addr_str[ADDRSTRLEN];
1418 if (capture_child) {
1419 /* Let our parent know we succeeded. */
1420 pipe_write_block(2, SP_SUCCESS, NULL);
1423 i = 1; /* Interface id number */
1424 for (if_entry = g_list_first(if_list); if_entry != NULL;
1425 if_entry = g_list_next(if_entry)) {
1426 if_info = (if_info_t *)if_entry->data;
1427 printf("%d. %s\t", i++, if_info->name);
1430 * Print the contents of the if_entry struct in a parseable format.
1431 * Each if_entry element is tab-separated. Addresses are comma-
1434 /* XXX - Make sure our description doesn't contain a tab */
1435 if (if_info->vendor_description != NULL)
1436 printf("%s\t", if_info->vendor_description);
1440 /* XXX - Make sure our friendly name doesn't contain a tab */
1441 if (if_info->friendly_name != NULL)
1442 printf("%s\t", if_info->friendly_name);
1446 printf("%i\t", if_info->type);
1448 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1449 addr = g_slist_next(addr)) {
1450 if (addr != g_slist_nth(if_info->addrs, 0))
1453 if_addr = (if_addr_t *)addr->data;
1454 switch(if_addr->ifat_type) {
1456 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1458 printf("%s", addr_str);
1460 printf("<unknown IPv4>");
1464 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1465 addr_str, ADDRSTRLEN)) {
1466 printf("%s", addr_str);
1468 printf("<unknown IPv6>");
1472 printf("<type unknown %i>", if_addr->ifat_type);
1476 if (if_info->loopback)
1477 printf("\tloopback");
1479 printf("\tnetwork");
1481 printf("\t%s", if_info->extcap);
1488 * If you change the machine-readable output format of this function,
1489 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1492 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1495 data_link_info_t *data_link_info;
1496 const gchar *desc_str;
1498 if (capture_child) {
1499 /* Let our parent know we succeeded. */
1500 pipe_write_block(2, SP_SUCCESS, NULL);
1503 if (caps->can_set_rfmon)
1507 for (lt_entry = caps->data_link_types; lt_entry != NULL;
1508 lt_entry = g_list_next(lt_entry)) {
1509 data_link_info = (data_link_info_t *)lt_entry->data;
1510 if (data_link_info->description != NULL)
1511 desc_str = data_link_info->description;
1513 desc_str = "(not supported)";
1514 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1524 /* Print the number of packets captured for each interface until we're killed. */
1526 print_statistics_loop(gboolean machine_readable)
1528 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1534 char errbuf[PCAP_ERRBUF_SIZE];
1535 struct pcap_stat ps;
1537 if_list = get_interface_list(&err, &err_str);
1538 if (if_list == NULL) {
1540 cmdarg_err("There are no interfaces on which a capture can be done");
1542 cmdarg_err("%s", err_str);
1548 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1549 if_info = (if_info_t *)if_entry->data;
1552 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
1553 * connections. We avoid collecting stats on them.
1555 if (!strncmp(if_info->name, "nf", 2)) {
1556 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
1562 #ifdef HAVE_PCAP_OPEN
1563 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1565 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1569 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1570 if_stat->name = g_strdup(if_info->name);
1572 stat_list = g_list_append(stat_list, if_stat);
1577 cmdarg_err("There are no interfaces on which a capture can be done");
1581 if (capture_child) {
1582 /* Let our parent know we succeeded. */
1583 pipe_write_block(2, SP_SUCCESS, NULL);
1586 if (!machine_readable) {
1587 printf("%-15s %10s %10s\n", "Interface", "Received",
1591 global_ld.go = TRUE;
1592 while (global_ld.go) {
1593 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1594 if_stat = (if_stat_t *)stat_entry->data;
1595 pcap_stats(if_stat->pch, &ps);
1597 if (!machine_readable) {
1598 printf("%-15s %10u %10u\n", if_stat->name,
1599 ps.ps_recv, ps.ps_drop);
1601 printf("%s\t%u\t%u\n", if_stat->name,
1602 ps.ps_recv, ps.ps_drop);
1607 /* If we have a dummy signal pipe check it */
1608 if (!signal_pipe_check_running()) {
1609 global_ld.go = FALSE;
1617 /* XXX - Not reached. Should we look for 'q' in stdin? */
1618 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1619 if_stat = (if_stat_t *)stat_entry->data;
1620 pcap_close(if_stat->pch);
1621 g_free(if_stat->name);
1624 g_list_free(stat_list);
1625 free_interface_list(if_list);
1633 capture_cleanup_handler(DWORD dwCtrlType)
1635 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1636 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1637 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1638 like SIGTERM at least when the machine's shutting down.
1640 For now, if we're running as a command rather than a capture child,
1641 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1642 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1643 in that way on UN*X.
1645 If we're not running as a capture child, we might be running as
1646 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1647 user logs out. (XXX - can we explicitly check whether we're
1648 running as a service?) */
1650 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1651 "Console: Control signal");
1652 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1653 "Console: Control signal, CtrlType: %u", dwCtrlType);
1655 /* Keep capture running if we're a service and a user logs off */
1656 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1657 capture_loop_stop();
1665 capture_cleanup_handler(int signum _U_)
1667 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1668 SIGTERM. We assume that if the user wanted it to keep running
1669 after they logged out, they'd have nohupped it. */
1671 /* Note: don't call g_log() in the signal handler: if we happened to be in
1672 * g_log() in process context when the signal came in, g_log will detect
1673 * the "recursion" and abort.
1676 capture_loop_stop();
1682 report_capture_count(gboolean reportit)
1684 /* Don't print this if we're a capture child. */
1685 if (!capture_child && reportit) {
1686 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packet_count);
1687 /* stderr could be line buffered */
1695 report_counts_for_siginfo(void)
1697 report_capture_count(quiet);
1698 infoprint = FALSE; /* we just reported it */
1702 report_counts_siginfo(int signum _U_)
1704 int sav_errno = errno;
1706 /* If we've been told to delay printing, just set a flag asking
1707 that we print counts (if we're supposed to), otherwise print
1708 the count of packets captured (if we're supposed to). */
1712 report_counts_for_siginfo();
1715 #endif /* SIGINFO */
1718 exit_main(int status)
1721 /* Shutdown windows sockets */
1724 /* can be helpful for debugging */
1725 #ifdef DEBUG_DUMPCAP
1726 printf("Press any key\n");
1737 * If we were linked with libcap (not related to libpcap), make sure we have
1738 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1739 * (See comment in main() for details)
1742 relinquish_privs_except_capture(void)
1744 /* If 'started_with_special_privs' (ie: suid) then enable for
1745 * ourself the NET_ADMIN and NET_RAW capabilities and then
1746 * drop our suid privileges.
1748 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1749 * stuff we don't need (and shouldn't have).
1750 * CAP_NET_RAW: Packet capture (raw sockets).
1753 if (started_with_special_privs()) {
1754 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1755 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1757 cap_t caps = cap_init(); /* all capabilities initialized to off */
1759 print_caps("Pre drop, pre set");
1761 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1762 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1765 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1766 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1768 if (cap_set_proc(caps)) {
1769 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1771 print_caps("Pre drop, post set");
1773 relinquish_special_privs_perm();
1775 print_caps("Post drop, pre set");
1776 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1777 if (cap_set_proc(caps)) {
1778 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1780 print_caps("Post drop, post set");
1786 #endif /* HAVE_LIBCAP */
1788 /* Take care of byte order in the libpcap headers read from pipes.
1789 * (function taken from wiretap/libpcap.c) */
1791 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1794 /* Byte-swap the record header fields. */
1795 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1796 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1797 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1798 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1801 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1802 swapped, in order to match the BPF header layout.
1804 Unfortunately, some files were, according to a comment in the "libpcap"
1805 source, written with version 2.3 in their headers but without the
1806 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1807 would make no sense - we assume that we need to swap them. */
1808 if (hdr->version_major == 2 &&
1809 (hdr->version_minor < 3 ||
1810 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1813 temp = rechdr->orig_len;
1814 rechdr->orig_len = rechdr->incl_len;
1815 rechdr->incl_len = temp;
1819 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1823 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1827 return recv(pipe_fd, buf, (int)sz, 0);
1832 return ws_read(pipe_fd, buf, sz);
1838 * Thread function that reads from a pipe and pushes the data
1839 * to the main application thread.
1842 * XXX Right now we use async queues for basic signaling. The main thread
1843 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1844 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1845 * Iff the read is successful cap_pipe_read pushes an item onto
1846 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1847 * the queues themselves (yet).
1849 * We might want to move some of the cap_pipe_dispatch logic here so that
1850 * we can let cap_thread_read run independently, queuing up multiple reads
1851 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1853 static void *cap_thread_read(void *arg)
1855 pcap_options *pcap_opts;
1858 DWORD b, last_err, bytes_read;
1864 pcap_opts = (pcap_options *)arg;
1865 while (pcap_opts->cap_pipe_err == PIPOK) {
1866 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1867 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1869 while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1870 if ((pcap_opts->from_cap_socket)
1876 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1877 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1880 pcap_opts->cap_pipe_err = PIPEOF;
1884 pcap_opts->cap_pipe_err = PIPERR;
1895 /* If we try to use read() on a named pipe on Windows with partial
1896 * data it appears to return EOF.
1898 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1899 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1904 last_err = GetLastError();
1905 if (last_err == ERROR_MORE_DATA) {
1907 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1908 pcap_opts->cap_pipe_err = PIPEOF;
1912 pcap_opts->cap_pipe_err = PIPERR;
1915 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1916 pcap_opts->cap_pipe_err = PIPEOF;
1923 pcap_opts->cap_pipe_bytes_read = bytes_read;
1924 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1925 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1927 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1933 /* Provide select() functionality for a single file descriptor
1934 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1936 * Returns the same values as select.
1939 cap_pipe_select(int pipe_fd)
1942 struct timeval timeout;
1945 FD_SET(pipe_fd, &rfds);
1947 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1948 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1950 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1953 #define DEF_TCP_PORT 19000
1956 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1958 char *sockname = pipename + 4;
1959 struct sockaddr_in sa;
1966 memset(&sa, 0, sizeof(sa));
1968 p = strchr(sockname, ':');
1970 len = strlen(sockname);
1971 port = DEF_TCP_PORT;
1975 port = strtoul(p + 1, &p, 10);
1976 if (*p || port > 65535) {
1985 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1987 if (inet_pton(AF_INET, buf, &sa.sin_addr) <= 0) {
1991 sa.sin_family = AF_INET;
1992 sa.sin_port = g_htons((u_short)port);
1994 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1995 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1997 LPTSTR errorText = NULL;
2000 lastError = WSAGetLastError();
2001 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2002 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2003 FORMAT_MESSAGE_IGNORE_INSERTS,
2004 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2005 (LPTSTR)&errorText, 0, NULL);
2007 g_snprintf(errmsg, errmsgl,
2008 "The capture session could not be initiated due to the socket error: \n"
2010 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
2012 LocalFree(errorText);
2014 " %d: %s", errno, g_strerror(errno));
2016 pcap_opts->cap_pipe_err = PIPERR;
2019 cap_pipe_close(fd, TRUE);
2023 pcap_opts->from_cap_socket = TRUE;
2027 g_snprintf(errmsg, errmsgl,
2028 "The capture session could not be initiated because\n"
2029 "\"%s\" is not a valid socket specification", pipename);
2030 pcap_opts->cap_pipe_err = PIPERR;
2034 /* Wrapper: distinguish between closesocket on Windows; use ws_close
2038 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
2042 closesocket(pipe_fd);
2049 /* Mimic pcap_open_live() for pipe captures
2051 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
2052 * open it, and read the header.
2054 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
2055 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
2057 cap_pipe_open_live(char *pipename,
2058 pcap_options *pcap_opts,
2059 struct pcap_hdr *hdr,
2060 char *errmsg, int errmsgl)
2063 ws_statb64 pipe_stat;
2064 struct sockaddr_un sa;
2068 interface_options interface_opts;
2070 char* extcap_pipe_name;
2071 gboolean extcap_pipe;
2075 int fd = -1, sel_ret;
2078 pcap_opts->cap_pipe_fd = -1;
2080 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2083 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
2086 * XXX - this blocks until a pcap per-file header has been written to
2087 * the pipe, so it could block indefinitely.
2089 if (strcmp(pipename, "-") == 0) {
2091 fd = 0; /* read from stdin */
2093 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
2095 } else if (!strncmp(pipename, "TCP@", 4)) {
2096 if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
2101 if (ws_stat64(pipename, &pipe_stat) < 0) {
2102 if (errno == ENOENT || errno == ENOTDIR)
2103 pcap_opts->cap_pipe_err = PIPNEXIST;
2105 g_snprintf(errmsg, errmsgl,
2106 "The capture session could not be initiated "
2107 "due to error getting information on pipe/socket: %s", g_strerror(errno));
2108 pcap_opts->cap_pipe_err = PIPERR;
2112 if (S_ISFIFO(pipe_stat.st_mode)) {
2113 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
2115 g_snprintf(errmsg, errmsgl,
2116 "The capture session could not be initiated "
2117 "due to error on pipe open: %s", g_strerror(errno));
2118 pcap_opts->cap_pipe_err = PIPERR;
2121 } else if (S_ISSOCK(pipe_stat.st_mode)) {
2122 fd = socket(AF_UNIX, SOCK_STREAM, 0);
2124 g_snprintf(errmsg, errmsgl,
2125 "The capture session could not be initiated "
2126 "due to error on socket create: %s", g_strerror(errno));
2127 pcap_opts->cap_pipe_err = PIPERR;
2130 sa.sun_family = AF_UNIX;
2132 * The Single UNIX Specification says:
2134 * The size of sun_path has intentionally been left undefined.
2135 * This is because different implementations use different sizes.
2136 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
2137 * of 104. Since most implementations originate from BSD versions,
2138 * the size is typically in the range 92 to 108.
2140 * Applications should not assume a particular length for sun_path
2141 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
2145 * The <sys/un.h> header shall define the sockaddr_un structure,
2146 * which shall include at least the following members:
2148 * sa_family_t sun_family Address family.
2149 * char sun_path[] Socket pathname.
2151 * so we assume that it's an array, with a specified size,
2152 * and that the size reflects the maximum path length.
2154 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
2155 /* Path name too long */
2156 g_snprintf(errmsg, errmsgl,
2157 "The capture session coud not be initiated "
2158 "due to error on socket connect: Path name too long");
2159 pcap_opts->cap_pipe_err = PIPERR;
2163 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
2165 g_snprintf(errmsg, errmsgl,
2166 "The capture session coud not be initiated "
2167 "due to error on socket connect: %s", g_strerror(errno));
2168 pcap_opts->cap_pipe_err = PIPERR;
2173 if (S_ISCHR(pipe_stat.st_mode)) {
2175 * Assume the user specified an interface on a system where
2176 * interfaces are in /dev. Pretend we haven't seen it.
2178 pcap_opts->cap_pipe_err = PIPNEXIST;
2180 g_snprintf(errmsg, errmsgl,
2181 "The capture session could not be initiated because\n"
2182 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
2183 pcap_opts->cap_pipe_err = PIPERR;
2188 #define PIPE_STR "\\pipe\\"
2189 /* Under Windows, named pipes _must_ have the form
2190 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
2192 pncopy = g_strdup(pipename);
2193 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
2194 pos = strchr(pncopy + 3, '\\');
2195 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
2202 g_snprintf(errmsg, errmsgl,
2203 "The capture session could not be initiated because\n"
2204 "\"%s\" is neither an interface nor a pipe", pipename);
2205 pcap_opts->cap_pipe_err = PIPNEXIST;
2209 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
2211 extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
2212 extcap_pipe = strstr(interface_opts.name, extcap_pipe_name) ? TRUE : FALSE;
2213 g_free(extcap_pipe_name);
2216 /* Wait for the pipe to appear */
2221 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
2224 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
2225 OPEN_EXISTING, 0, NULL);
2227 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
2230 if (GetLastError() != ERROR_PIPE_BUSY) {
2231 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2232 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2233 g_snprintf(errmsg, errmsgl,
2234 "The capture session on \"%s\" could not be started "
2235 "due to error on pipe open: %s (error %d)",
2236 pipename, utf_16to8(err_str), GetLastError());
2238 pcap_opts->cap_pipe_err = PIPERR;
2242 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
2243 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2244 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2245 g_snprintf(errmsg, errmsgl,
2246 "The capture session on \"%s\" timed out during "
2247 "pipe open: %s (error %d)",
2248 pipename, utf_16to8(err_str), GetLastError());
2250 pcap_opts->cap_pipe_err = PIPERR;
2257 pcap_opts->from_cap_pipe = TRUE;
2260 if (pcap_opts->from_cap_socket)
2263 /* read the pcap header */
2265 while (bytes_read < sizeof magic) {
2267 g_snprintf(errmsg, errmsgl, "Invalid file descriptor");
2271 sel_ret = cap_pipe_select(fd);
2273 g_snprintf(errmsg, errmsgl,
2274 "Unexpected error from select: %s", g_strerror(errno));
2276 } else if (sel_ret > 0) {
2277 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
2278 sizeof magic-bytes_read,
2279 pcap_opts->from_cap_socket);
2282 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2284 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2294 #if GLIB_CHECK_VERSION(2,31,0)
2295 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
2297 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
2300 pcap_opts->cap_pipe_buf = (char *) &magic;
2301 pcap_opts->cap_pipe_bytes_read = 0;
2302 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
2303 /* We don't have to worry about cap_pipe_read_mtx here */
2304 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2305 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2306 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2307 if (pcap_opts->cap_pipe_bytes_read == 0)
2308 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2310 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2319 case PCAP_NSEC_MAGIC:
2320 /* Host that wrote it has our byte order, and was running
2321 a program using either standard or ss990417 libpcap. */
2322 pcap_opts->cap_pipe_byte_swapped = FALSE;
2323 pcap_opts->cap_pipe_modified = FALSE;
2324 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
2326 case PCAP_MODIFIED_MAGIC:
2327 /* Host that wrote it has our byte order, but was running
2328 a program using either ss990915 or ss991029 libpcap. */
2329 pcap_opts->cap_pipe_byte_swapped = FALSE;
2330 pcap_opts->cap_pipe_modified = TRUE;
2332 case PCAP_SWAPPED_MAGIC:
2333 case PCAP_SWAPPED_NSEC_MAGIC:
2334 /* Host that wrote it has a byte order opposite to ours,
2335 and was running a program using either standard or
2336 ss990417 libpcap. */
2337 pcap_opts->cap_pipe_byte_swapped = TRUE;
2338 pcap_opts->cap_pipe_modified = FALSE;
2339 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2341 case PCAP_SWAPPED_MODIFIED_MAGIC:
2342 /* Host that wrote it out has a byte order opposite to
2343 ours, and was running a program using either ss990915
2344 or ss991029 libpcap. */
2345 pcap_opts->cap_pipe_byte_swapped = TRUE;
2346 pcap_opts->cap_pipe_modified = TRUE;
2349 /* Not a "libpcap" type we know about. */
2350 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2355 if (pcap_opts->from_cap_socket)
2358 /* Read the rest of the header */
2360 while (bytes_read < sizeof(struct pcap_hdr)) {
2361 sel_ret = cap_pipe_select(fd);
2363 g_snprintf(errmsg, errmsgl,
2364 "Unexpected error from select: %s", g_strerror(errno));
2366 } else if (sel_ret > 0) {
2367 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2368 sizeof(struct pcap_hdr) - bytes_read,
2369 pcap_opts->from_cap_socket);
2372 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2374 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
2384 pcap_opts->cap_pipe_buf = (char *) hdr;
2385 pcap_opts->cap_pipe_bytes_read = 0;
2386 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
2387 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2388 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2389 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2390 if (pcap_opts->cap_pipe_bytes_read == 0)
2391 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2393 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
2400 if (pcap_opts->cap_pipe_byte_swapped) {
2401 /* Byte-swap the header fields about which we care. */
2402 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
2403 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
2404 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
2405 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
2407 pcap_opts->linktype = hdr->network;
2409 if (hdr->version_major < 2) {
2410 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2414 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2415 pcap_opts->cap_pipe_err = PIPOK;
2416 pcap_opts->cap_pipe_fd = fd;
2420 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2421 pcap_opts->cap_pipe_err = PIPERR;
2422 cap_pipe_close(fd, pcap_opts->from_cap_socket);
2423 pcap_opts->cap_pipe_fd = -1;
2427 /* We read one record from the pipe, take care of byte order in the record
2428 * header, write the record to the capture file, and update capture statistics. */
2430 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2432 struct pcap_pkthdr phdr;
2433 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2436 #if !GLIB_CHECK_VERSION(2,31,18)
2444 #ifdef LOG_CAPTURE_VERBOSE
2445 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2448 switch (pcap_opts->cap_pipe_state) {
2450 case STATE_EXPECT_REC_HDR:
2452 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2455 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2456 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2457 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2458 pcap_opts->cap_pipe_bytes_read = 0;
2461 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2462 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2463 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2468 case STATE_READ_REC_HDR:
2470 if (pcap_opts->from_cap_socket)
2473 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2474 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
2477 result = PD_PIPE_EOF;
2479 result = PD_PIPE_ERR;
2482 pcap_opts->cap_pipe_bytes_read += b;
2486 #if GLIB_CHECK_VERSION(2,31,18)
2487 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2489 g_get_current_time(&wait_time);
2490 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2491 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2493 if (pcap_opts->cap_pipe_err == PIPEOF) {
2494 result = PD_PIPE_EOF;
2496 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2497 result = PD_PIPE_ERR;
2505 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2507 result = PD_REC_HDR_READ;
2510 case STATE_EXPECT_DATA:
2512 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2515 pcap_opts->cap_pipe_state = STATE_READ_DATA;
2516 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2517 pcap_opts->cap_pipe_bytes_read = 0;
2520 pcap_opts->cap_pipe_buf = (char *) data;
2521 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2522 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2527 case STATE_READ_DATA:
2529 if (pcap_opts->from_cap_socket)
2532 b = cap_pipe_read(pcap_opts->cap_pipe_fd,
2533 data+pcap_opts->cap_pipe_bytes_read,
2534 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
2535 pcap_opts->from_cap_socket);
2538 result = PD_PIPE_EOF;
2540 result = PD_PIPE_ERR;
2543 pcap_opts->cap_pipe_bytes_read += b;
2548 #if GLIB_CHECK_VERSION(2,31,18)
2549 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2551 g_get_current_time(&wait_time);
2552 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2553 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2554 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2555 if (pcap_opts->cap_pipe_err == PIPEOF) {
2556 result = PD_PIPE_EOF;
2558 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2559 result = PD_PIPE_ERR;
2567 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2569 result = PD_DATA_READ;
2573 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2576 } /* switch (pcap_opts->cap_pipe_state) */
2579 * We've now read as much data as we were expecting, so process it.
2583 case PD_REC_HDR_READ:
2584 /* We've read the header. Take care of byte order. */
2585 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2586 &pcap_opts->cap_pipe_rechdr.hdr);
2587 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2588 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2589 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2593 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2594 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2597 /* no data to read? fall through */
2600 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2601 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2602 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2603 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2604 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2607 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2609 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2611 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2615 pcap_opts->cap_pipe_err = PIPEOF;
2620 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2621 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2622 g_snprintf(errmsg, errmsgl,
2623 "Error reading from pipe: %s (error %d)",
2624 utf_16to8(err_str), GetLastError());
2627 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2635 pcap_opts->cap_pipe_err = PIPERR;
2636 /* Return here rather than inside the switch to prevent GCC warning */
2641 /** Open the capture input file (pcap or capture pipe).
2642 * Returns TRUE if it succeeds, FALSE otherwise. */
2644 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2645 char *errmsg, size_t errmsg_len,
2646 char *secondary_errmsg, size_t secondary_errmsg_len)
2648 gchar open_err_str[PCAP_ERRBUF_SIZE];
2649 gchar *sync_msg_str;
2650 interface_options interface_opts;
2651 pcap_options *pcap_opts;
2655 WORD wVersionRequested;
2659 /* XXX - opening Winsock on tshark? */
2661 /* Initialize Windows Socket if we are in a WIN32 OS
2662 This needs to be done before querying the interface for network/netmask */
2664 /* XXX - do we really require 1.1 or earlier?
2665 Are there any versions that support only 2.0 or higher? */
2666 wVersionRequested = MAKEWORD(1, 1);
2667 err = WSAStartup(wVersionRequested, &wsaData);
2671 case WSASYSNOTREADY:
2672 g_snprintf(errmsg, (gulong) errmsg_len,
2673 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2676 case WSAVERNOTSUPPORTED:
2677 g_snprintf(errmsg, (gulong) errmsg_len,
2678 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2679 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2682 case WSAEINPROGRESS:
2683 g_snprintf(errmsg, (gulong) errmsg_len,
2684 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2688 g_snprintf(errmsg, (gulong) errmsg_len,
2689 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2693 g_snprintf(errmsg, (gulong) errmsg_len,
2694 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2698 g_snprintf(errmsg, (gulong) errmsg_len,
2699 "Couldn't initialize Windows Sockets: error %d", err);
2702 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2706 if ((use_threads == FALSE) &&
2707 (capture_opts->ifaces->len > 1)) {
2708 g_snprintf(errmsg, (gulong) errmsg_len,
2709 "Using threads is required for capturing on multiple interfaces.");
2713 for (i = 0; i < capture_opts->ifaces->len; i++) {
2714 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2715 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2716 if (pcap_opts == NULL) {
2717 g_snprintf(errmsg, (gulong) errmsg_len,
2718 "Could not allocate memory.");
2721 pcap_opts->received = 0;
2722 pcap_opts->dropped = 0;
2723 pcap_opts->flushed = 0;
2724 pcap_opts->pcap_h = NULL;
2725 #ifdef MUST_DO_SELECT
2726 pcap_opts->pcap_fd = -1;
2728 pcap_opts->pcap_err = FALSE;
2729 pcap_opts->interface_id = i;
2730 pcap_opts->tid = NULL;
2731 pcap_opts->snaplen = 0;
2732 pcap_opts->linktype = -1;
2733 pcap_opts->ts_nsec = FALSE;
2734 pcap_opts->from_cap_pipe = FALSE;
2735 pcap_opts->from_cap_socket = FALSE;
2736 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2737 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2739 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2741 pcap_opts->cap_pipe_fd = -1;
2742 pcap_opts->cap_pipe_modified = FALSE;
2743 pcap_opts->cap_pipe_byte_swapped = FALSE;
2745 pcap_opts->cap_pipe_buf = NULL;
2747 pcap_opts->cap_pipe_bytes_to_read = 0;
2748 pcap_opts->cap_pipe_bytes_read = 0;
2749 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2750 pcap_opts->cap_pipe_err = PIPOK;
2752 #if GLIB_CHECK_VERSION(2,31,0)
2753 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2754 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2756 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2758 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2759 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2761 g_array_append_val(ld->pcaps, pcap_opts);
2763 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2764 pcap_opts->pcap_h = open_capture_device(capture_opts, &interface_opts, &open_err_str);
2766 if (pcap_opts->pcap_h != NULL) {
2767 /* we've opened "iface" as a network device */
2769 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2770 /* Find out if we're getting nanosecond-precision time stamps */
2771 pcap_opts->ts_nsec = have_high_resolution_timestamp(pcap_opts->pcap_h);
2774 #if defined(HAVE_PCAP_SETSAMPLING)
2775 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2776 struct pcap_samp *samp;
2778 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2779 switch (interface_opts.sampling_method) {
2780 case CAPTURE_SAMP_BY_COUNT:
2781 samp->method = PCAP_SAMP_1_EVERY_N;
2784 case CAPTURE_SAMP_BY_TIMER:
2785 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2789 sync_msg_str = g_strdup_printf(
2790 "Unknown sampling method %d specified,\n"
2791 "continue without packet sampling",
2792 interface_opts.sampling_method);
2793 report_capture_error("Couldn't set the capture "
2794 "sampling", sync_msg_str);
2795 g_free(sync_msg_str);
2797 samp->value = interface_opts.sampling_param;
2799 report_capture_error("Couldn't set the capture sampling",
2800 "Cannot get packet sampling data structure");
2805 /* setting the data link type only works on real interfaces */
2806 if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2808 secondary_errmsg, secondary_errmsg_len)) {
2811 pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2813 /* We couldn't open "iface" as a network device. */
2814 /* Try to open it as a pipe */
2815 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2818 if (pcap_opts->cap_pipe_fd == -1) {
2820 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2822 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2823 /* Pipe doesn't exist, so output message for interface */
2824 get_capture_device_open_failure_messages(open_err_str,
2825 interface_opts.name,
2829 secondary_errmsg_len);
2832 * Else pipe (or file) does exist and cap_pipe_open_live() has
2837 /* cap_pipe_open_live() succeeded; don't want
2838 error message from pcap_open_live() */
2839 open_err_str[0] = '\0';
2843 /* XXX - will this work for tshark? */
2844 #ifdef MUST_DO_SELECT
2845 if (!pcap_opts->from_cap_pipe) {
2846 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2847 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2849 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2854 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2855 returned a warning; print it, but keep capturing. */
2856 if (open_err_str[0] != '\0') {
2857 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2858 report_capture_error(sync_msg_str, "");
2859 g_free(sync_msg_str);
2861 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2862 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2865 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2866 /* to remove any suid privileges. */
2867 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2868 /* (euid/egid have already previously been set to ruid/rgid. */
2869 /* (See comment in main() for details) */
2871 relinquish_special_privs_perm();
2873 relinquish_all_capabilities();
2878 /* close the capture input file (pcap or capture pipe) */
2879 static void capture_loop_close_input(loop_data *ld)
2882 pcap_options *pcap_opts;
2884 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2886 for (i = 0; i < ld->pcaps->len; i++) {
2887 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2888 /* if open, close the capture pipe "input file" */
2889 if (pcap_opts->cap_pipe_fd >= 0) {
2890 g_assert(pcap_opts->from_cap_pipe);
2891 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2892 pcap_opts->cap_pipe_fd = -1;
2895 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2896 CloseHandle(pcap_opts->cap_pipe_h);
2897 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2900 /* if open, close the pcap "input file" */
2901 if (pcap_opts->pcap_h != NULL) {
2902 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2903 pcap_close(pcap_opts->pcap_h);
2904 pcap_opts->pcap_h = NULL;
2911 /* Shut down windows sockets */
2917 /* init the capture filter */
2918 static initfilter_status_t
2919 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2920 const gchar * name, const gchar * cfilter)
2922 struct bpf_program fcode;
2924 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2926 /* capture filters only work on real interfaces */
2927 if (cfilter && !from_cap_pipe) {
2928 /* A capture filter was specified; set it up. */
2929 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2930 /* Treat this specially - our caller might try to compile this
2931 as a display filter and, if that succeeds, warn the user that
2932 the display and capture filter syntaxes are different. */
2933 return INITFILTER_BAD_FILTER;
2935 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2936 #ifdef HAVE_PCAP_FREECODE
2937 pcap_freecode(&fcode);
2939 return INITFILTER_OTHER_ERROR;
2941 #ifdef HAVE_PCAP_FREECODE
2942 pcap_freecode(&fcode);
2946 return INITFILTER_NO_ERROR;
2950 /* set up to write to the already-opened capture output file/files */
2952 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2956 pcap_options *pcap_opts;
2957 interface_options interface_opts;
2958 gboolean successful;
2960 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2962 if ((capture_opts->use_pcapng == FALSE) &&
2963 (capture_opts->ifaces->len > 1)) {
2964 g_snprintf(errmsg, errmsg_len,
2965 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
2969 /* Set up to write to the capture file. */
2970 if (capture_opts->multi_files_on) {
2971 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2973 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2974 if (ld->pdh == NULL) {
2979 if (capture_opts->use_pcapng) {
2981 GString *os_info_str;
2983 os_info_str = g_string_new("");
2984 get_os_version_info(os_info_str);
2986 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2987 successful = pcapng_write_session_header_block(ld->pdh,
2988 (const char *)capture_opts->capture_comment, /* Comment*/
2990 os_info_str->str, /* OS*/
2992 -1, /* section_length */
2997 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2998 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2999 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
3000 if (pcap_opts->from_cap_pipe) {
3001 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
3003 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
3005 successful = pcapng_write_interface_description_block(global_ld.pdh,
3006 NULL, /* OPT_COMMENT 1 */
3007 interface_opts.name, /* IDB_NAME 2 */
3008 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3009 interface_opts.cfilter, /* IDB_FILTER 11 */
3010 os_info_str->str, /* IDB_OS 12 */
3011 pcap_opts->linktype,
3013 &(global_ld.bytes_written),
3014 0, /* IDB_IF_SPEED 8 */
3015 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3019 g_string_free(os_info_str, TRUE);
3022 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
3023 if (pcap_opts->from_cap_pipe) {
3024 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
3026 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
3028 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
3029 pcap_opts->ts_nsec, &ld->bytes_written, &err);
3037 if (ld->pdh == NULL) {
3038 /* We couldn't set up to write to the capture file. */
3039 /* XXX - use cf_open_error_message from tshark instead? */
3044 g_snprintf(errmsg, errmsg_len,
3045 "The file to which the capture would be"
3046 " saved (\"%s\") could not be opened: Error %d.",
3047 capture_opts->save_file, err);
3049 g_snprintf(errmsg, errmsg_len,
3050 "The file to which the capture would be"
3051 " saved (\"%s\") could not be opened: %s.",
3052 capture_opts->save_file, g_strerror(err));
3064 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
3068 pcap_options *pcap_opts;
3069 guint64 end_time = create_timestamp();
3071 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
3073 if (capture_opts->multi_files_on) {
3074 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
3076 if (capture_opts->use_pcapng) {
3077 for (i = 0; i < global_ld.pcaps->len; i++) {
3078 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3079 if (!pcap_opts->from_cap_pipe) {
3080 guint64 isb_ifrecv, isb_ifdrop;
3081 struct pcap_stat stats;
3083 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
3084 isb_ifrecv = pcap_opts->received;
3085 isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
3087 isb_ifrecv = G_MAXUINT64;
3088 isb_ifdrop = G_MAXUINT64;
3090 pcapng_write_interface_statistics_block(ld->pdh,
3093 "Counters provided by dumpcap",
3102 if (fclose(ld->pdh) == EOF) {
3103 if (err_close != NULL) {
3113 /* dispatch incoming packets (pcap or capture pipe)
3115 * Waits for incoming packets to be available, and calls pcap_dispatch()
3116 * to cause them to be processed.
3118 * Returns the number of packets which were processed.
3120 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3121 * packet-batching behaviour does not cause packets to get held back
3125 capture_loop_dispatch(loop_data *ld,
3126 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
3129 gint packet_count_before;
3130 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
3135 packet_count_before = ld->packet_count;
3136 if (pcap_opts->from_cap_pipe) {
3137 /* dispatch from capture pipe */
3138 #ifdef LOG_CAPTURE_VERBOSE
3139 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3142 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
3144 if (sel_ret < 0 && errno != EINTR) {
3145 g_snprintf(errmsg, errmsg_len,
3146 "Unexpected error from select: %s", g_strerror(errno));
3147 report_capture_error(errmsg, please_report);
3152 * "select()" says we can read from the pipe without blocking
3155 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
3165 /* dispatch from pcap */
3166 #ifdef MUST_DO_SELECT
3168 * If we have "pcap_get_selectable_fd()", we use it to get the
3169 * descriptor on which to select; if that's -1, it means there
3170 * is no descriptor on which you can do a "select()" (perhaps
3171 * because you're capturing on a special device, and that device's
3172 * driver unfortunately doesn't support "select()", in which case
3173 * we don't do the select - which means it might not be possible
3174 * to stop a capture until a packet arrives. If that's unacceptable,
3175 * plead with whoever supplies the software for that device to add
3176 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3177 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3178 * later, so it can use pcap_breakloop().
3180 #ifdef LOG_CAPTURE_VERBOSE
3181 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3183 if (pcap_opts->pcap_fd != -1) {
3184 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
3187 * "select()" says we can read from it without blocking; go for
3190 * We don't have pcap_breakloop(), so we only process one packet
3191 * per pcap_dispatch() call, to allow a signal to stop the
3192 * processing immediately, rather than processing all packets
3193 * in a batch before quitting.
3196 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3198 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3202 /* Error, rather than pcap_breakloop(). */
3203 pcap_opts->pcap_err = TRUE;
3205 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3208 if (sel_ret < 0 && errno != EINTR) {
3209 g_snprintf(errmsg, errmsg_len,
3210 "Unexpected error from select: %s", g_strerror(errno));
3211 report_capture_error(errmsg, please_report);
3217 #endif /* MUST_DO_SELECT */
3219 /* dispatch from pcap without select */
3221 #ifdef LOG_CAPTURE_VERBOSE
3222 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3226 * On Windows, we don't support asynchronously telling a process to
3227 * stop capturing; instead, we check for an indication on a pipe
3228 * after processing packets. We therefore process only one packet
3229 * at a time, so that we can check the pipe after every packet.
3232 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3234 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3238 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3240 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3245 /* Error, rather than pcap_breakloop(). */
3246 pcap_opts->pcap_err = TRUE;
3248 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3250 #else /* pcap_next_ex */
3251 #ifdef LOG_CAPTURE_VERBOSE
3252 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3254 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3257 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3258 * see https://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
3259 * This should be fixed in the WinPcap 4.0 alpha release.
3261 * For reference, an example remote interface:
3262 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3265 /* emulate dispatch from pcap */
3268 struct pcap_pkthdr *pkt_header;
3273 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
3275 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3277 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3282 pcap_opts->pcap_err = TRUE;
3286 #endif /* pcap_next_ex */
3290 #ifdef LOG_CAPTURE_VERBOSE
3291 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3294 return ld->packet_count - packet_count_before;
3298 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3299 * want to grab only the characters between the '{' and '}' delimiters.
3301 * Returns a GString that must be freed with g_string_free(). */
3303 isolate_uuid(const char *iface)
3308 ptr = strchr(iface, '{');
3310 return g_string_new(iface);
3311 gstr = g_string_new(ptr + 1);
3313 ptr = strchr(gstr->str, '}');
3317 gstr = g_string_truncate(gstr, ptr - gstr->str);
3322 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3323 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3325 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3326 char *errmsg, int errmsg_len)
3329 gchar *capfile_name;
3331 gboolean is_tempfile;
3333 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3334 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3336 if (capture_opts->save_file != NULL) {
3337 /* We return to the caller while the capture is in progress.
3338 * Therefore we need to take a copy of save_file in
3339 * case the caller destroys it after we return.
3341 capfile_name = g_strdup(capture_opts->save_file);
3343 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3344 if (capture_opts->multi_files_on) {
3345 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3346 g_snprintf(errmsg, errmsg_len,
3347 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3348 g_free(capfile_name);
3351 if (strcmp(capfile_name, "-") == 0) {
3352 /* write to stdout */
3355 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3356 _setmode(1, O_BINARY);
3359 } /* if (...output_to_pipe ... */
3362 if (capture_opts->multi_files_on) {
3363 /* ringbuffer is enabled */
3364 *save_file_fd = ringbuf_init(capfile_name,
3365 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3366 capture_opts->group_read_access);
3368 /* we need the ringbuf name */
3369 if (*save_file_fd != -1) {
3370 g_free(capfile_name);
3371 capfile_name = g_strdup(ringbuf_current_filename());
3374 /* Try to open/create the specified file for use as a capture buffer. */
3375 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
3376 (capture_opts->group_read_access) ? 0640 : 0600);
3379 is_tempfile = FALSE;
3381 /* Choose a random name for the temporary capture buffer */
3382 if (global_capture_opts.ifaces->len > 1) {
3383 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3386 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
3388 /* use the generic portion of the interface guid to form the basis of the filename */
3389 if (strncmp("NPF_{", basename, 5)==0)
3391 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3393 iface = isolate_uuid(basename);
3395 basename = g_strdup(iface->str);
3396 g_string_free(iface, TRUE);
3399 /* generate the temp file name prefix...
3400 * It would be nice if we could specify a pcapng/pcap filename suffix,
3401 * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
3402 if (capture_opts->use_pcapng) {
3403 prefix = g_strconcat("wireshark_pcapng_", basename, NULL);
3405 prefix = g_strconcat("wireshark_pcap_", basename, NULL);
3409 *save_file_fd = create_tempfile(&tmpname, prefix);
3411 capfile_name = g_strdup(tmpname);
3415 /* did we fail to open the output file? */
3416 if (*save_file_fd == -1) {
3418 g_snprintf(errmsg, errmsg_len,
3419 "The temporary file to which the capture would be saved (\"%s\") "
3420 "could not be opened: %s.", capfile_name, g_strerror(errno));
3422 if (capture_opts->multi_files_on) {
3423 ringbuf_error_cleanup();
3426 g_snprintf(errmsg, errmsg_len,
3427 "The file to which the capture would be saved (\"%s\") "
3428 "could not be opened: %s.", capfile_name,
3431 g_free(capfile_name);
3435 if (capture_opts->save_file != NULL) {
3436 g_free(capture_opts->save_file);
3438 capture_opts->save_file = capfile_name;
3439 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3440 "g_free(capfile_name)". */
3446 /* Do the work of handling either the file size or file duration capture
3447 conditions being reached, and switching files or stopping. */
3449 do_file_switch_or_stop(capture_options *capture_opts,
3450 condition *cnd_autostop_files,
3451 condition *cnd_autostop_size,
3452 condition *cnd_file_duration)
3455 pcap_options *pcap_opts;
3456 interface_options interface_opts;
3457 gboolean successful;
3459 if (capture_opts->multi_files_on) {
3460 if (cnd_autostop_files != NULL &&
3461 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
3462 /* no files left: stop here */
3463 global_ld.go = FALSE;
3467 /* Switch to the next ringbuffer file */
3468 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3469 &global_ld.save_file_fd, &global_ld.err)) {
3471 /* File switch succeeded: reset the conditions */
3472 global_ld.bytes_written = 0;
3473 if (capture_opts->use_pcapng) {
3475 GString *os_info_str;
3477 os_info_str = g_string_new("");
3478 get_os_version_info(os_info_str);
3480 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
3481 successful = pcapng_write_session_header_block(global_ld.pdh,
3484 os_info_str->str, /* OS */
3486 -1, /* section_length */
3487 &(global_ld.bytes_written),
3491 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3492 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3493 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3494 successful = pcapng_write_interface_description_block(global_ld.pdh,
3495 NULL, /* OPT_COMMENT 1 */
3496 interface_opts.name, /* IDB_NAME 2 */
3497 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3498 interface_opts.cfilter, /* IDB_FILTER 11 */
3499 os_info_str->str, /* IDB_OS 12 */
3500 pcap_opts->linktype,
3502 &(global_ld.bytes_written),
3503 0, /* IDB_IF_SPEED 8 */
3504 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3508 g_string_free(os_info_str, TRUE);
3511 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3512 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3513 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3516 fclose(global_ld.pdh);
3517 global_ld.pdh = NULL;
3518 global_ld.go = FALSE;
3521 if (cnd_autostop_size)
3522 cnd_reset(cnd_autostop_size);
3523 if (cnd_file_duration)
3524 cnd_reset(cnd_file_duration);
3525 fflush(global_ld.pdh);
3527 report_packet_count(global_ld.inpkts_to_sync_pipe);
3528 global_ld.inpkts_to_sync_pipe = 0;
3529 report_new_capture_file(capture_opts->save_file);
3531 /* File switch failed: stop here */
3532 global_ld.go = FALSE;
3536 /* single file, stop now */
3537 global_ld.go = FALSE;
3544 pcap_read_handler(void* arg)
3546 pcap_options *pcap_opts;
3547 char errmsg[MSG_MAX_LENGTH+1];
3549 pcap_opts = (pcap_options *)arg;
3551 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3552 pcap_opts->interface_id);
3554 while (global_ld.go) {
3555 /* dispatch incoming packets */
3556 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3558 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3559 pcap_opts->interface_id);
3560 g_thread_exit(NULL);
3564 /* Do the low-level work of a capture.
3565 Returns TRUE if it succeeds, FALSE otherwise. */
3567 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3570 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3572 struct timeval upd_time, cur_time;
3576 condition *cnd_file_duration = NULL;
3577 condition *cnd_autostop_files = NULL;
3578 condition *cnd_autostop_size = NULL;
3579 condition *cnd_autostop_duration = NULL;
3582 gboolean cfilter_error = FALSE;
3583 char errmsg[MSG_MAX_LENGTH+1];
3584 char secondary_errmsg[MSG_MAX_LENGTH+1];
3585 pcap_options *pcap_opts;
3586 interface_options interface_opts;
3587 guint i, error_index = 0;
3590 *secondary_errmsg = '\0';
3592 /* init the loop data */
3593 global_ld.go = TRUE;
3594 global_ld.packet_count = 0;
3596 global_ld.report_packet_count = FALSE;
3598 if (capture_opts->has_autostop_packets)
3599 global_ld.packet_max = capture_opts->autostop_packets;
3601 global_ld.packet_max = 0; /* no limit */
3602 global_ld.inpkts_to_sync_pipe = 0;
3603 global_ld.err = 0; /* no error seen yet */
3604 global_ld.pdh = NULL;
3605 global_ld.autostop_files = 0;
3606 global_ld.save_file_fd = -1;
3608 /* We haven't yet gotten the capture statistics. */
3609 *stats_known = FALSE;
3611 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3612 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3614 /* open the "input file" from network interface or capture pipe */
3615 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3616 secondary_errmsg, sizeof(secondary_errmsg))) {
3619 for (i = 0; i < capture_opts->ifaces->len; i++) {
3620 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3621 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3622 /* init the input filter from the network interface (capture pipe will do nothing) */
3624 * When remote capturing WinPCap crashes when the capture filter
3625 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3628 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3629 interface_opts.name,
3630 interface_opts.cfilter?interface_opts.cfilter:"")) {
3632 case INITFILTER_NO_ERROR:
3635 case INITFILTER_BAD_FILTER:
3636 cfilter_error = TRUE;
3638 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3641 case INITFILTER_OTHER_ERROR:
3642 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3643 pcap_geterr(pcap_opts->pcap_h));
3644 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3649 /* If we're supposed to write to a capture file, open it for output
3650 (temporary/specified name/ringbuffer) */
3651 if (capture_opts->saving_to_file) {
3652 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3653 errmsg, sizeof(errmsg))) {
3657 /* set up to write to the already-opened capture output file/files */
3658 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3663 /* XXX - capture SIGTERM and close the capture, in case we're on a
3664 Linux 2.0[.x] system and you have to explicitly close the capture
3665 stream in order to turn promiscuous mode off? We need to do that
3666 in other places as well - and I don't think that works all the
3667 time in any case, due to libpcap bugs. */
3669 /* Well, we should be able to start capturing.
3671 Sync out the capture file, so the header makes it to the file system,
3672 and send a "capture started successfully and capture file created"
3673 message to our parent so that they'll open the capture file and
3674 update its windows to indicate that we have a live capture in
3676 fflush(global_ld.pdh);
3677 report_new_capture_file(capture_opts->save_file);
3680 /* initialize capture stop (and alike) conditions */
3681 init_capture_stop_conditions();
3682 /* create stop conditions */
3683 if (capture_opts->has_autostop_filesize) {
3684 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3685 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3688 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3690 if (capture_opts->has_autostop_duration)
3691 cnd_autostop_duration =
3692 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3694 if (capture_opts->multi_files_on) {
3695 if (capture_opts->has_file_duration)
3697 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3699 if (capture_opts->has_autostop_files)
3700 cnd_autostop_files =
3701 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3704 /* init the time values */
3706 upd_time = GetTickCount();
3708 gettimeofday(&upd_time, NULL);
3710 start_time = create_timestamp();
3711 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3713 /* WOW, everything is prepared! */
3714 /* please fasten your seat belts, we will enter now the actual capture loop */
3716 pcap_queue = g_async_queue_new();
3717 pcap_queue_bytes = 0;
3718 pcap_queue_packets = 0;
3719 for (i = 0; i < global_ld.pcaps->len; i++) {
3720 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3721 #if GLIB_CHECK_VERSION(2,31,0)
3722 /* XXX - Add an interface name here? */
3723 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3725 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3729 while (global_ld.go) {
3730 /* dispatch incoming packets */
3732 pcap_queue_element *queue_element;
3733 #if GLIB_CHECK_VERSION(2,31,18)
3735 g_async_queue_lock(pcap_queue);
3736 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3738 GTimeVal write_thread_time;
3740 g_get_current_time(&write_thread_time);
3741 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3742 g_async_queue_lock(pcap_queue);
3743 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3745 if (queue_element) {
3746 pcap_queue_bytes -= queue_element->phdr.caplen;
3747 pcap_queue_packets -= 1;
3749 g_async_queue_unlock(pcap_queue);
3750 if (queue_element) {
3751 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3752 "Dequeued a packet of length %d captured on interface %d.",
3753 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3755 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3756 &queue_element->phdr,
3758 g_free(queue_element->pd);
3759 g_free(queue_element);
3765 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3766 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3767 sizeof(errmsg), pcap_opts);
3770 /* Were we asked to print packet counts by the SIGINFO handler? */
3771 if (global_ld.report_packet_count) {
3772 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3773 plurality(global_ld.packet_count, "", "s"));
3774 global_ld.report_packet_count = FALSE;
3779 /* any news from our parent (signal pipe)? -> just stop the capture */
3780 if (!signal_pipe_check_running()) {
3781 global_ld.go = FALSE;
3786 global_ld.inpkts_to_sync_pipe += inpkts;
3788 /* check capture size condition */
3789 if (cnd_autostop_size != NULL &&
3790 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3791 /* Capture size limit reached, do we have another file? */
3792 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3793 cnd_autostop_size, cnd_file_duration))
3795 } /* cnd_autostop_size */
3796 if (capture_opts->output_to_pipe) {
3797 fflush(global_ld.pdh);
3801 /* Only update once every 500ms so as not to overload slow displays.
3802 * This also prevents too much context-switching between the dumpcap
3803 * and wireshark processes.
3805 #define DUMPCAP_UPD_TIME 500
3808 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3809 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3811 gettimeofday(&cur_time, NULL);
3812 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3813 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3816 upd_time = cur_time;
3819 if (pcap_stats(pch, stats) >= 0) {
3820 *stats_known = TRUE;
3823 /* Let the parent process know. */
3824 if (global_ld.inpkts_to_sync_pipe) {
3826 fflush(global_ld.pdh);
3828 /* Send our parent a message saying we've written out
3829 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3831 report_packet_count(global_ld.inpkts_to_sync_pipe);
3833 global_ld.inpkts_to_sync_pipe = 0;
3836 /* check capture duration condition */
3837 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3838 /* The maximum capture time has elapsed; stop the capture. */
3839 global_ld.go = FALSE;
3843 /* check capture file duration condition */
3844 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3845 /* duration limit reached, do we have another file? */
3846 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3847 cnd_autostop_size, cnd_file_duration))
3849 } /* cnd_file_duration */
3853 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3855 pcap_queue_element *queue_element;
3857 for (i = 0; i < global_ld.pcaps->len; i++) {
3858 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3859 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3860 pcap_opts->interface_id);
3861 g_thread_join(pcap_opts->tid);
3862 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3863 pcap_opts->interface_id);
3866 g_async_queue_lock(pcap_queue);
3867 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3868 if (queue_element) {
3869 pcap_queue_bytes -= queue_element->phdr.caplen;
3870 pcap_queue_packets -= 1;
3872 g_async_queue_unlock(pcap_queue);
3873 if (queue_element == NULL) {
3876 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3877 "Dequeued a packet of length %d captured on interface %d.",
3878 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3879 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3880 &queue_element->phdr,
3882 g_free(queue_element->pd);
3883 g_free(queue_element);
3884 global_ld.inpkts_to_sync_pipe += 1;
3885 if (capture_opts->output_to_pipe) {
3886 fflush(global_ld.pdh);
3892 /* delete stop conditions */
3893 if (cnd_file_duration != NULL)
3894 cnd_delete(cnd_file_duration);
3895 if (cnd_autostop_files != NULL)
3896 cnd_delete(cnd_autostop_files);
3897 if (cnd_autostop_size != NULL)
3898 cnd_delete(cnd_autostop_size);
3899 if (cnd_autostop_duration != NULL)
3900 cnd_delete(cnd_autostop_duration);
3902 /* did we have a pcap (input) error? */
3903 for (i = 0; i < capture_opts->ifaces->len; i++) {
3904 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3905 if (pcap_opts->pcap_err) {
3906 /* On Linux, if an interface goes down while you're capturing on it,
3907 you'll get a "recvfrom: Network is down" or
3908 "The interface went down" error (ENETDOWN).
3909 (At least you will if g_strerror() doesn't show a local translation
3912 On FreeBSD and OS X, if a network adapter disappears while
3913 you're capturing on it, you'll get a "read: Device not configured"
3914 error (ENXIO). (See previous parenthetical note.)
3916 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3918 These should *not* be reported to the Wireshark developers. */
3921 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3922 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3923 strcmp(cap_err_str, "The interface went down") == 0 ||
3924 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3925 strcmp(cap_err_str, "read: I/O error") == 0 ||
3926 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3927 report_capture_error("The network adapter on which the capture was being done "
3928 "is no longer running; the capture has stopped.",
3931 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3933 report_capture_error(errmsg, please_report);
3936 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3937 report_capture_error(errmsg, "");
3941 /* did we have an output error while capturing? */
3942 if (global_ld.err == 0) {
3945 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3946 global_ld.err, FALSE);
3947 report_capture_error(errmsg, please_report);
3951 if (capture_opts->saving_to_file) {
3952 /* close the output file */
3953 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3957 /* there might be packets not yet notified to the parent */
3958 /* (do this after closing the file, so all packets are already flushed) */
3959 if (global_ld.inpkts_to_sync_pipe) {
3961 report_packet_count(global_ld.inpkts_to_sync_pipe);
3962 global_ld.inpkts_to_sync_pipe = 0;
3965 /* If we've displayed a message about a write error, there's no point
3966 in displaying another message about an error on close. */
3967 if (!close_ok && write_ok) {
3968 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3970 report_capture_error(errmsg, "");
3974 * XXX We exhibit different behaviour between normal mode and sync mode
3975 * when the pipe is stdin and not already at EOF. If we're a child, the
3976 * parent's stdin isn't closed, so if the user starts another capture,
3977 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3978 * will say "Unrecognized libpcap format". On the other hand, in normal
3979 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3982 report_capture_count(TRUE);
3984 /* get packet drop statistics from pcap */
3985 for (i = 0; i < capture_opts->ifaces->len; i++) {
3987 guint32 pcap_dropped = 0;
3989 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3990 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3991 received = pcap_opts->received;
3992 if (pcap_opts->pcap_h != NULL) {
3993 g_assert(!pcap_opts->from_cap_pipe);
3994 /* Get the capture statistics, so we know how many packets were dropped. */
3996 * Older versions of libpcap didn't set ps_ifdrop on some
3997 * platforms; initialize it to 0 to handle that.
3999 stats->ps_ifdrop = 0;
4000 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
4001 *stats_known = TRUE;
4002 /* Let the parent process know. */
4003 pcap_dropped += stats->ps_drop;
4005 g_snprintf(errmsg, sizeof(errmsg),
4006 "Can't get packet-drop statistics: %s",
4007 pcap_geterr(pcap_opts->pcap_h));
4008 report_capture_error(errmsg, please_report);
4011 report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
4014 /* close the input file (pcap or capture pipe) */
4015 capture_loop_close_input(&global_ld);
4017 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
4019 /* ok, if the write and the close were successful. */
4020 return write_ok && close_ok;
4023 if (capture_opts->multi_files_on) {
4024 /* cleanup ringbuffer */
4025 ringbuf_error_cleanup();
4027 /* We can't use the save file, and we have no FILE * for the stream
4028 to close in order to close it, so close the FD directly. */
4029 if (global_ld.save_file_fd != -1) {
4030 ws_close(global_ld.save_file_fd);
4033 /* We couldn't even start the capture, so get rid of the capture
4035 if (capture_opts->save_file != NULL) {
4036 ws_unlink(capture_opts->save_file);
4037 g_free(capture_opts->save_file);
4040 capture_opts->save_file = NULL;
4042 report_cfilter_error(capture_opts, error_index, errmsg);
4044 report_capture_error(errmsg, secondary_errmsg);
4046 /* close the input file (pcap or cap_pipe) */
4047 capture_loop_close_input(&global_ld);
4049 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
4056 capture_loop_stop(void)
4058 #ifdef HAVE_PCAP_BREAKLOOP
4060 pcap_options *pcap_opts;
4062 for (i = 0; i < global_ld.pcaps->len; i++) {
4063 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
4064 if (pcap_opts->pcap_h != NULL)
4065 pcap_breakloop(pcap_opts->pcap_h);
4068 global_ld.go = FALSE;
4073 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
4074 int err, gboolean is_close)
4079 g_snprintf(errmsg, errmsglen,
4080 "Not all the packets could be written to the file"
4081 " to which the capture was being saved\n"
4082 "(\"%s\") because there is no space left on the file system\n"
4083 "on which that file resides.",
4089 g_snprintf(errmsg, errmsglen,
4090 "Not all the packets could be written to the file"
4091 " to which the capture was being saved\n"
4092 "(\"%s\") because you are too close to, or over,"
4093 " your disk quota\n"
4094 "on the file system on which that file resides.",
4101 g_snprintf(errmsg, errmsglen,
4102 "The file to which the capture was being saved\n"
4103 "(\"%s\") could not be closed: %s.",
4104 fname, g_strerror(err));
4106 g_snprintf(errmsg, errmsglen,
4107 "An error occurred while writing to the file"
4108 " to which the capture was being saved\n"
4110 fname, g_strerror(err));
4117 /* one packet was captured, process it */
4119 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4122 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4124 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
4126 /* We may be called multiple times from pcap_dispatch(); if we've set
4127 the "stop capturing" flag, ignore this packet, as we're not
4128 supposed to be saving any more packets. */
4129 if (!global_ld.go) {
4130 pcap_opts->flushed++;
4134 if (global_ld.pdh) {
4135 gboolean successful;
4137 /* We're supposed to write the packet to a file; do so.
4138 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4139 "ld->err" to the error. */
4140 if (global_capture_opts.use_pcapng) {
4141 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4143 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4144 phdr->caplen, phdr->len,
4145 pcap_opts->interface_id,
4148 &global_ld.bytes_written, &err);
4150 successful = libpcap_write_packet(global_ld.pdh,
4151 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4152 phdr->caplen, phdr->len,
4154 &global_ld.bytes_written, &err);
4157 global_ld.go = FALSE;
4158 global_ld.err = err;
4159 pcap_opts->dropped++;
4161 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4162 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4163 "Wrote a packet of length %d captured on interface %u.",
4164 phdr->caplen, pcap_opts->interface_id);
4166 global_ld.packet_count++;
4167 pcap_opts->received++;
4168 /* if the user told us to stop after x packets, do we already have enough? */
4169 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4170 global_ld.go = FALSE;
4176 /* one packet was captured, queue it */
4178 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4181 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4182 pcap_queue_element *queue_element;
4183 gboolean limit_reached;
4185 /* We may be called multiple times from pcap_dispatch(); if we've set
4186 the "stop capturing" flag, ignore this packet, as we're not
4187 supposed to be saving any more packets. */
4188 if (!global_ld.go) {
4189 pcap_opts->flushed++;
4193 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4194 if (queue_element == NULL) {
4195 pcap_opts->dropped++;
4198 queue_element->pcap_opts = pcap_opts;
4199 queue_element->phdr = *phdr;
4200 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4201 if (queue_element->pd == NULL) {
4202 pcap_opts->dropped++;
4203 g_free(queue_element);
4206 memcpy(queue_element->pd, pd, phdr->caplen);
4207 g_async_queue_lock(pcap_queue);
4208 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4209 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4210 limit_reached = FALSE;
4211 g_async_queue_push_unlocked(pcap_queue, queue_element);
4212 pcap_queue_bytes += phdr->caplen;
4213 pcap_queue_packets += 1;
4215 limit_reached = TRUE;
4217 g_async_queue_unlock(pcap_queue);
4218 if (limit_reached) {
4219 pcap_opts->dropped++;
4220 g_free(queue_element->pd);
4221 g_free(queue_element);
4222 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4223 "Dropped a packet of length %d captured on interface %u.",
4224 phdr->caplen, pcap_opts->interface_id);
4226 pcap_opts->received++;
4227 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4228 "Queued a packet of length %d captured on interface %u.",
4229 phdr->caplen, pcap_opts->interface_id);
4231 /* I don't want to hold the mutex over the debug output. So the
4232 output may be wrong */
4233 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4234 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4235 pcap_queue_bytes, pcap_queue_packets);
4239 set_80211_channel(const char *iface, const char *opt)
4241 int freq = 0, type, ret;
4242 gchar **options = NULL;
4244 options = g_strsplit_set(opt, ",", 2);
4247 freq = atoi(options[0]);
4250 type = ws80211_str_to_chan_type(options[1]);
4259 ret = ws80211_init();
4261 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4265 ret = ws80211_set_freq(iface, freq, type);
4268 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4274 pipe_write_block(2, SP_SUCCESS, NULL);
4278 g_strfreev(options);
4283 get_dumpcap_compiled_info(GString *str)
4285 /* Capture libraries */
4286 g_string_append(str, ", ");
4287 get_compiled_caplibs_version(str);
4290 g_string_append(str, ", ");
4292 g_string_append(str, "with libz ");
4294 g_string_append(str, ZLIB_VERSION);
4295 #else /* ZLIB_VERSION */
4296 g_string_append(str, "(version unknown)");
4297 #endif /* ZLIB_VERSION */
4298 #else /* HAVE_LIBZ */
4299 g_string_append(str, "without libz");
4300 #endif /* HAVE_LIBZ */
4304 get_dumpcap_runtime_info(GString *str)
4306 /* Capture libraries */
4307 g_string_append(str, ", ");
4308 get_runtime_caplibs_version(str);
4311 #if defined(HAVE_LIBZ) && !defined(_WIN32)
4312 g_string_append_printf(str, ", with libz %s", zlibVersion());
4316 /* And now our feature presentation... [ fade to music ] */
4318 main(int argc, char *argv[])
4320 GString *comp_info_str;
4321 GString *runtime_info_str;
4324 static const struct option long_options[] = {
4325 {(char *)"help", no_argument, NULL, 'h'},
4326 {(char *)"version", no_argument, NULL, 'v'},
4327 LONGOPT_CAPTURE_COMMON
4332 gboolean arg_error = FALSE;
4337 struct sigaction action, oldaction;
4340 gboolean start_capture = TRUE;
4341 gboolean stats_known;
4342 struct pcap_stat stats;
4343 GLogLevelFlags log_flags;
4344 gboolean list_interfaces = FALSE;
4345 gboolean list_link_layer_types = FALSE;
4346 #ifdef HAVE_BPF_IMAGE
4347 gboolean print_bpf_code = FALSE;
4349 gboolean set_chan = FALSE;
4350 gchar *set_chan_arg = NULL;
4351 gboolean machine_readable = FALSE;
4352 gboolean print_statistics = FALSE;
4353 int status, run_once_args = 0;
4356 #if defined(__APPLE__) && defined(__LP64__)
4357 struct utsname osinfo;
4361 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
4363 /* Get the compile-time version information string */
4364 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4366 /* Get the run-time version information string */
4367 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4369 /* Add it to the information to be reported on a crash. */
4370 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
4375 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
4378 arg_list_utf_16to8(argc, argv);
4379 create_app_running_mutex();
4382 * Initialize our DLL search path. MUST be called before LoadLibrary
4385 ws_init_dll_search_path();
4388 #ifdef HAVE_BPF_IMAGE
4389 #define OPTSTRING_d "d"
4391 #define OPTSTRING_d ""
4394 #ifdef HAVE_PCAP_REMOTE
4395 #define OPTSTRING_r "r"
4396 #define OPTSTRING_u "u"
4398 #define OPTSTRING_r ""
4399 #define OPTSTRING_u ""
4402 #ifdef HAVE_PCAP_SETSAMPLING
4403 #define OPTSTRING_m "m:"
4405 #define OPTSTRING_m ""
4408 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
4410 #ifdef DEBUG_CHILD_DUMPCAP
4411 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4412 fprintf (stderr, "Unable to open debug log file .\n");
4417 #if defined(__APPLE__) && defined(__LP64__)
4419 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4420 * a bug workaround - timeouts less than 1 second don't work with libpcap
4421 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4422 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4423 * The problem is extremely unlikely to be reintroduced in a future
4426 if (uname(&osinfo) == 0) {
4428 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
4429 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4430 * number of 10.0.0, not 10.1.0 - go figure).
4432 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4433 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4434 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4435 need_timeout_workaround = TRUE;
4440 * Determine if dumpcap is being requested to run in a special
4441 * capture_child mode by going thru the command line args to see if
4442 * a -Z is present. (-Z is a hidden option).
4444 * The primary result of running in capture_child mode is that
4445 * all messages sent out on stderr are in a special type/len/string
4446 * format to allow message processing by type. These messages include
4447 * error messages if dumpcap fails to start the operation it was
4448 * requested to do, as well as various "status" messages which are sent
4449 * when an actual capture is in progress, and a "success" message sent
4450 * if dumpcap was requested to perform an operation other than a
4453 * Capture_child mode would normally be requested by a parent process
4454 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4455 * to which dumpcap stderr has been redirected. It might also have
4456 * another pipe to obtain dumpcap stdout output; for operations other
4457 * than a capture, that information is formatted specially for easier
4458 * parsing by the parent process.
4460 * Capture_child mode needs to be determined immediately upon
4461 * startup so that any messages generated by dumpcap in this mode
4462 * (eg: during initialization) will be formatted properly.
4465 for (i=1; i<argc; i++) {
4466 if (strcmp("-Z", argv[i]) == 0) {
4467 capture_child = TRUE;
4468 machine_readable = TRUE; /* request machine-readable output */
4470 /* set output pipe to binary mode, to avoid ugly text conversions */
4471 _setmode(2, O_BINARY);
4476 /* The default_log_handler will use stdout, which makes trouble in */
4477 /* capture child mode, as it uses stdout for its sync_pipe. */
4478 /* So: the filtering is done in the console_log_handler and not here.*/
4479 /* We set the log handlers right up front to make sure that any log */
4480 /* messages when running as child will be sent back to the parent */
4481 /* with the correct format. */
4486 G_LOG_LEVEL_CRITICAL|
4487 G_LOG_LEVEL_WARNING|
4488 G_LOG_LEVEL_MESSAGE|
4492 G_LOG_FLAG_RECURSION);
4494 g_log_set_handler(NULL,
4496 console_log_handler, NULL /* user_data */);
4497 g_log_set_handler(LOG_DOMAIN_MAIN,
4499 console_log_handler, NULL /* user_data */);
4500 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4502 console_log_handler, NULL /* user_data */);
4503 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4505 console_log_handler, NULL /* user_data */);
4507 /* Initialize the pcaps list */
4508 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
4510 #if !GLIB_CHECK_VERSION(2,31,0)
4511 /* Initialize the thread system */
4512 g_thread_init(NULL);
4516 /* Load wpcap if possible. Do this before collecting the run-time version information */
4519 /* ... and also load the packet.dll from wpcap */
4520 /* XXX - currently not required, may change later. */
4521 /*wpcap_packet_load();*/
4523 /* Start windows sockets */
4524 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4526 /* Set handler for Ctrl+C key */
4527 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4529 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4530 and exit. Do the same with SIGPIPE, in case, for example,
4531 we're writing to our standard output and it's a pipe.
4532 Do the same with SIGHUP if it's not being ignored (if we're
4533 being run under nohup, it might be ignored, in which case we
4534 should leave it ignored).
4536 XXX - apparently, Coverity complained that part of action
4537 wasn't initialized. Perhaps it's running on Linux, where
4538 struct sigaction has an ignored "sa_restorer" element and
4539 where "sa_handler" and "sa_sigaction" might not be two
4540 members of a union. */
4541 memset(&action, 0, sizeof(action));
4542 action.sa_handler = capture_cleanup_handler;
4544 * Arrange that system calls not get restarted, because when
4545 * our signal handler returns we don't want to restart
4546 * a call that was waiting for packets to arrive.
4548 action.sa_flags = 0;
4549 sigemptyset(&action.sa_mask);
4550 sigaction(SIGTERM, &action, NULL);
4551 sigaction(SIGINT, &action, NULL);
4552 sigaction(SIGPIPE, &action, NULL);
4553 sigaction(SIGHUP, NULL, &oldaction);
4554 if (oldaction.sa_handler == SIG_DFL)
4555 sigaction(SIGHUP, &action, NULL);
4558 /* Catch SIGINFO and, if we get it and we're capturing in
4559 quiet mode, report the number of packets we've captured. */
4560 action.sa_handler = report_counts_siginfo;
4561 action.sa_flags = SA_RESTART;
4562 sigemptyset(&action.sa_mask);
4563 sigaction(SIGINFO, &action, NULL);
4564 #endif /* SIGINFO */
4568 enable_kernel_bpf_jit_compiler();
4571 /* ----------------------------------------------------------------- */
4572 /* Privilege and capability handling */
4574 /* 1. Running not as root or suid root; no special capabilities. */
4577 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4580 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4582 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4583 /* capabilities; Drop all other capabilities; */
4584 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4585 /* else: after pcap_open_live() in capture_loop_open_input() */
4586 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4587 /* (Note: this means that the process, although logged in */
4588 /* as root, does not have various permissions such as the */
4589 /* ability to bypass file access permissions). */
4590 /* XXX: Should we just leave capabilities alone in this case */
4591 /* so that user gets expected effect that root can do */
4594 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4596 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4597 /* else: after pcap_open_live() in capture_loop_open_input() */
4598 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4599 /* pcap_open_live). */
4601 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4603 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4604 /* capabilities; Drop all other capabilities; */
4605 /* Drop suid privileges (euid=ruid); */
4606 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4607 /* else: after pcap_open_live() in capture_loop_open_input() */
4608 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4610 /* XXX: For some Linux versions/distros with capabilities */
4611 /* a 'normal' process with any capabilities cannot be */
4612 /* 'killed' (signaled) from another (same uid) non-privileged */
4614 /* For example: If (non-suid) Wireshark forks a */
4615 /* child suid dumpcap which acts as described here (case 5), */
4616 /* Wireshark will be unable to kill (signal) the child */
4617 /* dumpcap process until the capabilities have been dropped */
4618 /* (after pcap_open_live()). */
4619 /* This behaviour will apparently be changed in the kernel */
4620 /* to allow the kill (signal) in this case. */
4621 /* See the following for details: */
4622 /* https://www.mail-archive.com/ [wrapped] */
4623 /* linux-security-module@vger.kernel.org/msg02913.html */
4625 /* It is therefore conceivable that if dumpcap somehow hangs */
4626 /* in pcap_open_live or before that wireshark will not */
4627 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4628 /* In this case, exiting wireshark will kill the child */
4629 /* dumpcap process. */
4631 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4632 /* capabilities; Using libcap. Note: capset cmd (which see) */
4633 /* used to assign capabilities to file. */
4635 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4636 /* else: after pcap_open_live() in capture_loop_open_input() */
4637 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4639 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4640 /* longer required (similar to capture). */
4642 /* ----------------------------------------------------------------- */
4644 init_process_policies();
4647 /* If 'started with special privileges' (and using libcap) */
4648 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4649 /* Set euid/egid = ruid/rgid to remove suid privileges */
4650 relinquish_privs_except_capture();
4653 /* Set the initial values in the capture options. This might be overwritten
4654 by the command line parameters. */
4655 capture_opts_init(&global_capture_opts);
4656 /* We always save to a file - if no file was specified, we save to a
4658 global_capture_opts.saving_to_file = TRUE;
4659 global_capture_opts.has_ring_num_files = TRUE;
4661 /* Pass on capture_child mode for capture_opts */
4662 global_capture_opts.capture_child = capture_child;
4664 /* Now get our args */
4665 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4667 case 'h': /* Print help and exit */
4668 printf("Dumpcap (Wireshark) %s\n"
4669 "Capture network packets and dump them into a pcapng or pcap file.\n"
4670 "See https://www.wireshark.org for more information.\n",
4671 get_ws_vcs_version_info());
4672 print_usage(stdout);
4675 case 'v': /* Show version and exit */
4677 show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4678 g_string_free(comp_info_str, TRUE);
4679 g_string_free(runtime_info_str, TRUE);
4683 /*** capture option specific ***/
4684 case 'a': /* autostop criteria */
4685 case 'b': /* Ringbuffer option */
4686 case 'c': /* Capture x packets */
4687 case 'f': /* capture filter */
4688 case 'g': /* enable group read access on file(s) */
4689 case 'i': /* Use interface x */
4690 case 'n': /* Use pcapng format */
4691 case 'p': /* Don't capture in promiscuous mode */
4692 case 'P': /* Use pcap format */
4693 case 's': /* Set the snapshot (capture) length */
4694 case 'w': /* Write to capture file x */
4695 case 'y': /* Set the pcap data link type */
4696 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4697 #ifdef HAVE_PCAP_REMOTE
4698 case 'u': /* Use UDP for data transfer */
4699 case 'r': /* Capture own RPCAP traffic too */
4700 case 'A': /* Authentication */
4702 #ifdef HAVE_PCAP_SETSAMPLING
4703 case 'm': /* Sampling */
4705 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4706 case 'B': /* Buffer size */
4708 #ifdef HAVE_PCAP_CREATE
4709 case 'I': /* Monitor mode */
4711 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4716 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4718 capture_child = TRUE;
4720 /* set output pipe to binary mode, to avoid ugly text conversions */
4721 _setmode(2, O_BINARY);
4723 * optarg = the control ID, aka the PPID, currently used for the
4726 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4727 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4728 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4729 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4731 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4732 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4733 "Signal pipe: Unable to open %s. Dead parent?",
4741 case 'q': /* Quiet */
4747 /*** all non capture option specific ***/
4748 case 'D': /* Print a list of capture devices and exit */
4749 if (!list_interfaces) {
4750 list_interfaces = TRUE;
4754 case 'L': /* Print list of link-layer types and exit */
4755 if (!list_link_layer_types) {
4756 list_link_layer_types = TRUE;
4760 #ifdef HAVE_BPF_IMAGE
4761 case 'd': /* Print BPF code for capture filter and exit */
4762 if (!print_bpf_code) {
4763 print_bpf_code = TRUE;
4768 case 'S': /* Print interface statistics once a second */
4769 if (!print_statistics) {
4770 print_statistics = TRUE;
4774 case 'k': /* Set wireless channel */
4777 set_chan_arg = optarg;
4780 cmdarg_err("Only one -k flag may be specified");
4784 case 'M': /* For -D, -L, and -S, print machine-readable output */
4785 machine_readable = TRUE;
4788 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4791 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4794 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4796 case '?': /* Bad flag - print usage message */
4805 /* user specified file name as regular command-line argument */
4806 /* XXX - use it as the capture file name (or something else)? */
4812 * Extra command line arguments were specified; complain.
4813 * XXX - interpret as capture filter, as tcpdump and tshark do?
4815 cmdarg_err("Invalid argument: %s", argv[0]);
4820 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4823 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4824 /* Use some default if the user hasn't specified some */
4825 /* XXX: Are these defaults good enough? */
4826 pcap_queue_byte_limit = 1000 * 1000;
4827 pcap_queue_packet_limit = 1000;
4830 print_usage(stderr);
4834 if (run_once_args > 1) {
4835 #ifdef HAVE_BPF_IMAGE
4836 cmdarg_err("Only one of -D, -L, -d, -k, or -S may be supplied.");
4838 cmdarg_err("Only one of -D, -L, -k, or -S may be supplied.");
4841 } else if (run_once_args == 1) {
4842 /* We're supposed to print some information, rather than
4843 to capture traffic; did they specify a ring buffer option? */
4844 if (global_capture_opts.multi_files_on) {
4845 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4849 /* We're supposed to capture traffic; */
4851 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4852 if (global_capture_opts.ifaces->len > 1) {
4854 global_capture_opts.use_pcapng = TRUE;
4857 if (global_capture_opts.capture_comment &&
4858 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4859 /* XXX - for ringbuffer, should we apply the comment to each file? */
4860 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4864 /* Was the ring buffer option specified and, if so, does it make sense? */
4865 if (global_capture_opts.multi_files_on) {
4866 /* Ring buffer works only under certain conditions:
4867 a) ring buffer does not work with temporary files;
4868 b) it makes no sense to enable the ring buffer if the maximum
4869 file size is set to "infinite". */
4870 if (global_capture_opts.save_file == NULL) {
4871 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4872 global_capture_opts.multi_files_on = FALSE;
4874 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4875 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4877 /* XXX - this must be redesigned as the conditions changed */
4878 global_capture_opts.multi_files_on = FALSE;
4885 * "-D" requires no interface to be selected; it's supposed to list
4888 if (list_interfaces) {
4889 /* Get the list of interfaces */
4894 if_list = capture_interface_list(&err, &err_str,NULL);
4895 if (if_list == NULL) {
4898 * If we're being run by another program, just give them
4899 * an empty list of interfaces, don't report this as
4900 * an error; that lets them decide whether to report
4901 * this as an error or not.
4903 if (!machine_readable) {
4904 cmdarg_err("There are no interfaces on which a capture can be done");
4908 cmdarg_err("%s", err_str);
4914 if (machine_readable) /* tab-separated values to stdout */
4915 print_machine_readable_interfaces(if_list);
4917 capture_opts_print_interfaces(if_list);
4918 free_interface_list(if_list);
4923 * "-S" requires no interface to be selected; it gives statistics
4924 * for all interfaces.
4926 if (print_statistics) {
4927 status = print_statistics_loop(machine_readable);
4932 interface_options interface_opts;
4934 if (global_capture_opts.ifaces->len != 1) {
4935 cmdarg_err("Need one interface");
4939 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4940 status = set_80211_channel(interface_opts.name, set_chan_arg);
4945 * "-L", "-d", and capturing act on a particular interface, so we have to
4946 * have an interface; if none was specified, pick a default.
4948 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4950 /* cmdarg_err() already called .... */
4954 if (list_link_layer_types) {
4955 /* Get the list of link-layer types for the capture device. */
4956 if_capabilities_t *caps;
4960 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4961 interface_options interface_opts;
4963 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4965 caps = get_if_capabilities(interface_opts.name,
4966 interface_opts.monitor_mode, &err_str);
4968 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4969 "Please check to make sure you have sufficient permissions, and that\n"
4970 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4974 if (caps->data_link_types == NULL) {
4975 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4978 if (machine_readable) /* tab-separated values to stdout */
4979 /* XXX: We need to change the format and adopt consumers */
4980 print_machine_readable_if_capabilities(caps);
4982 /* XXX: We might want to print also the interface name */
4983 capture_opts_print_if_capabilities(caps, interface_opts.name,
4984 interface_opts.monitor_mode);
4985 free_if_capabilities(caps);
4990 /* We're supposed to do a capture, or print the BPF code for a filter. */
4992 /* Let the user know what interfaces were chosen. */
4993 if (capture_child) {
4994 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4995 interface_options interface_opts;
4997 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4998 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4999 interface_opts.name);
5002 str = g_string_new("");
5004 if (global_capture_opts.ifaces->len < 2)
5006 if (global_capture_opts.ifaces->len < 4)
5009 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5010 interface_options interface_opts;
5012 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
5014 if (global_capture_opts.ifaces->len > 2) {
5015 g_string_append_printf(str, ",");
5017 g_string_append_printf(str, " ");
5018 if (j == global_capture_opts.ifaces->len - 1) {
5019 g_string_append_printf(str, "and ");
5022 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
5025 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
5027 fprintf(stderr, "Capturing on %s\n", str->str);
5028 g_string_free(str, TRUE);
5031 /* Process the snapshot length, as that affects the generated BPF code. */
5032 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
5034 #ifdef HAVE_BPF_IMAGE
5035 if (print_bpf_code) {
5036 show_filter_code(&global_capture_opts);
5041 /* We're supposed to do a capture. Process the ring buffer arguments. */
5042 capture_opts_trim_ring_num_files(&global_capture_opts);
5044 /* flush stderr prior to starting the main capture loop */
5047 /* Now start the capture. */
5048 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
5052 /* capture failed */
5055 return 0; /* never here, make compiler happy */
5060 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
5061 const char *message, gpointer user_data _U_)
5068 /* ignore log message, if log_level isn't interesting */
5069 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5070 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
5075 /* create a "timestamp" */
5077 today = localtime(&curr);
5079 switch(log_level & G_LOG_LEVEL_MASK) {
5080 case G_LOG_LEVEL_ERROR:
5083 case G_LOG_LEVEL_CRITICAL:
5086 case G_LOG_LEVEL_WARNING:
5089 case G_LOG_LEVEL_MESSAGE:
5092 case G_LOG_LEVEL_INFO:
5095 case G_LOG_LEVEL_DEBUG:
5099 fprintf(stderr, "unknown log_level %d\n", log_level);
5101 g_assert_not_reached();
5104 /* Generate the output message */
5105 if (log_level & G_LOG_LEVEL_MESSAGE) {
5106 /* normal user messages without additional infos */
5107 msg = g_strdup_printf("%s\n", message);
5109 /* info/debug messages with additional infos */
5110 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
5111 today->tm_hour, today->tm_min, today->tm_sec,
5112 log_domain != NULL ? log_domain : "",
5116 /* DEBUG & INFO msgs (if we're debugging today) */
5117 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
5118 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5119 #ifdef DEBUG_DUMPCAP
5120 fprintf(stderr, "%s", msg);
5123 #ifdef DEBUG_CHILD_DUMPCAP
5124 fprintf(debug_log, "%s", msg);
5132 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
5133 /* to parent especially formatted if dumpcap running as child. */
5134 if (capture_child) {
5135 sync_pipe_errmsg_to_parent(2, msg, "");
5137 fprintf(stderr, "%s", msg);
5144 /****************************************************************************************************************/
5145 /* indication report routines */
5149 report_packet_count(unsigned int packet_count)
5151 char tmp[SP_DECISIZE+1+1];
5152 static unsigned int count = 0;
5154 if (capture_child) {
5155 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
5156 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
5157 pipe_write_block(2, SP_PACKET_COUNT, tmp);
5159 count += packet_count;
5160 fprintf(stderr, "\rPackets: %u ", count);
5161 /* stderr could be line buffered */
5167 report_new_capture_file(const char *filename)
5169 if (capture_child) {
5170 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
5171 pipe_write_block(2, SP_FILE, filename);
5175 * Prevent a SIGINFO handler from writing to the standard error
5176 * while we're doing so; instead, have it just set a flag telling
5177 * us to print that information when we're done.
5180 #endif /* SIGINFO */
5181 fprintf(stderr, "File: %s\n", filename);
5182 /* stderr could be line buffered */
5187 * Allow SIGINFO handlers to write.
5192 * If a SIGINFO handler asked us to write out capture counts, do so.
5195 report_counts_for_siginfo();
5196 #endif /* SIGINFO */
5201 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5203 interface_options interface_opts;
5204 char tmp[MSG_MAX_LENGTH+1+6];
5206 if (i < capture_opts->ifaces->len) {
5207 if (capture_child) {
5208 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5209 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5210 pipe_write_block(2, SP_BAD_FILTER, tmp);
5213 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5214 * the error message below.
5216 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
5218 "Invalid capture filter \"%s\" for interface '%s'.\n"
5220 "That string isn't a valid capture filter (%s).\n"
5221 "See the User's Guide for a description of the capture filter syntax.",
5222 interface_opts.cfilter, interface_opts.name, errmsg);
5228 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5230 if (capture_child) {
5231 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5232 "Primary Error: %s", error_msg);
5233 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5234 "Secondary Error: %s", secondary_error_msg);
5235 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5237 cmdarg_err("%s", error_msg);
5238 if (secondary_error_msg[0] != '\0')
5239 cmdarg_err_cont("%s", secondary_error_msg);
5244 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
5246 char tmp[SP_DECISIZE+1+1];
5247 guint32 total_drops = pcap_drops + drops + flushed;
5249 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5251 if (capture_child) {
5252 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5253 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5254 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
5255 /* XXX: Need to provide interface id, changes to consumers required. */
5256 pipe_write_block(2, SP_DROPS, tmp);
5259 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5260 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
5261 received ? 100.0 * received / (received + total_drops) : 0.0);
5262 /* stderr could be line buffered */
5268 /************************************************************************************************/
5269 /* signal_pipe handling */
5274 signal_pipe_check_running(void)
5276 /* any news from our parent? -> just stop the capture */
5280 /* if we are running standalone, no check required */
5281 if (!capture_child) {
5285 if (!sig_pipe_name || !sig_pipe_handle) {
5286 /* This shouldn't happen */
5287 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5288 "Signal pipe: No name or handle");
5293 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5294 * at this point. Should we check to see if the parent is still alive,
5295 * e.g. by using OpenProcess?
5298 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5300 if (!result || avail > 0) {
5301 /* peek failed or some bytes really available */
5302 /* (if not piping from stdin this would fail) */
5303 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5304 "Signal pipe: Stop capture: %s", sig_pipe_name);
5305 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5306 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
5307 sig_pipe_handle, result, avail);
5310 /* pipe ok and no bytes available */
5321 * Editor modelines - https://www.wireshark.org/tools/modelines.html
5326 * indent-tabs-mode: nil
5329 * vi: set shiftwidth=4 tabstop=8 expandtab:
5330 * :indentSize=4:tabSize=8:noTabs=true: