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>
70 #include <zlib.h> /* to get the libz version number */
73 #include <wsutil/cmdarg_err.h>
74 #include <wsutil/crash_info.h>
75 #include <wsutil/ws_diag_control.h>
76 #include <wsutil/ws_version_info.h>
78 #ifndef HAVE_GETOPT_LONG
79 #include "wsutil/wsgetopt.h"
87 # include <sys/prctl.h>
88 # include <sys/capability.h>
91 #include "ringbuffer.h"
93 #include "caputils/capture_ifinfo.h"
94 #include "caputils/capture-pcap-util.h"
95 #include "caputils/capture-pcap-util-int.h"
97 #include "caputils/capture-wpcap.h"
103 #include <wsutil/unicode-utils.h>
110 #ifdef NEED_INET_V6DEFS_H
111 # include "wsutil/inet_v6defs.h"
114 #include <wsutil/clopts_common.h>
115 #include <wsutil/privileges.h>
117 #include "sync_pipe.h"
119 #include "capture_opts.h"
120 #include <capchild/capture_session.h>
121 #include <capchild/capture_sync.h>
123 #include "conditions.h"
124 #include "capture_stop_conditions.h"
126 #include "wsutil/tempfile.h"
128 #include "wsutil/file_util.h"
129 #include "wsutil/os_version_info.h"
131 #include "caputils/ws80211_utils.h"
134 * Get information about libpcap format from "wiretap/libpcap.h".
135 * XXX - can we just use pcap_open_offline() to read the pipe?
137 #include "wiretap/libpcap.h"
139 /**#define DEBUG_DUMPCAP**/
140 /**#define DEBUG_CHILD_DUMPCAP**/
144 #include <conio.h> /* _getch() */
148 #ifdef DEBUG_CHILD_DUMPCAP
149 FILE *debug_log; /* for logging debug messages to */
150 /* a file if DEBUG_CHILD_DUMPCAP */
154 static GAsyncQueue *pcap_queue;
155 static gint64 pcap_queue_bytes;
156 static gint64 pcap_queue_packets;
157 static gint64 pcap_queue_byte_limit = 0;
158 static gint64 pcap_queue_packet_limit = 0;
160 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
162 static gchar *sig_pipe_name = NULL;
163 static HANDLE sig_pipe_handle = NULL;
164 static gboolean signal_pipe_check_running(void);
168 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
169 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
172 /** Stop a low-level capture (stops the capture child). */
173 static void capture_loop_stop(void);
174 /** Close a pipe, or socket if \a from_socket is TRUE */
175 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
179 * Enable kernel BPF JIT compiler if available.
180 * If any calls fail, just drive on - the JIT compiler might not be
181 * enabled, but filtering will still work, and it's not clear what
182 * we could do if the calls fail; should we just report the error
183 * and not continue to capture, should we report it as a warning, or
187 enable_kernel_bpf_jit_compiler(void)
191 static const char file[] = "/proc/sys/net/core/bpf_jit_enable";
193 fd = ws_open(file, O_WRONLY);
197 written = write(fd, "1", strlen("1"));
203 #if !defined (__linux__)
204 #ifndef HAVE_PCAP_BREAKLOOP
206 * We don't have pcap_breakloop(), which is the only way to ensure that
207 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
208 * won't, if the call to read the next packet or batch of packets is
209 * is interrupted by a signal on UN*X, just go back and try again to
212 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
213 * the signal handler, set a flag to stop capturing; however, without
214 * a guarantee of that sort, we can't guarantee that we'll stop capturing
215 * if the read will be retried and won't time out if no packets arrive.
217 * Therefore, on at least some platforms, we work around the lack of
218 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
219 * to wait for packets to arrive, so that we're probably going to be
220 * blocked in the select() when the signal arrives, and can just bail
221 * out of the loop at that point.
223 * However, we don't want to do that on BSD (because "select()" doesn't work
224 * correctly on BPF devices on at least some releases of some flavors of
225 * BSD), and we don't want to do it on Windows (because "select()" is
226 * something for sockets, not for arbitrary handles). (Note that "Windows"
227 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
228 * using WinPcap, not a UNIX libpcap.)
230 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
231 * on BSD times out even if no packets have arrived, so we'll eventually
232 * exit pcap_dispatch() with an indication that no packets have arrived,
233 * and will break out of the capture loop at that point.
235 * On Windows, we can't send a SIGINT to stop capturing, so none of this
236 * applies in any case.
238 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
239 * want to include it if it's not present on this platform, however.
241 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
242 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
244 # define MUST_DO_SELECT
245 # endif /* avoid select */
246 #endif /* HAVE_PCAP_BREAKLOOP */
248 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
249 * in pcap_dispatch(); on the other hand, select() works just fine there.
250 * Hence we use a select for that come what may.
252 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
253 * internally, and, with TPACKET_V3, once that's supported, it'll
254 * support timeouts, at least as I understand the way the code works.
256 #define MUST_DO_SELECT
259 /** init the capture filter */
262 INITFILTER_BAD_FILTER,
263 INITFILTER_OTHER_ERROR
264 } initfilter_status_t;
267 STATE_EXPECT_REC_HDR,
280 typedef struct _pcap_options {
285 #ifdef MUST_DO_SELECT
286 int pcap_fd; /**< pcap file descriptor */
293 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
294 /**< capture pipe (unix only "input file") */
295 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
296 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
297 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
298 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
300 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
302 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
303 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
304 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
306 char * cap_pipe_buf; /**< Pointer to the data buffer we read into */
307 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
308 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
310 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
311 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
313 cap_pipe_state_t cap_pipe_state;
314 cap_pipe_err_t cap_pipe_err;
317 GMutex *cap_pipe_read_mtx;
318 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
322 typedef struct _loop_data {
324 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
325 int err; /**< if non-zero, error seen while capturing */
326 gint packet_count; /**< Number of packets we have already captured */
327 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
328 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
330 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
336 guint64 bytes_written;
337 guint32 autostop_files;
340 typedef struct _pcap_queue_element {
341 pcap_options *pcap_opts;
342 struct pcap_pkthdr phdr;
344 } pcap_queue_element;
347 * Standard secondary message for unexpected errors.
349 static const char please_report[] =
350 "Please report this to the Wireshark developers.\n"
351 "https://bugs.wireshark.org/\n"
352 "(This is not a crash; please do not report it as such.)";
355 * This needs to be static, so that the SIGINT handler can clear the "go"
358 static loop_data global_ld;
362 * Timeout, in milliseconds, for reads from the stream of captured packets
363 * from a capture device.
365 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
366 * 64-bit applications, with sub-second timeouts not to work. The bug is
367 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
369 #if defined(__APPLE__) && defined(__LP64__)
370 static gboolean need_timeout_workaround;
372 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
374 #define CAP_READ_TIMEOUT 250
378 * Timeout, in microseconds, for reads from the stream of captured packets
379 * from a pipe. Pipes don't have the same problem that BPF devices do
380 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
381 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
382 * of the offending versions of Snow Leopard.
384 * On Windows this value is converted to milliseconds and passed to
385 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
386 * will return immediately.
389 #define PIPE_READ_TIMEOUT 100000
391 #define PIPE_READ_TIMEOUT 250000
394 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
397 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
398 const char *message, gpointer user_data _U_);
400 /* capture related options */
401 static capture_options global_capture_opts;
402 static gboolean quiet = FALSE;
403 static gboolean use_threads = FALSE;
404 static guint64 start_time;
406 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
408 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
410 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
411 int err, gboolean is_close);
413 static void WS_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
415 static void report_new_capture_file(const char *filename);
416 static void report_packet_count(unsigned int packet_count);
417 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
418 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
419 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
421 #define MSG_MAX_LENGTH 4096
423 /* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
425 create_timestamp(void) {
435 * Current time, represented as 100-nanosecond intervals since
436 * January 1, 1601, 00:00:00 UTC.
438 * I think DWORD might be signed, so cast both parts of "now"
439 * to guint32 so that the sign bit doesn't get treated specially.
441 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
442 * might want to use instead.
444 GetSystemTimeAsFileTime(&now);
445 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
446 (guint32)now.dwLowDateTime;
449 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
455 * Subtract difference, in microseconds, between January 1, 1601
456 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
458 timestamp -= G_GUINT64_CONSTANT(11644473600000000);
461 * Current time, represented as seconds and microseconds since
462 * January 1, 1970, 00:00:00 UTC.
464 gettimeofday(&now, NULL);
467 * Convert to delta in microseconds.
469 timestamp = (guint64)(now.tv_sec) * 1000000 +
470 (guint64)(now.tv_usec);
476 print_usage(FILE *output)
478 fprintf(output, "\nUsage: dumpcap [options] ...\n");
479 fprintf(output, "\n");
480 fprintf(output, "Capture interface:\n");
481 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
482 " or for remote capturing, use one of these formats:\n"
483 " rpcap://<host>/<interface>\n"
484 " TCP@<host>:<port>\n");
485 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
486 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
487 fprintf(output, " -p don't capture in promiscuous mode\n");
488 #ifdef HAVE_PCAP_CREATE
489 fprintf(output, " -I capture in monitor mode, if available\n");
491 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
492 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
494 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
495 fprintf(output, " -D print list of interfaces and exit\n");
496 fprintf(output, " -L print list of link-layer types of iface and exit\n");
497 #ifdef HAVE_BPF_IMAGE
498 fprintf(output, " -d print generated BPF code for capture filter\n");
500 fprintf(output, " -k set channel on wifi interface <freq>,[<type>]\n");
501 fprintf(output, " -S print statistics for each interface once per second\n");
502 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
503 fprintf(output, "\n");
504 #ifdef HAVE_PCAP_REMOTE
505 fprintf(output, "RPCAP options:\n");
506 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
507 fprintf(output, " -u use UDP for RPCAP data transfer\n");
508 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
509 #ifdef HAVE_PCAP_SETSAMPLING
510 fprintf(output, " -m <sampling type> use packet sampling\n");
511 fprintf(output, " count:NUM - capture one packet of every NUM\n");
512 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
515 fprintf(output, "Stop conditions:\n");
516 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
517 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
518 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
519 fprintf(output, " files:NUM - stop after NUM files\n");
520 /*fprintf(output, "\n");*/
521 fprintf(output, "Output (files):\n");
522 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
523 fprintf(output, " -g enable group read access on the output file(s)\n");
524 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
525 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
526 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
527 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
528 fprintf(output, " -P use libpcap format instead of pcapng\n");
529 fprintf(output, " --capture-comment <comment>\n");
530 fprintf(output, " add a capture comment to the output file\n");
531 fprintf(output, " (only for pcapng)\n");
532 fprintf(output, "\n");
533 fprintf(output, "Miscellaneous:\n");
534 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
535 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
536 fprintf(output, " within dumpcap\n");
537 fprintf(output, " -t use a separate thread per interface\n");
538 fprintf(output, " -q don't report packet capture counts\n");
539 fprintf(output, " -v print version information and exit\n");
540 fprintf(output, " -h display this help and exit\n");
541 fprintf(output, "\n");
543 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
544 fprintf(output, "You might want to reset it\n");
545 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
546 fprintf(output, "\n");
548 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
549 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
550 fprintf(output, "\n");
551 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
555 * Report an error in command-line arguments.
556 * If we're a capture child, send a message back to the parent, otherwise
560 dumpcap_cmdarg_err(const char *fmt, va_list ap)
564 /* Generate a 'special format' message back to parent */
565 msg = g_strdup_vprintf(fmt, ap);
566 sync_pipe_errmsg_to_parent(2, msg, "");
569 fprintf(stderr, "dumpcap: ");
570 vfprintf(stderr, fmt, ap);
571 fprintf(stderr, "\n");
576 * Report additional information for an error in command-line arguments.
577 * If we're a capture child, send a message back to the parent, otherwise
581 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
585 msg = g_strdup_vprintf(fmt, ap);
586 sync_pipe_errmsg_to_parent(2, msg, "");
589 vfprintf(stderr, fmt, ap);
590 fprintf(stderr, "\n");
596 #if 0 /* Set to enable capability debugging */
597 /* see 'man cap_to_text()' for explanation of output */
598 /* '=' means 'all= ' ie: no capabilities */
599 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
601 print_caps(const char *pfx) {
602 cap_t caps = cap_get_proc();
603 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
604 "%s: EUID: %d Capabilities: %s", pfx,
605 geteuid(), cap_to_text(caps, NULL));
608 print_caps(const char *pfx _U_) {
613 relinquish_all_capabilities(void)
615 /* Drop any and all capabilities this process may have. */
616 /* Allowed whether or not process has any privileges. */
617 cap_t caps = cap_init(); /* all capabilities initialized to off */
618 print_caps("Pre-clear");
619 if (cap_set_proc(caps)) {
620 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
622 print_caps("Post-clear");
628 open_capture_device(capture_options *capture_opts
629 #ifndef HAVE_PCAP_SET_TSTAMP_PRECISION
633 interface_options *interface_opts,
634 char (*open_err_str)[PCAP_ERRBUF_SIZE])
637 #ifdef HAVE_PCAP_CREATE
640 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
641 struct pcap_rmtauth auth;
644 /* Open the network interface to capture from it.
645 Some versions of libpcap may put warnings into the error buffer
646 if they succeed; to tell if that's happened, we have to clear
647 the error buffer, and check if it's still a null string. */
648 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Entering open_capture_device().");
649 (*open_err_str)[0] = '\0';
650 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
652 * If we're opening a remote device, use pcap_open(); that's currently
653 * the only open routine that supports remote devices.
655 if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
656 auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
657 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
658 auth.username = interface_opts->auth_username;
659 auth.password = interface_opts->auth_password;
661 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
662 "Calling pcap_open() using name %s, snaplen %d, promisc_mode %d, datatx_udp %d, nocap_rpcap %d.",
663 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode,
664 interface_opts->datatx_udp, interface_opts->nocap_rpcap);
665 pcap_h = pcap_open(interface_opts->name, interface_opts->snaplen,
667 (interface_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
668 (interface_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
669 (interface_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
670 CAP_READ_TIMEOUT, &auth, *open_err_str);
671 if (pcap_h == NULL) {
672 /* Error - did pcap actually supply an error message? */
673 if ((*open_err_str)[0] == '\0') {
674 /* Work around known WinPcap bug wherein no error message is
675 filled in on a failure to open an rpcap: URL. */
676 g_strlcpy(*open_err_str,
677 "Unknown error (pcap bug; actual error cause not reported)",
678 sizeof *open_err_str);
681 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
682 "pcap_open() returned %p.", (void *)pcap_h);
687 * If we're not opening a remote device, use pcap_create() and
688 * pcap_activate() if we have them, so that we can set the buffer
689 * size, otherwise use pcap_open_live().
691 #ifdef HAVE_PCAP_CREATE
692 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
693 "Calling pcap_create() using %s.", interface_opts->name);
694 pcap_h = pcap_create(interface_opts->name, *open_err_str);
695 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
696 "pcap_create() returned %p.", (void *)pcap_h);
697 if (pcap_h != NULL) {
698 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
699 "Calling pcap_set_snaplen() with snaplen %d.", interface_opts->snaplen);
700 pcap_set_snaplen(pcap_h, interface_opts->snaplen);
701 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
702 "Calling pcap_set_promisc() with promisc_mode %d.", interface_opts->promisc_mode);
703 pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
704 pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
706 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
708 * If we're writing pcap-ng files, try to enable
709 * nanosecond-resolution capture; any code that
710 * can read pcap-ng files must be able to handle
711 * nanosecond-resolution time stamps.
713 * If we're writing pcap files, don't try to enable
714 * nanosecond-resolution capture, as not all code
715 * that reads pcap files recognizes the nanosecond-
716 * resolution pcap file magic number.
718 if (capture_opts->use_pcapng)
719 request_high_resolution_timestamp(pcap_h);
720 #endif /* HAVE_PCAP_SET_TSTAMP_PRECISION */
722 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
723 "buffersize %d.", interface_opts->buffer_size);
724 if (interface_opts->buffer_size != 0) {
725 pcap_set_buffer_size(pcap_h, interface_opts->buffer_size * 1024 * 1024);
727 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
728 "monitor_mode %d.", interface_opts->monitor_mode);
729 if (interface_opts->monitor_mode)
730 pcap_set_rfmon(pcap_h, 1);
731 err = pcap_activate(pcap_h);
732 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
733 "pcap_activate() returned %d.", err);
735 /* Failed to activate, set to NULL */
736 if (err == PCAP_ERROR)
737 g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
739 g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
745 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
746 "pcap_open_live() calling using name %s, snaplen %d, promisc_mode %d.",
747 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode);
748 pcap_h = pcap_open_live(interface_opts->name, interface_opts->snaplen,
749 interface_opts->promisc_mode, CAP_READ_TIMEOUT,
751 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
752 "pcap_open_live() returned %p.", (void *)pcap_h);
755 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_capture_device %s : %s", pcap_h ? "SUCCESS" : "FAILURE", interface_opts->name);
760 get_capture_device_open_failure_messages(const char *open_err_str,
762 char *errmsg, size_t errmsg_len,
763 char *secondary_errmsg,
764 size_t secondary_errmsg_len)
767 const char *libpcap_warn;
768 static const char ppamsg[] = "can't find PPA for ";
771 g_snprintf(errmsg, (gulong) errmsg_len,
772 "The capture session could not be initiated on interface '%s' (%s).",
773 iface, open_err_str);
776 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
778 "In order to capture packets, WinPcap must be installed; see\n"
780 " https://www.winpcap.org/\n"
782 "for a downloadable version of WinPcap and for instructions on how to install\n"
785 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
787 "Please check that \"%s\" is the proper interface.\n"
790 "Help can be found at:\n"
792 " https://wiki.wireshark.org/WinPcap\n"
793 " https://wiki.wireshark.org/CaptureSetup\n",
797 /* If we got a "can't find PPA for X" message, warn the user (who
798 is running dumpcap on HP-UX) that they don't have a version of
799 libpcap that properly handles HP-UX (libpcap 0.6.x and later
800 versions, which properly handle HP-UX, say "can't find /dev/dlpi
801 PPA for X" rather than "can't find PPA for X"). */
802 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
805 "You are running (T)Wireshark with a version of the libpcap library\n"
806 "that doesn't handle HP-UX network devices well; this means that\n"
807 "(T)Wireshark may not be able to capture packets.\n"
809 "To fix this, you should install libpcap 0.6.2, or a later version\n"
810 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
811 "packaged binary form from the Software Porting And Archive Centre\n"
812 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
813 "at the URL lists a number of mirror sites.";
817 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
818 "Please check to make sure you have sufficient permissions, and that you have "
819 "the proper interface or pipe specified.%s", libpcap_warn);
823 /* Set the data link type on a pcap. */
825 set_pcap_linktype(pcap_t *pcap_h, int linktype, char *name,
826 char *errmsg, size_t errmsg_len,
827 char *secondary_errmsg, size_t secondary_errmsg_len)
829 char *set_linktype_err_str;
832 return TRUE; /* just use the default */
833 #ifdef HAVE_PCAP_SET_DATALINK
834 if (pcap_set_datalink(pcap_h, linktype) == 0)
835 return TRUE; /* no error */
836 set_linktype_err_str = pcap_geterr(pcap_h);
838 /* Let them set it to the type it is; reject any other request. */
839 if (get_pcap_linktype(pcap_h, name) == linktype)
840 return TRUE; /* no error */
841 set_linktype_err_str =
842 "That DLT isn't one of the DLTs supported by this device";
844 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type on interface '%s' (%s).",
845 name, set_linktype_err_str);
847 * If the error isn't "XXX is not one of the DLTs supported by this device",
848 * tell the user to tell the Wireshark developers about it.
850 if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
851 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
853 secondary_errmsg[0] = '\0';
858 compile_capture_filter(const char *iface, pcap_t *pcap_h,
859 struct bpf_program *fcode, const char *cfilter)
861 bpf_u_int32 netnum, netmask;
862 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
864 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
866 * Well, we can't get the netmask for this interface; it's used
867 * only for filters that check for broadcast IP addresses, so
868 * we just punt and use 0. It might be nice to warn the user,
869 * but that's a pain in a GUI application, as it'd involve popping
870 * up a message box, and it's not clear how often this would make
871 * a difference (only filters that check for IP broadcast addresses
875 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
880 * Sigh. Older versions of libpcap don't properly declare the
881 * third argument to pcap_compile() as a const pointer. Cast
885 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
891 #ifdef HAVE_BPF_IMAGE
893 show_filter_code(capture_options *capture_opts)
895 interface_options interface_opts;
897 gchar open_err_str[PCAP_ERRBUF_SIZE];
898 char errmsg[MSG_MAX_LENGTH+1];
899 char secondary_errmsg[MSG_MAX_LENGTH+1];
900 struct bpf_program fcode;
901 struct bpf_insn *insn;
905 for (j = 0; j < capture_opts->ifaces->len; j++) {
906 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
907 pcap_h = open_capture_device(capture_opts, &interface_opts, &open_err_str);
908 if (pcap_h == NULL) {
909 /* Open failed; get messages */
910 get_capture_device_open_failure_messages(open_err_str,
912 errmsg, sizeof errmsg,
914 sizeof secondary_errmsg);
915 /* And report them */
916 report_capture_error(errmsg, secondary_errmsg);
920 /* Set the link-layer type. */
921 if (!set_pcap_linktype(pcap_h, interface_opts.linktype, interface_opts.name,
922 errmsg, sizeof errmsg,
923 secondary_errmsg, sizeof secondary_errmsg)) {
925 report_capture_error(errmsg, secondary_errmsg);
929 /* OK, try to compile the capture filter. */
930 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
931 interface_opts.cfilter)) {
933 report_cfilter_error(capture_opts, j, errmsg);
938 /* Now print the filter code. */
939 insn = fcode.bf_insns;
941 for (i = 0; i < fcode.bf_len; insn++, i++)
942 printf("%s\n", bpf_image(insn, i));
944 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
945 /* to remove any suid privileges. */
946 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
947 /* (euid/egid have already previously been set to ruid/rgid. */
948 /* (See comment in main() for details) */
950 relinquish_special_privs_perm();
952 relinquish_all_capabilities();
955 /* Let our parent know we succeeded. */
956 pipe_write_block(2, SP_SUCCESS, NULL);
963 * capture_interface_list() is expected to do the right thing to get
964 * a list of interfaces.
966 * In most of the programs in the Wireshark suite, "the right thing"
967 * is to run dumpcap and ask it for the list, because dumpcap may
968 * be the only program in the suite with enough privileges to get
971 * In dumpcap itself, however, we obviously can't run dumpcap to
972 * ask for the list. Therefore, our capture_interface_list() should
973 * just call get_interface_list().
976 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
978 return get_interface_list(err, err_str);
982 * Get the data-link type for a libpcap device.
983 * This works around AIX 5.x's non-standard and incompatible-with-the-
984 * rest-of-the-universe libpcap.
987 get_pcap_linktype(pcap_t *pch, const char *devicename
995 const char *ifacename;
998 linktype = pcap_datalink(pch);
1002 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
1003 * rather than DLT_ values for link-layer types; the ifType values
1004 * for LAN devices are:
1011 * and the ifType value for a loopback device is 24.
1013 * The AIX names for LAN devices begin with:
1020 * and the AIX names for loopback devices begin with "lo".
1022 * (The difference between "Ethernet" and "802.3" is presumably
1023 * whether packets have an Ethernet header, with a packet type,
1024 * or an 802.3 header, with a packet length, followed by an 802.2
1025 * header and possibly a SNAP header.)
1027 * If the device name matches "linktype" interpreted as an ifType
1028 * value, rather than as a DLT_ value, we will assume this is AIX's
1029 * non-standard, incompatible libpcap, rather than a standard libpcap,
1030 * and will map the link-layer type to the standard DLT_ value for
1031 * that link-layer type, as that's what the rest of Wireshark expects.
1033 * (This means the capture files won't be readable by a tcpdump
1034 * linked with AIX's non-standard libpcap, but so it goes. They
1035 * *will* be readable by standard versions of tcpdump, Wireshark,
1038 * XXX - if we conclude we're using AIX libpcap, should we also
1039 * set a flag to cause us to assume the time stamps are in
1040 * seconds-and-nanoseconds form, and to convert them to
1041 * seconds-and-microseconds form before processing them and
1046 * Find the last component of the device name, which is the
1049 ifacename = strchr(devicename, '/');
1050 if (ifacename == NULL)
1051 ifacename = devicename;
1053 /* See if it matches any of the LAN device names. */
1054 if (strncmp(ifacename, "en", 2) == 0) {
1055 if (linktype == 6) {
1057 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
1061 } else if (strncmp(ifacename, "et", 2) == 0) {
1062 if (linktype == 7) {
1064 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
1065 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
1070 } else if (strncmp(ifacename, "tr", 2) == 0) {
1071 if (linktype == 9) {
1073 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
1074 * DLT_IEEE802, which is what's used for Token Ring.
1078 } else if (strncmp(ifacename, "fi", 2) == 0) {
1079 if (linktype == 15) {
1081 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
1085 } else if (strncmp(ifacename, "lo", 2) == 0) {
1086 if (linktype == 24) {
1088 * That's the RFC 1573 value for "software loopback" devices; map it
1089 * to DLT_NULL, which is what's used for loopback devices on BSD.
1099 static data_link_info_t *
1100 create_data_link_info(int dlt)
1102 data_link_info_t *data_link_info;
1105 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
1106 data_link_info->dlt = dlt;
1107 text = pcap_datalink_val_to_name(dlt);
1109 data_link_info->name = g_strdup(text);
1111 data_link_info->name = g_strdup_printf("DLT %d", dlt);
1112 text = pcap_datalink_val_to_description(dlt);
1114 data_link_info->description = g_strdup(text);
1116 data_link_info->description = NULL;
1117 return data_link_info;
1121 * Get the capabilities of a network device.
1123 static if_capabilities_t *
1124 get_if_capabilities(const char *devicename, gboolean monitor_mode
1125 #ifndef HAVE_PCAP_CREATE
1130 if_capabilities_t *caps;
1131 char errbuf[PCAP_ERRBUF_SIZE];
1133 #ifdef HAVE_PCAP_CREATE
1137 #ifdef HAVE_PCAP_LIST_DATALINKS
1141 data_link_info_t *data_link_info;
1144 * Allocate the interface capabilities structure.
1146 caps = (if_capabilities_t *)g_malloc(sizeof *caps);
1149 * WinPcap 4.1.2, and possibly earlier versions, have a bug
1150 * wherein, when an open with an rpcap: URL fails, the error
1151 * message for the error is not copied to errbuf and whatever
1152 * on-the-stack junk is in errbuf is treated as the error
1155 * To work around that (and any other bugs of that sort, we
1156 * initialize errbuf to an empty string. If we get an error
1157 * and the string is empty, we report it as an unknown error.
1158 * (If we *don't* get an error, and the string is *non*-empty,
1159 * that could be a warning returned, such as "can't turn
1160 * promiscuous mode on"; we currently don't do so.)
1163 #ifdef HAVE_PCAP_OPEN
1164 pch = pcap_open(devicename, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1165 caps->can_set_rfmon = FALSE;
1167 if (err_str != NULL)
1168 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1172 #elif defined(HAVE_PCAP_CREATE)
1173 pch = pcap_create(devicename, errbuf);
1175 if (err_str != NULL)
1176 *err_str = g_strdup(errbuf);
1180 status = pcap_can_set_rfmon(pch);
1183 if (status == PCAP_ERROR)
1184 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1187 *err_str = g_strdup(pcap_statustostr(status));
1193 caps->can_set_rfmon = FALSE;
1194 else if (status == 1) {
1195 caps->can_set_rfmon = TRUE;
1197 pcap_set_rfmon(pch, 1);
1199 if (err_str != NULL) {
1200 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1208 status = pcap_activate(pch);
1210 /* Error. We ignore warnings (status > 0). */
1211 if (err_str != NULL) {
1212 if (status == PCAP_ERROR)
1213 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1216 *err_str = g_strdup(pcap_statustostr(status));
1223 pch = pcap_open_live(devicename, MIN_PACKET_SIZE, 0, 0, errbuf);
1224 caps->can_set_rfmon = FALSE;
1226 if (err_str != NULL)
1227 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1232 deflt = get_pcap_linktype(pch, devicename);
1233 #ifdef HAVE_PCAP_LIST_DATALINKS
1234 nlt = pcap_list_datalinks(pch, &linktypes);
1235 if (nlt == 0 || linktypes == NULL) {
1237 if (err_str != NULL)
1238 *err_str = NULL; /* an empty list doesn't mean an error */
1242 caps->data_link_types = NULL;
1243 for (i = 0; i < nlt; i++) {
1244 data_link_info = create_data_link_info(linktypes[i]);
1247 * XXX - for 802.11, make the most detailed 802.11
1248 * version the default, rather than the one the
1249 * device has as the default?
1251 if (linktypes[i] == deflt)
1252 caps->data_link_types = g_list_prepend(caps->data_link_types,
1255 caps->data_link_types = g_list_append(caps->data_link_types,
1258 #ifdef HAVE_PCAP_FREE_DATALINKS
1259 pcap_free_datalinks(linktypes);
1262 * In Windows, there's no guarantee that if you have a library
1263 * built with one version of the MSVC++ run-time library, and
1264 * it returns a pointer to allocated data, you can free that
1265 * data from a program linked with another version of the
1266 * MSVC++ run-time library.
1268 * This is not an issue on UN*X.
1270 * See the mail threads starting at
1272 * https://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1276 * https://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1279 #define xx_free free /* hack so checkAPIs doesn't complain */
1282 #endif /* HAVE_PCAP_FREE_DATALINKS */
1283 #else /* HAVE_PCAP_LIST_DATALINKS */
1285 data_link_info = create_data_link_info(deflt);
1286 caps->data_link_types = g_list_append(caps->data_link_types,
1288 #endif /* HAVE_PCAP_LIST_DATALINKS */
1292 if (err_str != NULL)
1297 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1299 * Output a machine readable list of the interfaces
1300 * This list is retrieved by the sync_interface_list_open() function
1301 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
1304 print_machine_readable_interfaces(GList *if_list)
1311 char addr_str[ADDRSTRLEN];
1313 if (capture_child) {
1314 /* Let our parent know we succeeded. */
1315 pipe_write_block(2, SP_SUCCESS, NULL);
1318 i = 1; /* Interface id number */
1319 for (if_entry = g_list_first(if_list); if_entry != NULL;
1320 if_entry = g_list_next(if_entry)) {
1321 if_info = (if_info_t *)if_entry->data;
1322 printf("%d. %s\t", i++, if_info->name);
1325 * Print the contents of the if_entry struct in a parseable format.
1326 * Each if_entry element is tab-separated. Addresses are comma-
1329 /* XXX - Make sure our description doesn't contain a tab */
1330 if (if_info->vendor_description != NULL)
1331 printf("%s\t", if_info->vendor_description);
1335 /* XXX - Make sure our friendly name doesn't contain a tab */
1336 if (if_info->friendly_name != NULL)
1337 printf("%s\t", if_info->friendly_name);
1341 printf("%i\t", if_info->type);
1343 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1344 addr = g_slist_next(addr)) {
1345 if (addr != g_slist_nth(if_info->addrs, 0))
1348 if_addr = (if_addr_t *)addr->data;
1349 switch(if_addr->ifat_type) {
1351 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1353 printf("%s", addr_str);
1355 printf("<unknown IPv4>");
1359 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1360 addr_str, ADDRSTRLEN)) {
1361 printf("%s", addr_str);
1363 printf("<unknown IPv6>");
1367 printf("<type unknown %i>", if_addr->ifat_type);
1371 if (if_info->loopback)
1372 printf("\tloopback");
1374 printf("\tnetwork");
1376 printf("\t%s", if_info->extcap);
1383 * If you change the machine-readable output format of this function,
1384 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1387 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1390 data_link_info_t *data_link_info;
1391 const gchar *desc_str;
1393 if (capture_child) {
1394 /* Let our parent know we succeeded. */
1395 pipe_write_block(2, SP_SUCCESS, NULL);
1398 if (caps->can_set_rfmon)
1402 for (lt_entry = caps->data_link_types; lt_entry != NULL;
1403 lt_entry = g_list_next(lt_entry)) {
1404 data_link_info = (data_link_info_t *)lt_entry->data;
1405 if (data_link_info->description != NULL)
1406 desc_str = data_link_info->description;
1408 desc_str = "(not supported)";
1409 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1419 /* Print the number of packets captured for each interface until we're killed. */
1421 print_statistics_loop(gboolean machine_readable)
1423 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1429 char errbuf[PCAP_ERRBUF_SIZE];
1430 struct pcap_stat ps;
1432 if_list = get_interface_list(&err, &err_str);
1433 if (if_list == NULL) {
1435 cmdarg_err("There are no interfaces on which a capture can be done");
1437 cmdarg_err("%s", err_str);
1443 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1444 if_info = (if_info_t *)if_entry->data;
1447 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
1448 * connections. We avoid collecting stats on them.
1450 if (!strncmp(if_info->name, "nf", 2)) {
1451 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
1457 #ifdef HAVE_PCAP_OPEN
1458 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1460 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1464 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1465 if_stat->name = g_strdup(if_info->name);
1467 stat_list = g_list_append(stat_list, if_stat);
1472 cmdarg_err("There are no interfaces on which a capture can be done");
1476 if (capture_child) {
1477 /* Let our parent know we succeeded. */
1478 pipe_write_block(2, SP_SUCCESS, NULL);
1481 if (!machine_readable) {
1482 printf("%-15s %10s %10s\n", "Interface", "Received",
1486 global_ld.go = TRUE;
1487 while (global_ld.go) {
1488 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1489 if_stat = (if_stat_t *)stat_entry->data;
1490 pcap_stats(if_stat->pch, &ps);
1492 if (!machine_readable) {
1493 printf("%-15s %10u %10u\n", if_stat->name,
1494 ps.ps_recv, ps.ps_drop);
1496 printf("%s\t%u\t%u\n", if_stat->name,
1497 ps.ps_recv, ps.ps_drop);
1502 /* If we have a dummy signal pipe check it */
1503 if (!signal_pipe_check_running()) {
1504 global_ld.go = FALSE;
1512 /* XXX - Not reached. Should we look for 'q' in stdin? */
1513 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1514 if_stat = (if_stat_t *)stat_entry->data;
1515 pcap_close(if_stat->pch);
1516 g_free(if_stat->name);
1519 g_list_free(stat_list);
1520 free_interface_list(if_list);
1528 capture_cleanup_handler(DWORD dwCtrlType)
1530 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1531 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1532 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1533 like SIGTERM at least when the machine's shutting down.
1535 For now, if we're running as a command rather than a capture child,
1536 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1537 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1538 in that way on UN*X.
1540 If we're not running as a capture child, we might be running as
1541 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1542 user logs out. (XXX - can we explicitly check whether we're
1543 running as a service?) */
1545 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1546 "Console: Control signal");
1547 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1548 "Console: Control signal, CtrlType: %u", dwCtrlType);
1550 /* Keep capture running if we're a service and a user logs off */
1551 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1552 capture_loop_stop();
1560 capture_cleanup_handler(int signum _U_)
1562 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1563 SIGTERM. We assume that if the user wanted it to keep running
1564 after they logged out, they'd have nohupped it. */
1566 /* Note: don't call g_log() in the signal handler: if we happened to be in
1567 * g_log() in process context when the signal came in, g_log will detect
1568 * the "recursion" and abort.
1571 capture_loop_stop();
1577 report_capture_count(gboolean reportit)
1579 /* Don't print this if we're a capture child. */
1580 if (!capture_child && reportit) {
1581 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packet_count);
1582 /* stderr could be line buffered */
1590 report_counts_for_siginfo(void)
1592 report_capture_count(quiet);
1593 infoprint = FALSE; /* we just reported it */
1597 report_counts_siginfo(int signum _U_)
1599 int sav_errno = errno;
1601 /* If we've been told to delay printing, just set a flag asking
1602 that we print counts (if we're supposed to), otherwise print
1603 the count of packets captured (if we're supposed to). */
1607 report_counts_for_siginfo();
1610 #endif /* SIGINFO */
1613 exit_main(int status)
1616 /* Shutdown windows sockets */
1619 /* can be helpful for debugging */
1620 #ifdef DEBUG_DUMPCAP
1621 printf("Press any key\n");
1632 * If we were linked with libcap (not related to libpcap), make sure we have
1633 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1634 * (See comment in main() for details)
1637 relinquish_privs_except_capture(void)
1639 /* If 'started_with_special_privs' (ie: suid) then enable for
1640 * ourself the NET_ADMIN and NET_RAW capabilities and then
1641 * drop our suid privileges.
1643 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1644 * stuff we don't need (and shouldn't have).
1645 * CAP_NET_RAW: Packet capture (raw sockets).
1648 if (started_with_special_privs()) {
1649 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1650 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1652 cap_t caps = cap_init(); /* all capabilities initialized to off */
1654 print_caps("Pre drop, pre set");
1656 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1657 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1660 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1661 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1663 if (cap_set_proc(caps)) {
1664 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1666 print_caps("Pre drop, post set");
1668 relinquish_special_privs_perm();
1670 print_caps("Post drop, pre set");
1671 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1672 if (cap_set_proc(caps)) {
1673 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1675 print_caps("Post drop, post set");
1681 #endif /* HAVE_LIBCAP */
1683 /* Take care of byte order in the libpcap headers read from pipes.
1684 * (function taken from wiretap/libpcap.c) */
1686 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1689 /* Byte-swap the record header fields. */
1690 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1691 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1692 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1693 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1696 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1697 swapped, in order to match the BPF header layout.
1699 Unfortunately, some files were, according to a comment in the "libpcap"
1700 source, written with version 2.3 in their headers but without the
1701 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1702 would make no sense - we assume that we need to swap them. */
1703 if (hdr->version_major == 2 &&
1704 (hdr->version_minor < 3 ||
1705 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1708 temp = rechdr->orig_len;
1709 rechdr->orig_len = rechdr->incl_len;
1710 rechdr->incl_len = temp;
1714 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1718 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1722 return recv(pipe_fd, buf, (int)sz, 0);
1727 return ws_read(pipe_fd, buf, sz);
1733 * Thread function that reads from a pipe and pushes the data
1734 * to the main application thread.
1737 * XXX Right now we use async queues for basic signaling. The main thread
1738 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1739 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1740 * Iff the read is successful cap_pipe_read pushes an item onto
1741 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1742 * the queues themselves (yet).
1744 * We might want to move some of the cap_pipe_dispatch logic here so that
1745 * we can let cap_thread_read run independently, queuing up multiple reads
1746 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1748 static void *cap_thread_read(void *arg)
1750 pcap_options *pcap_opts;
1753 DWORD b, last_err, bytes_read;
1759 pcap_opts = (pcap_options *)arg;
1760 while (pcap_opts->cap_pipe_err == PIPOK) {
1761 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1762 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1764 while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1765 if ((pcap_opts->from_cap_socket)
1771 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1772 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1775 pcap_opts->cap_pipe_err = PIPEOF;
1779 pcap_opts->cap_pipe_err = PIPERR;
1790 /* If we try to use read() on a named pipe on Windows with partial
1791 * data it appears to return EOF.
1793 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1794 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1799 last_err = GetLastError();
1800 if (last_err == ERROR_MORE_DATA) {
1802 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1803 pcap_opts->cap_pipe_err = PIPEOF;
1807 pcap_opts->cap_pipe_err = PIPERR;
1810 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1811 pcap_opts->cap_pipe_err = PIPEOF;
1818 pcap_opts->cap_pipe_bytes_read = bytes_read;
1819 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1820 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1822 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1828 /* Provide select() functionality for a single file descriptor
1829 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1831 * Returns the same values as select.
1834 cap_pipe_select(int pipe_fd)
1837 struct timeval timeout;
1840 FD_SET(pipe_fd, &rfds);
1842 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1843 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1845 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1848 #define DEF_TCP_PORT 19000
1851 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1853 char *sockname = pipename + 4;
1854 struct sockaddr_in sa;
1861 memset(&sa, 0, sizeof(sa));
1863 p = strchr(sockname, ':');
1865 len = strlen(sockname);
1866 port = DEF_TCP_PORT;
1870 port = strtoul(p + 1, &p, 10);
1871 if (*p || port > 65535) {
1880 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1882 if (inet_pton(AF_INET, buf, &sa.sin_addr) <= 0) {
1886 sa.sin_family = AF_INET;
1887 sa.sin_port = g_htons((u_short)port);
1889 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1890 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1892 LPTSTR errorText = NULL;
1895 lastError = WSAGetLastError();
1896 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1897 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1898 FORMAT_MESSAGE_IGNORE_INSERTS,
1899 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1900 (LPTSTR)&errorText, 0, NULL);
1902 g_snprintf(errmsg, errmsgl,
1903 "The capture session could not be initiated due to the socket error: \n"
1905 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1907 LocalFree(errorText);
1909 " %d: %s", errno, g_strerror(errno));
1911 pcap_opts->cap_pipe_err = PIPERR;
1914 cap_pipe_close(fd, TRUE);
1918 pcap_opts->from_cap_socket = TRUE;
1922 g_snprintf(errmsg, errmsgl,
1923 "The capture session could not be initiated because\n"
1924 "\"%s\" is not a valid socket specification", pipename);
1925 pcap_opts->cap_pipe_err = PIPERR;
1929 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1933 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1937 closesocket(pipe_fd);
1944 /* Mimic pcap_open_live() for pipe captures
1946 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1947 * open it, and read the header.
1949 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1950 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1952 cap_pipe_open_live(char *pipename,
1953 pcap_options *pcap_opts,
1954 struct pcap_hdr *hdr,
1955 char *errmsg, int errmsgl)
1958 ws_statb64 pipe_stat;
1959 struct sockaddr_un sa;
1963 interface_options interface_opts;
1966 int fd = -1, sel_ret;
1969 pcap_opts->cap_pipe_fd = -1;
1971 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1973 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1976 * XXX - this blocks until a pcap per-file header has been written to
1977 * the pipe, so it could block indefinitely.
1979 if (strcmp(pipename, "-") == 0) {
1981 fd = 0; /* read from stdin */
1983 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1985 } else if (!strncmp(pipename, "TCP@", 4)) {
1986 if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
1991 if (ws_stat64(pipename, &pipe_stat) < 0) {
1992 if (errno == ENOENT || errno == ENOTDIR)
1993 pcap_opts->cap_pipe_err = PIPNEXIST;
1995 g_snprintf(errmsg, errmsgl,
1996 "The capture session could not be initiated "
1997 "due to error getting information on pipe/socket: %s", g_strerror(errno));
1998 pcap_opts->cap_pipe_err = PIPERR;
2002 if (S_ISFIFO(pipe_stat.st_mode)) {
2003 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
2005 g_snprintf(errmsg, errmsgl,
2006 "The capture session could not be initiated "
2007 "due to error on pipe open: %s", g_strerror(errno));
2008 pcap_opts->cap_pipe_err = PIPERR;
2011 } else if (S_ISSOCK(pipe_stat.st_mode)) {
2012 fd = socket(AF_UNIX, SOCK_STREAM, 0);
2014 g_snprintf(errmsg, errmsgl,
2015 "The capture session could not be initiated "
2016 "due to error on socket create: %s", g_strerror(errno));
2017 pcap_opts->cap_pipe_err = PIPERR;
2020 sa.sun_family = AF_UNIX;
2022 * The Single UNIX Specification says:
2024 * The size of sun_path has intentionally been left undefined.
2025 * This is because different implementations use different sizes.
2026 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
2027 * of 104. Since most implementations originate from BSD versions,
2028 * the size is typically in the range 92 to 108.
2030 * Applications should not assume a particular length for sun_path
2031 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
2035 * The <sys/un.h> header shall define the sockaddr_un structure,
2036 * which shall include at least the following members:
2038 * sa_family_t sun_family Address family.
2039 * char sun_path[] Socket pathname.
2041 * so we assume that it's an array, with a specified size,
2042 * and that the size reflects the maximum path length.
2044 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
2045 /* Path name too long */
2046 g_snprintf(errmsg, errmsgl,
2047 "The capture session coud not be initiated "
2048 "due to error on socket connect: Path name too long");
2049 pcap_opts->cap_pipe_err = PIPERR;
2053 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
2055 g_snprintf(errmsg, errmsgl,
2056 "The capture session coud not be initiated "
2057 "due to error on socket connect: %s", g_strerror(errno));
2058 pcap_opts->cap_pipe_err = PIPERR;
2063 if (S_ISCHR(pipe_stat.st_mode)) {
2065 * Assume the user specified an interface on a system where
2066 * interfaces are in /dev. Pretend we haven't seen it.
2068 pcap_opts->cap_pipe_err = PIPNEXIST;
2070 g_snprintf(errmsg, errmsgl,
2071 "The capture session could not be initiated because\n"
2072 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
2073 pcap_opts->cap_pipe_err = PIPERR;
2078 #define PIPE_STR "\\pipe\\"
2079 /* Under Windows, named pipes _must_ have the form
2080 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
2082 pncopy = g_strdup(pipename);
2083 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
2084 pos = strchr(pncopy + 3, '\\');
2085 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
2092 g_snprintf(errmsg, errmsgl,
2093 "The capture session could not be initiated because\n"
2094 "\"%s\" is neither an interface nor a pipe", pipename);
2095 pcap_opts->cap_pipe_err = PIPNEXIST;
2099 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
2101 /* Wait for the pipe to appear */
2104 if(strncmp(interface_opts.name,"\\\\.\\pipe\\",9)== 0)
2105 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
2107 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
2108 OPEN_EXISTING, 0, NULL);
2110 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
2113 if (GetLastError() != ERROR_PIPE_BUSY) {
2114 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2115 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2116 g_snprintf(errmsg, errmsgl,
2117 "The capture session on \"%s\" could not be started "
2118 "due to error on pipe open: %s (error %d)",
2119 pipename, utf_16to8(err_str), GetLastError());
2121 pcap_opts->cap_pipe_err = PIPERR;
2125 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
2126 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2127 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2128 g_snprintf(errmsg, errmsgl,
2129 "The capture session on \"%s\" timed out during "
2130 "pipe open: %s (error %d)",
2131 pipename, utf_16to8(err_str), GetLastError());
2133 pcap_opts->cap_pipe_err = PIPERR;
2140 pcap_opts->from_cap_pipe = TRUE;
2143 if (pcap_opts->from_cap_socket)
2146 /* read the pcap header */
2148 while (bytes_read < sizeof magic) {
2150 g_snprintf(errmsg, errmsgl, "Invalid file descriptor");
2154 sel_ret = cap_pipe_select(fd);
2156 g_snprintf(errmsg, errmsgl,
2157 "Unexpected error from select: %s", g_strerror(errno));
2159 } else if (sel_ret > 0) {
2160 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
2161 sizeof magic-bytes_read,
2162 pcap_opts->from_cap_socket);
2165 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2167 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2177 #if GLIB_CHECK_VERSION(2,31,0)
2178 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
2180 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
2183 pcap_opts->cap_pipe_buf = (char *) &magic;
2184 pcap_opts->cap_pipe_bytes_read = 0;
2185 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
2186 /* We don't have to worry about cap_pipe_read_mtx here */
2187 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2188 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2189 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2190 if (pcap_opts->cap_pipe_bytes_read == 0)
2191 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2193 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2202 case PCAP_NSEC_MAGIC:
2203 /* Host that wrote it has our byte order, and was running
2204 a program using either standard or ss990417 libpcap. */
2205 pcap_opts->cap_pipe_byte_swapped = FALSE;
2206 pcap_opts->cap_pipe_modified = FALSE;
2207 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
2209 case PCAP_MODIFIED_MAGIC:
2210 /* Host that wrote it has our byte order, but was running
2211 a program using either ss990915 or ss991029 libpcap. */
2212 pcap_opts->cap_pipe_byte_swapped = FALSE;
2213 pcap_opts->cap_pipe_modified = TRUE;
2215 case PCAP_SWAPPED_MAGIC:
2216 case PCAP_SWAPPED_NSEC_MAGIC:
2217 /* Host that wrote it has a byte order opposite to ours,
2218 and was running a program using either standard or
2219 ss990417 libpcap. */
2220 pcap_opts->cap_pipe_byte_swapped = TRUE;
2221 pcap_opts->cap_pipe_modified = FALSE;
2222 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2224 case PCAP_SWAPPED_MODIFIED_MAGIC:
2225 /* Host that wrote it out has a byte order opposite to
2226 ours, and was running a program using either ss990915
2227 or ss991029 libpcap. */
2228 pcap_opts->cap_pipe_byte_swapped = TRUE;
2229 pcap_opts->cap_pipe_modified = TRUE;
2232 /* Not a "libpcap" type we know about. */
2233 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2238 if (pcap_opts->from_cap_socket)
2241 /* Read the rest of the header */
2243 while (bytes_read < sizeof(struct pcap_hdr)) {
2244 sel_ret = cap_pipe_select(fd);
2246 g_snprintf(errmsg, errmsgl,
2247 "Unexpected error from select: %s", g_strerror(errno));
2249 } else if (sel_ret > 0) {
2250 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2251 sizeof(struct pcap_hdr) - bytes_read,
2252 pcap_opts->from_cap_socket);
2255 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2257 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
2267 pcap_opts->cap_pipe_buf = (char *) hdr;
2268 pcap_opts->cap_pipe_bytes_read = 0;
2269 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
2270 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2271 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2272 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2273 if (pcap_opts->cap_pipe_bytes_read == 0)
2274 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2276 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
2283 if (pcap_opts->cap_pipe_byte_swapped) {
2284 /* Byte-swap the header fields about which we care. */
2285 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
2286 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
2287 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
2288 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
2290 pcap_opts->linktype = hdr->network;
2292 if (hdr->version_major < 2) {
2293 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2297 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2298 pcap_opts->cap_pipe_err = PIPOK;
2299 pcap_opts->cap_pipe_fd = fd;
2303 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2304 pcap_opts->cap_pipe_err = PIPERR;
2305 cap_pipe_close(fd, pcap_opts->from_cap_socket);
2306 pcap_opts->cap_pipe_fd = -1;
2310 /* We read one record from the pipe, take care of byte order in the record
2311 * header, write the record to the capture file, and update capture statistics. */
2313 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2315 struct pcap_pkthdr phdr;
2316 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2319 #if !GLIB_CHECK_VERSION(2,31,18)
2327 #ifdef LOG_CAPTURE_VERBOSE
2328 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2331 switch (pcap_opts->cap_pipe_state) {
2333 case STATE_EXPECT_REC_HDR:
2335 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2338 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2339 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2340 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2341 pcap_opts->cap_pipe_bytes_read = 0;
2344 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2345 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2346 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2351 case STATE_READ_REC_HDR:
2353 if (pcap_opts->from_cap_socket)
2356 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2357 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
2360 result = PD_PIPE_EOF;
2362 result = PD_PIPE_ERR;
2365 pcap_opts->cap_pipe_bytes_read += b;
2369 #if GLIB_CHECK_VERSION(2,31,18)
2370 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2372 g_get_current_time(&wait_time);
2373 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2374 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2376 if (pcap_opts->cap_pipe_err == PIPEOF) {
2377 result = PD_PIPE_EOF;
2379 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2380 result = PD_PIPE_ERR;
2388 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2390 result = PD_REC_HDR_READ;
2393 case STATE_EXPECT_DATA:
2395 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2398 pcap_opts->cap_pipe_state = STATE_READ_DATA;
2399 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2400 pcap_opts->cap_pipe_bytes_read = 0;
2403 pcap_opts->cap_pipe_buf = (char *) data;
2404 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2405 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2410 case STATE_READ_DATA:
2412 if (pcap_opts->from_cap_socket)
2415 b = cap_pipe_read(pcap_opts->cap_pipe_fd,
2416 data+pcap_opts->cap_pipe_bytes_read,
2417 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
2418 pcap_opts->from_cap_socket);
2421 result = PD_PIPE_EOF;
2423 result = PD_PIPE_ERR;
2426 pcap_opts->cap_pipe_bytes_read += b;
2431 #if GLIB_CHECK_VERSION(2,31,18)
2432 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2434 g_get_current_time(&wait_time);
2435 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2436 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2437 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2438 if (pcap_opts->cap_pipe_err == PIPEOF) {
2439 result = PD_PIPE_EOF;
2441 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2442 result = PD_PIPE_ERR;
2450 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2452 result = PD_DATA_READ;
2456 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2459 } /* switch (pcap_opts->cap_pipe_state) */
2462 * We've now read as much data as we were expecting, so process it.
2466 case PD_REC_HDR_READ:
2467 /* We've read the header. Take care of byte order. */
2468 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2469 &pcap_opts->cap_pipe_rechdr.hdr);
2470 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2471 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2472 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2476 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2477 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2480 /* no data to read? fall through */
2483 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2484 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2485 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2486 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2487 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2490 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2492 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2494 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2498 pcap_opts->cap_pipe_err = PIPEOF;
2503 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2504 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2505 g_snprintf(errmsg, errmsgl,
2506 "Error reading from pipe: %s (error %d)",
2507 utf_16to8(err_str), GetLastError());
2510 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2518 pcap_opts->cap_pipe_err = PIPERR;
2519 /* Return here rather than inside the switch to prevent GCC warning */
2524 /** Open the capture input file (pcap or capture pipe).
2525 * Returns TRUE if it succeeds, FALSE otherwise. */
2527 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2528 char *errmsg, size_t errmsg_len,
2529 char *secondary_errmsg, size_t secondary_errmsg_len)
2531 gchar open_err_str[PCAP_ERRBUF_SIZE];
2532 gchar *sync_msg_str;
2533 interface_options interface_opts;
2534 pcap_options *pcap_opts;
2538 gchar *sync_secondary_msg_str;
2539 WORD wVersionRequested;
2543 /* XXX - opening Winsock on tshark? */
2545 /* Initialize Windows Socket if we are in a WIN32 OS
2546 This needs to be done before querying the interface for network/netmask */
2548 /* XXX - do we really require 1.1 or earlier?
2549 Are there any versions that support only 2.0 or higher? */
2550 wVersionRequested = MAKEWORD(1, 1);
2551 err = WSAStartup(wVersionRequested, &wsaData);
2555 case WSASYSNOTREADY:
2556 g_snprintf(errmsg, (gulong) errmsg_len,
2557 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2560 case WSAVERNOTSUPPORTED:
2561 g_snprintf(errmsg, (gulong) errmsg_len,
2562 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2563 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2566 case WSAEINPROGRESS:
2567 g_snprintf(errmsg, (gulong) errmsg_len,
2568 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2572 g_snprintf(errmsg, (gulong) errmsg_len,
2573 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2577 g_snprintf(errmsg, (gulong) errmsg_len,
2578 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2582 g_snprintf(errmsg, (gulong) errmsg_len,
2583 "Couldn't initialize Windows Sockets: error %d", err);
2586 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2590 if ((use_threads == FALSE) &&
2591 (capture_opts->ifaces->len > 1)) {
2592 g_snprintf(errmsg, (gulong) errmsg_len,
2593 "Using threads is required for capturing on multiple interfaces.");
2597 for (i = 0; i < capture_opts->ifaces->len; i++) {
2598 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2599 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2600 if (pcap_opts == NULL) {
2601 g_snprintf(errmsg, (gulong) errmsg_len,
2602 "Could not allocate memory.");
2605 pcap_opts->received = 0;
2606 pcap_opts->dropped = 0;
2607 pcap_opts->flushed = 0;
2608 pcap_opts->pcap_h = NULL;
2609 #ifdef MUST_DO_SELECT
2610 pcap_opts->pcap_fd = -1;
2612 pcap_opts->pcap_err = FALSE;
2613 pcap_opts->interface_id = i;
2614 pcap_opts->tid = NULL;
2615 pcap_opts->snaplen = 0;
2616 pcap_opts->linktype = -1;
2617 pcap_opts->ts_nsec = FALSE;
2618 pcap_opts->from_cap_pipe = FALSE;
2619 pcap_opts->from_cap_socket = FALSE;
2620 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2621 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2623 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2625 pcap_opts->cap_pipe_fd = -1;
2626 pcap_opts->cap_pipe_modified = FALSE;
2627 pcap_opts->cap_pipe_byte_swapped = FALSE;
2629 pcap_opts->cap_pipe_buf = NULL;
2631 pcap_opts->cap_pipe_bytes_to_read = 0;
2632 pcap_opts->cap_pipe_bytes_read = 0;
2633 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2634 pcap_opts->cap_pipe_err = PIPOK;
2636 #if GLIB_CHECK_VERSION(2,31,0)
2637 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2638 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2640 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2642 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2643 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2645 g_array_append_val(ld->pcaps, pcap_opts);
2647 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2648 pcap_opts->pcap_h = open_capture_device(capture_opts, &interface_opts, &open_err_str);
2650 if (pcap_opts->pcap_h != NULL) {
2651 /* we've opened "iface" as a network device */
2653 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2654 /* Find out if we're getting nanosecond-precision time stamps */
2655 pcap_opts->ts_nsec = have_high_resolution_timestamp(pcap_opts->pcap_h);
2659 /* try to set the capture buffer size */
2660 if (interface_opts.buffer_size > 1 &&
2661 pcap_setbuff(pcap_opts->pcap_h, interface_opts.buffer_size * 1024 * 1024) != 0) {
2662 sync_secondary_msg_str = g_strdup_printf(
2663 "The capture buffer size of %d MiB seems to be too high for your machine,\n"
2664 "the default of %d MiB will be used.\n"
2666 "Nonetheless, the capture is started.\n",
2667 interface_opts.buffer_size, DEFAULT_CAPTURE_BUFFER_SIZE);
2668 report_capture_error("Couldn't set the capture buffer size.",
2669 sync_secondary_msg_str);
2670 g_free(sync_secondary_msg_str);
2674 #if defined(HAVE_PCAP_SETSAMPLING)
2675 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2676 struct pcap_samp *samp;
2678 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2679 switch (interface_opts.sampling_method) {
2680 case CAPTURE_SAMP_BY_COUNT:
2681 samp->method = PCAP_SAMP_1_EVERY_N;
2684 case CAPTURE_SAMP_BY_TIMER:
2685 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2689 sync_msg_str = g_strdup_printf(
2690 "Unknown sampling method %d specified,\n"
2691 "continue without packet sampling",
2692 interface_opts.sampling_method);
2693 report_capture_error("Couldn't set the capture "
2694 "sampling", sync_msg_str);
2695 g_free(sync_msg_str);
2697 samp->value = interface_opts.sampling_param;
2699 report_capture_error("Couldn't set the capture sampling",
2700 "Cannot get packet sampling data structure");
2705 /* setting the data link type only works on real interfaces */
2706 if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2708 secondary_errmsg, secondary_errmsg_len)) {
2711 pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2713 /* We couldn't open "iface" as a network device. */
2714 /* Try to open it as a pipe */
2715 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2718 if (pcap_opts->cap_pipe_fd == -1) {
2720 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2722 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2723 /* Pipe doesn't exist, so output message for interface */
2724 get_capture_device_open_failure_messages(open_err_str,
2725 interface_opts.name,
2729 secondary_errmsg_len);
2732 * Else pipe (or file) does exist and cap_pipe_open_live() has
2737 /* cap_pipe_open_live() succeeded; don't want
2738 error message from pcap_open_live() */
2739 open_err_str[0] = '\0';
2743 /* XXX - will this work for tshark? */
2744 #ifdef MUST_DO_SELECT
2745 if (!pcap_opts->from_cap_pipe) {
2746 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2747 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2749 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2754 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2755 returned a warning; print it, but keep capturing. */
2756 if (open_err_str[0] != '\0') {
2757 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2758 report_capture_error(sync_msg_str, "");
2759 g_free(sync_msg_str);
2761 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2762 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2765 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2766 /* to remove any suid privileges. */
2767 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2768 /* (euid/egid have already previously been set to ruid/rgid. */
2769 /* (See comment in main() for details) */
2771 relinquish_special_privs_perm();
2773 relinquish_all_capabilities();
2778 /* close the capture input file (pcap or capture pipe) */
2779 static void capture_loop_close_input(loop_data *ld)
2782 pcap_options *pcap_opts;
2784 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2786 for (i = 0; i < ld->pcaps->len; i++) {
2787 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2788 /* if open, close the capture pipe "input file" */
2789 if (pcap_opts->cap_pipe_fd >= 0) {
2790 g_assert(pcap_opts->from_cap_pipe);
2791 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2792 pcap_opts->cap_pipe_fd = -1;
2795 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2796 CloseHandle(pcap_opts->cap_pipe_h);
2797 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2800 /* if open, close the pcap "input file" */
2801 if (pcap_opts->pcap_h != NULL) {
2802 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2803 pcap_close(pcap_opts->pcap_h);
2804 pcap_opts->pcap_h = NULL;
2811 /* Shut down windows sockets */
2817 /* init the capture filter */
2818 static initfilter_status_t
2819 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2820 const gchar * name, const gchar * cfilter)
2822 struct bpf_program fcode;
2824 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2826 /* capture filters only work on real interfaces */
2827 if (cfilter && !from_cap_pipe) {
2828 /* A capture filter was specified; set it up. */
2829 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2830 /* Treat this specially - our caller might try to compile this
2831 as a display filter and, if that succeeds, warn the user that
2832 the display and capture filter syntaxes are different. */
2833 return INITFILTER_BAD_FILTER;
2835 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2836 #ifdef HAVE_PCAP_FREECODE
2837 pcap_freecode(&fcode);
2839 return INITFILTER_OTHER_ERROR;
2841 #ifdef HAVE_PCAP_FREECODE
2842 pcap_freecode(&fcode);
2846 return INITFILTER_NO_ERROR;
2850 /* set up to write to the already-opened capture output file/files */
2852 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2856 pcap_options *pcap_opts;
2857 interface_options interface_opts;
2858 gboolean successful;
2860 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2862 if ((capture_opts->use_pcapng == FALSE) &&
2863 (capture_opts->ifaces->len > 1)) {
2864 g_snprintf(errmsg, errmsg_len,
2865 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
2869 /* Set up to write to the capture file. */
2870 if (capture_opts->multi_files_on) {
2871 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2873 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2874 if (ld->pdh == NULL) {
2879 if (capture_opts->use_pcapng) {
2881 GString *os_info_str;
2883 os_info_str = g_string_new("");
2884 get_os_version_info(os_info_str);
2886 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2887 successful = pcapng_write_session_header_block(ld->pdh,
2888 (const char *)capture_opts->capture_comment, /* Comment*/
2890 os_info_str->str, /* OS*/
2892 -1, /* section_length */
2897 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2898 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2899 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2900 if (pcap_opts->from_cap_pipe) {
2901 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2903 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2905 successful = pcapng_write_interface_description_block(global_ld.pdh,
2906 NULL, /* OPT_COMMENT 1 */
2907 interface_opts.name, /* IDB_NAME 2 */
2908 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2909 interface_opts.cfilter, /* IDB_FILTER 11 */
2910 os_info_str->str, /* IDB_OS 12 */
2911 pcap_opts->linktype,
2913 &(global_ld.bytes_written),
2914 0, /* IDB_IF_SPEED 8 */
2915 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2919 g_string_free(os_info_str, TRUE);
2922 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2923 if (pcap_opts->from_cap_pipe) {
2924 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2926 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2928 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2929 pcap_opts->ts_nsec, &ld->bytes_written, &err);
2937 if (ld->pdh == NULL) {
2938 /* We couldn't set up to write to the capture file. */
2939 /* XXX - use cf_open_error_message from tshark instead? */
2944 g_snprintf(errmsg, errmsg_len,
2945 "The file to which the capture would be"
2946 " saved (\"%s\") could not be opened: Error %d.",
2947 capture_opts->save_file, err);
2949 g_snprintf(errmsg, errmsg_len,
2950 "The file to which the capture would be"
2951 " saved (\"%s\") could not be opened: %s.",
2952 capture_opts->save_file, g_strerror(err));
2964 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2968 pcap_options *pcap_opts;
2969 guint64 end_time = create_timestamp();
2971 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2973 if (capture_opts->multi_files_on) {
2974 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2976 if (capture_opts->use_pcapng) {
2977 for (i = 0; i < global_ld.pcaps->len; i++) {
2978 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2979 if (!pcap_opts->from_cap_pipe) {
2980 guint64 isb_ifrecv, isb_ifdrop;
2981 struct pcap_stat stats;
2983 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
2984 isb_ifrecv = pcap_opts->received;
2985 isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
2987 isb_ifrecv = G_MAXUINT64;
2988 isb_ifdrop = G_MAXUINT64;
2990 pcapng_write_interface_statistics_block(ld->pdh,
2993 "Counters provided by dumpcap",
3002 if (fclose(ld->pdh) == EOF) {
3003 if (err_close != NULL) {
3013 /* dispatch incoming packets (pcap or capture pipe)
3015 * Waits for incoming packets to be available, and calls pcap_dispatch()
3016 * to cause them to be processed.
3018 * Returns the number of packets which were processed.
3020 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3021 * packet-batching behaviour does not cause packets to get held back
3025 capture_loop_dispatch(loop_data *ld,
3026 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
3029 gint packet_count_before;
3030 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
3035 packet_count_before = ld->packet_count;
3036 if (pcap_opts->from_cap_pipe) {
3037 /* dispatch from capture pipe */
3038 #ifdef LOG_CAPTURE_VERBOSE
3039 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3042 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
3044 if (sel_ret < 0 && errno != EINTR) {
3045 g_snprintf(errmsg, errmsg_len,
3046 "Unexpected error from select: %s", g_strerror(errno));
3047 report_capture_error(errmsg, please_report);
3052 * "select()" says we can read from the pipe without blocking
3055 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
3065 /* dispatch from pcap */
3066 #ifdef MUST_DO_SELECT
3068 * If we have "pcap_get_selectable_fd()", we use it to get the
3069 * descriptor on which to select; if that's -1, it means there
3070 * is no descriptor on which you can do a "select()" (perhaps
3071 * because you're capturing on a special device, and that device's
3072 * driver unfortunately doesn't support "select()", in which case
3073 * we don't do the select - which means it might not be possible
3074 * to stop a capture until a packet arrives. If that's unacceptable,
3075 * plead with whoever supplies the software for that device to add
3076 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3077 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3078 * later, so it can use pcap_breakloop().
3080 #ifdef LOG_CAPTURE_VERBOSE
3081 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3083 if (pcap_opts->pcap_fd != -1) {
3084 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
3087 * "select()" says we can read from it without blocking; go for
3090 * We don't have pcap_breakloop(), so we only process one packet
3091 * per pcap_dispatch() call, to allow a signal to stop the
3092 * processing immediately, rather than processing all packets
3093 * in a batch before quitting.
3096 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3098 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3102 /* Error, rather than pcap_breakloop(). */
3103 pcap_opts->pcap_err = TRUE;
3105 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3108 if (sel_ret < 0 && errno != EINTR) {
3109 g_snprintf(errmsg, errmsg_len,
3110 "Unexpected error from select: %s", g_strerror(errno));
3111 report_capture_error(errmsg, please_report);
3117 #endif /* MUST_DO_SELECT */
3119 /* dispatch from pcap without select */
3121 #ifdef LOG_CAPTURE_VERBOSE
3122 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3126 * On Windows, we don't support asynchronously telling a process to
3127 * stop capturing; instead, we check for an indication on a pipe
3128 * after processing packets. We therefore process only one packet
3129 * at a time, so that we can check the pipe after every packet.
3132 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3134 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3138 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3140 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3145 /* Error, rather than pcap_breakloop(). */
3146 pcap_opts->pcap_err = TRUE;
3148 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3150 #else /* pcap_next_ex */
3151 #ifdef LOG_CAPTURE_VERBOSE
3152 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3154 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3157 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3158 * see https://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
3159 * This should be fixed in the WinPcap 4.0 alpha release.
3161 * For reference, an example remote interface:
3162 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3165 /* emulate dispatch from pcap */
3168 struct pcap_pkthdr *pkt_header;
3173 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
3175 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3177 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3182 pcap_opts->pcap_err = TRUE;
3186 #endif /* pcap_next_ex */
3190 #ifdef LOG_CAPTURE_VERBOSE
3191 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3194 return ld->packet_count - packet_count_before;
3198 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3199 * want to grab only the characters between the '{' and '}' delimiters.
3201 * Returns a GString that must be freed with g_string_free(). */
3203 isolate_uuid(const char *iface)
3208 ptr = strchr(iface, '{');
3210 return g_string_new(iface);
3211 gstr = g_string_new(ptr + 1);
3213 ptr = strchr(gstr->str, '}');
3217 gstr = g_string_truncate(gstr, ptr - gstr->str);
3222 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3223 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3225 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3226 char *errmsg, int errmsg_len)
3229 gchar *capfile_name;
3231 gboolean is_tempfile;
3233 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3234 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3236 if (capture_opts->save_file != NULL) {
3237 /* We return to the caller while the capture is in progress.
3238 * Therefore we need to take a copy of save_file in
3239 * case the caller destroys it after we return.
3241 capfile_name = g_strdup(capture_opts->save_file);
3243 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3244 if (capture_opts->multi_files_on) {
3245 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3246 g_snprintf(errmsg, errmsg_len,
3247 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3248 g_free(capfile_name);
3251 if (strcmp(capfile_name, "-") == 0) {
3252 /* write to stdout */
3255 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3256 _setmode(1, O_BINARY);
3259 } /* if (...output_to_pipe ... */
3262 if (capture_opts->multi_files_on) {
3263 /* ringbuffer is enabled */
3264 *save_file_fd = ringbuf_init(capfile_name,
3265 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3266 capture_opts->group_read_access);
3268 /* we need the ringbuf name */
3269 if (*save_file_fd != -1) {
3270 g_free(capfile_name);
3271 capfile_name = g_strdup(ringbuf_current_filename());
3274 /* Try to open/create the specified file for use as a capture buffer. */
3275 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
3276 (capture_opts->group_read_access) ? 0640 : 0600);
3279 is_tempfile = FALSE;
3281 /* Choose a random name for the temporary capture buffer */
3282 if (global_capture_opts.ifaces->len > 1) {
3283 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3286 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
3288 /* use the generic portion of the interface guid to form the basis of the filename */
3289 if (strncmp("NPF_{", basename, 5)==0)
3291 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3293 iface = isolate_uuid(basename);
3295 basename = g_strdup(iface->str);
3296 g_string_free(iface, TRUE);
3299 /* generate the temp file name prefix...
3300 * It would be nice if we could specify a pcapng/pcap filename suffix,
3301 * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
3302 if (capture_opts->use_pcapng) {
3303 prefix = g_strconcat("wireshark_pcapng_", basename, NULL);
3305 prefix = g_strconcat("wireshark_pcap_", basename, NULL);
3309 *save_file_fd = create_tempfile(&tmpname, prefix);
3311 capfile_name = g_strdup(tmpname);
3315 /* did we fail to open the output file? */
3316 if (*save_file_fd == -1) {
3318 g_snprintf(errmsg, errmsg_len,
3319 "The temporary file to which the capture would be saved (\"%s\") "
3320 "could not be opened: %s.", capfile_name, g_strerror(errno));
3322 if (capture_opts->multi_files_on) {
3323 ringbuf_error_cleanup();
3326 g_snprintf(errmsg, errmsg_len,
3327 "The file to which the capture would be saved (\"%s\") "
3328 "could not be opened: %s.", capfile_name,
3331 g_free(capfile_name);
3335 if (capture_opts->save_file != NULL) {
3336 g_free(capture_opts->save_file);
3338 capture_opts->save_file = capfile_name;
3339 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3340 "g_free(capfile_name)". */
3346 /* Do the work of handling either the file size or file duration capture
3347 conditions being reached, and switching files or stopping. */
3349 do_file_switch_or_stop(capture_options *capture_opts,
3350 condition *cnd_autostop_files,
3351 condition *cnd_autostop_size,
3352 condition *cnd_file_duration)
3355 pcap_options *pcap_opts;
3356 interface_options interface_opts;
3357 gboolean successful;
3359 if (capture_opts->multi_files_on) {
3360 if (cnd_autostop_files != NULL &&
3361 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
3362 /* no files left: stop here */
3363 global_ld.go = FALSE;
3367 /* Switch to the next ringbuffer file */
3368 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3369 &global_ld.save_file_fd, &global_ld.err)) {
3371 /* File switch succeeded: reset the conditions */
3372 global_ld.bytes_written = 0;
3373 if (capture_opts->use_pcapng) {
3375 GString *os_info_str;
3377 os_info_str = g_string_new("");
3378 get_os_version_info(os_info_str);
3380 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
3381 successful = pcapng_write_session_header_block(global_ld.pdh,
3384 os_info_str->str, /* OS */
3386 -1, /* section_length */
3387 &(global_ld.bytes_written),
3391 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3392 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3393 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3394 successful = pcapng_write_interface_description_block(global_ld.pdh,
3395 NULL, /* OPT_COMMENT 1 */
3396 interface_opts.name, /* IDB_NAME 2 */
3397 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3398 interface_opts.cfilter, /* IDB_FILTER 11 */
3399 os_info_str->str, /* IDB_OS 12 */
3400 pcap_opts->linktype,
3402 &(global_ld.bytes_written),
3403 0, /* IDB_IF_SPEED 8 */
3404 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3408 g_string_free(os_info_str, TRUE);
3411 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3412 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3413 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3416 fclose(global_ld.pdh);
3417 global_ld.pdh = NULL;
3418 global_ld.go = FALSE;
3421 if (cnd_autostop_size)
3422 cnd_reset(cnd_autostop_size);
3423 if (cnd_file_duration)
3424 cnd_reset(cnd_file_duration);
3425 fflush(global_ld.pdh);
3427 report_packet_count(global_ld.inpkts_to_sync_pipe);
3428 global_ld.inpkts_to_sync_pipe = 0;
3429 report_new_capture_file(capture_opts->save_file);
3431 /* File switch failed: stop here */
3432 global_ld.go = FALSE;
3436 /* single file, stop now */
3437 global_ld.go = FALSE;
3444 pcap_read_handler(void* arg)
3446 pcap_options *pcap_opts;
3447 char errmsg[MSG_MAX_LENGTH+1];
3449 pcap_opts = (pcap_options *)arg;
3451 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3452 pcap_opts->interface_id);
3454 while (global_ld.go) {
3455 /* dispatch incoming packets */
3456 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3458 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3459 pcap_opts->interface_id);
3460 g_thread_exit(NULL);
3464 /* Do the low-level work of a capture.
3465 Returns TRUE if it succeeds, FALSE otherwise. */
3467 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3470 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3472 struct timeval upd_time, cur_time;
3476 condition *cnd_file_duration = NULL;
3477 condition *cnd_autostop_files = NULL;
3478 condition *cnd_autostop_size = NULL;
3479 condition *cnd_autostop_duration = NULL;
3482 gboolean cfilter_error = FALSE;
3483 char errmsg[MSG_MAX_LENGTH+1];
3484 char secondary_errmsg[MSG_MAX_LENGTH+1];
3485 pcap_options *pcap_opts;
3486 interface_options interface_opts;
3487 guint i, error_index = 0;
3490 *secondary_errmsg = '\0';
3492 /* init the loop data */
3493 global_ld.go = TRUE;
3494 global_ld.packet_count = 0;
3496 global_ld.report_packet_count = FALSE;
3498 if (capture_opts->has_autostop_packets)
3499 global_ld.packet_max = capture_opts->autostop_packets;
3501 global_ld.packet_max = 0; /* no limit */
3502 global_ld.inpkts_to_sync_pipe = 0;
3503 global_ld.err = 0; /* no error seen yet */
3504 global_ld.pdh = NULL;
3505 global_ld.autostop_files = 0;
3506 global_ld.save_file_fd = -1;
3508 /* We haven't yet gotten the capture statistics. */
3509 *stats_known = FALSE;
3511 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3512 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3514 /* open the "input file" from network interface or capture pipe */
3515 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3516 secondary_errmsg, sizeof(secondary_errmsg))) {
3519 for (i = 0; i < capture_opts->ifaces->len; i++) {
3520 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3521 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3522 /* init the input filter from the network interface (capture pipe will do nothing) */
3524 * When remote capturing WinPCap crashes when the capture filter
3525 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3528 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3529 interface_opts.name,
3530 interface_opts.cfilter?interface_opts.cfilter:"")) {
3532 case INITFILTER_NO_ERROR:
3535 case INITFILTER_BAD_FILTER:
3536 cfilter_error = TRUE;
3538 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3541 case INITFILTER_OTHER_ERROR:
3542 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3543 pcap_geterr(pcap_opts->pcap_h));
3544 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3549 /* If we're supposed to write to a capture file, open it for output
3550 (temporary/specified name/ringbuffer) */
3551 if (capture_opts->saving_to_file) {
3552 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3553 errmsg, sizeof(errmsg))) {
3557 /* set up to write to the already-opened capture output file/files */
3558 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3563 /* XXX - capture SIGTERM and close the capture, in case we're on a
3564 Linux 2.0[.x] system and you have to explicitly close the capture
3565 stream in order to turn promiscuous mode off? We need to do that
3566 in other places as well - and I don't think that works all the
3567 time in any case, due to libpcap bugs. */
3569 /* Well, we should be able to start capturing.
3571 Sync out the capture file, so the header makes it to the file system,
3572 and send a "capture started successfully and capture file created"
3573 message to our parent so that they'll open the capture file and
3574 update its windows to indicate that we have a live capture in
3576 fflush(global_ld.pdh);
3577 report_new_capture_file(capture_opts->save_file);
3580 /* initialize capture stop (and alike) conditions */
3581 init_capture_stop_conditions();
3582 /* create stop conditions */
3583 if (capture_opts->has_autostop_filesize) {
3584 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3585 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3588 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3590 if (capture_opts->has_autostop_duration)
3591 cnd_autostop_duration =
3592 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3594 if (capture_opts->multi_files_on) {
3595 if (capture_opts->has_file_duration)
3597 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3599 if (capture_opts->has_autostop_files)
3600 cnd_autostop_files =
3601 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3604 /* init the time values */
3606 upd_time = GetTickCount();
3608 gettimeofday(&upd_time, NULL);
3610 start_time = create_timestamp();
3611 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3613 /* WOW, everything is prepared! */
3614 /* please fasten your seat belts, we will enter now the actual capture loop */
3616 pcap_queue = g_async_queue_new();
3617 pcap_queue_bytes = 0;
3618 pcap_queue_packets = 0;
3619 for (i = 0; i < global_ld.pcaps->len; i++) {
3620 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3621 #if GLIB_CHECK_VERSION(2,31,0)
3622 /* XXX - Add an interface name here? */
3623 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3625 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3629 while (global_ld.go) {
3630 /* dispatch incoming packets */
3632 pcap_queue_element *queue_element;
3633 #if GLIB_CHECK_VERSION(2,31,18)
3635 g_async_queue_lock(pcap_queue);
3636 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3638 GTimeVal write_thread_time;
3640 g_get_current_time(&write_thread_time);
3641 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3642 g_async_queue_lock(pcap_queue);
3643 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3645 if (queue_element) {
3646 pcap_queue_bytes -= queue_element->phdr.caplen;
3647 pcap_queue_packets -= 1;
3649 g_async_queue_unlock(pcap_queue);
3650 if (queue_element) {
3651 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3652 "Dequeued a packet of length %d captured on interface %d.",
3653 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3655 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3656 &queue_element->phdr,
3658 g_free(queue_element->pd);
3659 g_free(queue_element);
3665 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3666 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3667 sizeof(errmsg), pcap_opts);
3670 /* Were we asked to print packet counts by the SIGINFO handler? */
3671 if (global_ld.report_packet_count) {
3672 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3673 plurality(global_ld.packet_count, "", "s"));
3674 global_ld.report_packet_count = FALSE;
3679 /* any news from our parent (signal pipe)? -> just stop the capture */
3680 if (!signal_pipe_check_running()) {
3681 global_ld.go = FALSE;
3686 global_ld.inpkts_to_sync_pipe += inpkts;
3688 /* check capture size condition */
3689 if (cnd_autostop_size != NULL &&
3690 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3691 /* Capture size limit reached, do we have another file? */
3692 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3693 cnd_autostop_size, cnd_file_duration))
3695 } /* cnd_autostop_size */
3696 if (capture_opts->output_to_pipe) {
3697 fflush(global_ld.pdh);
3701 /* Only update once every 500ms so as not to overload slow displays.
3702 * This also prevents too much context-switching between the dumpcap
3703 * and wireshark processes.
3705 #define DUMPCAP_UPD_TIME 500
3708 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3709 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3711 gettimeofday(&cur_time, NULL);
3712 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3713 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3716 upd_time = cur_time;
3719 if (pcap_stats(pch, stats) >= 0) {
3720 *stats_known = TRUE;
3723 /* Let the parent process know. */
3724 if (global_ld.inpkts_to_sync_pipe) {
3726 fflush(global_ld.pdh);
3728 /* Send our parent a message saying we've written out
3729 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3731 report_packet_count(global_ld.inpkts_to_sync_pipe);
3733 global_ld.inpkts_to_sync_pipe = 0;
3736 /* check capture duration condition */
3737 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3738 /* The maximum capture time has elapsed; stop the capture. */
3739 global_ld.go = FALSE;
3743 /* check capture file duration condition */
3744 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3745 /* duration limit reached, do we have another file? */
3746 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3747 cnd_autostop_size, cnd_file_duration))
3749 } /* cnd_file_duration */
3753 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3755 pcap_queue_element *queue_element;
3757 for (i = 0; i < global_ld.pcaps->len; i++) {
3758 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3759 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3760 pcap_opts->interface_id);
3761 g_thread_join(pcap_opts->tid);
3762 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3763 pcap_opts->interface_id);
3766 g_async_queue_lock(pcap_queue);
3767 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3768 if (queue_element) {
3769 pcap_queue_bytes -= queue_element->phdr.caplen;
3770 pcap_queue_packets -= 1;
3772 g_async_queue_unlock(pcap_queue);
3773 if (queue_element == NULL) {
3776 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3777 "Dequeued a packet of length %d captured on interface %d.",
3778 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3779 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3780 &queue_element->phdr,
3782 g_free(queue_element->pd);
3783 g_free(queue_element);
3784 global_ld.inpkts_to_sync_pipe += 1;
3785 if (capture_opts->output_to_pipe) {
3786 fflush(global_ld.pdh);
3792 /* delete stop conditions */
3793 if (cnd_file_duration != NULL)
3794 cnd_delete(cnd_file_duration);
3795 if (cnd_autostop_files != NULL)
3796 cnd_delete(cnd_autostop_files);
3797 if (cnd_autostop_size != NULL)
3798 cnd_delete(cnd_autostop_size);
3799 if (cnd_autostop_duration != NULL)
3800 cnd_delete(cnd_autostop_duration);
3802 /* did we have a pcap (input) error? */
3803 for (i = 0; i < capture_opts->ifaces->len; i++) {
3804 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3805 if (pcap_opts->pcap_err) {
3806 /* On Linux, if an interface goes down while you're capturing on it,
3807 you'll get a "recvfrom: Network is down" or
3808 "The interface went down" error (ENETDOWN).
3809 (At least you will if g_strerror() doesn't show a local translation
3812 On FreeBSD and OS X, if a network adapter disappears while
3813 you're capturing on it, you'll get a "read: Device not configured"
3814 error (ENXIO). (See previous parenthetical note.)
3816 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3818 These should *not* be reported to the Wireshark developers. */
3821 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3822 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3823 strcmp(cap_err_str, "The interface went down") == 0 ||
3824 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3825 strcmp(cap_err_str, "read: I/O error") == 0 ||
3826 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3827 report_capture_error("The network adapter on which the capture was being done "
3828 "is no longer running; the capture has stopped.",
3831 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3833 report_capture_error(errmsg, please_report);
3836 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3837 report_capture_error(errmsg, "");
3841 /* did we have an output error while capturing? */
3842 if (global_ld.err == 0) {
3845 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3846 global_ld.err, FALSE);
3847 report_capture_error(errmsg, please_report);
3851 if (capture_opts->saving_to_file) {
3852 /* close the output file */
3853 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3857 /* there might be packets not yet notified to the parent */
3858 /* (do this after closing the file, so all packets are already flushed) */
3859 if (global_ld.inpkts_to_sync_pipe) {
3861 report_packet_count(global_ld.inpkts_to_sync_pipe);
3862 global_ld.inpkts_to_sync_pipe = 0;
3865 /* If we've displayed a message about a write error, there's no point
3866 in displaying another message about an error on close. */
3867 if (!close_ok && write_ok) {
3868 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3870 report_capture_error(errmsg, "");
3874 * XXX We exhibit different behaviour between normal mode and sync mode
3875 * when the pipe is stdin and not already at EOF. If we're a child, the
3876 * parent's stdin isn't closed, so if the user starts another capture,
3877 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3878 * will say "Unrecognized libpcap format". On the other hand, in normal
3879 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3882 report_capture_count(TRUE);
3884 /* get packet drop statistics from pcap */
3885 for (i = 0; i < capture_opts->ifaces->len; i++) {
3887 guint32 pcap_dropped = 0;
3889 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3890 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3891 received = pcap_opts->received;
3892 if (pcap_opts->pcap_h != NULL) {
3893 g_assert(!pcap_opts->from_cap_pipe);
3894 /* Get the capture statistics, so we know how many packets were dropped. */
3896 * Older versions of libpcap didn't set ps_ifdrop on some
3897 * platforms; initialize it to 0 to handle that.
3899 stats->ps_ifdrop = 0;
3900 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3901 *stats_known = TRUE;
3902 /* Let the parent process know. */
3903 pcap_dropped += stats->ps_drop;
3905 g_snprintf(errmsg, sizeof(errmsg),
3906 "Can't get packet-drop statistics: %s",
3907 pcap_geterr(pcap_opts->pcap_h));
3908 report_capture_error(errmsg, please_report);
3911 report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
3914 /* close the input file (pcap or capture pipe) */
3915 capture_loop_close_input(&global_ld);
3917 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
3919 /* ok, if the write and the close were successful. */
3920 return write_ok && close_ok;
3923 if (capture_opts->multi_files_on) {
3924 /* cleanup ringbuffer */
3925 ringbuf_error_cleanup();
3927 /* We can't use the save file, and we have no FILE * for the stream
3928 to close in order to close it, so close the FD directly. */
3929 if (global_ld.save_file_fd != -1) {
3930 ws_close(global_ld.save_file_fd);
3933 /* We couldn't even start the capture, so get rid of the capture
3935 if (capture_opts->save_file != NULL) {
3936 ws_unlink(capture_opts->save_file);
3937 g_free(capture_opts->save_file);
3940 capture_opts->save_file = NULL;
3942 report_cfilter_error(capture_opts, error_index, errmsg);
3944 report_capture_error(errmsg, secondary_errmsg);
3946 /* close the input file (pcap or cap_pipe) */
3947 capture_loop_close_input(&global_ld);
3949 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3956 capture_loop_stop(void)
3958 #ifdef HAVE_PCAP_BREAKLOOP
3960 pcap_options *pcap_opts;
3962 for (i = 0; i < global_ld.pcaps->len; i++) {
3963 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3964 if (pcap_opts->pcap_h != NULL)
3965 pcap_breakloop(pcap_opts->pcap_h);
3968 global_ld.go = FALSE;
3973 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3974 int err, gboolean is_close)
3979 g_snprintf(errmsg, errmsglen,
3980 "Not all the packets could be written to the file"
3981 " to which the capture was being saved\n"
3982 "(\"%s\") because there is no space left on the file system\n"
3983 "on which that file resides.",
3989 g_snprintf(errmsg, errmsglen,
3990 "Not all the packets could be written to the file"
3991 " to which the capture was being saved\n"
3992 "(\"%s\") because you are too close to, or over,"
3993 " your disk quota\n"
3994 "on the file system on which that file resides.",
4001 g_snprintf(errmsg, errmsglen,
4002 "The file to which the capture was being saved\n"
4003 "(\"%s\") could not be closed: %s.",
4004 fname, g_strerror(err));
4006 g_snprintf(errmsg, errmsglen,
4007 "An error occurred while writing to the file"
4008 " to which the capture was being saved\n"
4010 fname, g_strerror(err));
4017 /* one packet was captured, process it */
4019 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4022 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4024 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
4026 /* We may be called multiple times from pcap_dispatch(); if we've set
4027 the "stop capturing" flag, ignore this packet, as we're not
4028 supposed to be saving any more packets. */
4029 if (!global_ld.go) {
4030 pcap_opts->flushed++;
4034 if (global_ld.pdh) {
4035 gboolean successful;
4037 /* We're supposed to write the packet to a file; do so.
4038 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4039 "ld->err" to the error. */
4040 if (global_capture_opts.use_pcapng) {
4041 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4043 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4044 phdr->caplen, phdr->len,
4045 pcap_opts->interface_id,
4048 &global_ld.bytes_written, &err);
4050 successful = libpcap_write_packet(global_ld.pdh,
4051 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4052 phdr->caplen, phdr->len,
4054 &global_ld.bytes_written, &err);
4057 global_ld.go = FALSE;
4058 global_ld.err = err;
4059 pcap_opts->dropped++;
4061 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4062 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4063 "Wrote a packet of length %d captured on interface %u.",
4064 phdr->caplen, pcap_opts->interface_id);
4066 global_ld.packet_count++;
4067 pcap_opts->received++;
4068 /* if the user told us to stop after x packets, do we already have enough? */
4069 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4070 global_ld.go = FALSE;
4076 /* one packet was captured, queue it */
4078 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4081 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4082 pcap_queue_element *queue_element;
4083 gboolean limit_reached;
4085 /* We may be called multiple times from pcap_dispatch(); if we've set
4086 the "stop capturing" flag, ignore this packet, as we're not
4087 supposed to be saving any more packets. */
4088 if (!global_ld.go) {
4089 pcap_opts->flushed++;
4093 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4094 if (queue_element == NULL) {
4095 pcap_opts->dropped++;
4098 queue_element->pcap_opts = pcap_opts;
4099 queue_element->phdr = *phdr;
4100 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4101 if (queue_element->pd == NULL) {
4102 pcap_opts->dropped++;
4103 g_free(queue_element);
4106 memcpy(queue_element->pd, pd, phdr->caplen);
4107 g_async_queue_lock(pcap_queue);
4108 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4109 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4110 limit_reached = FALSE;
4111 g_async_queue_push_unlocked(pcap_queue, queue_element);
4112 pcap_queue_bytes += phdr->caplen;
4113 pcap_queue_packets += 1;
4115 limit_reached = TRUE;
4117 g_async_queue_unlock(pcap_queue);
4118 if (limit_reached) {
4119 pcap_opts->dropped++;
4120 g_free(queue_element->pd);
4121 g_free(queue_element);
4122 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4123 "Dropped a packet of length %d captured on interface %u.",
4124 phdr->caplen, pcap_opts->interface_id);
4126 pcap_opts->received++;
4127 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4128 "Queued a packet of length %d captured on interface %u.",
4129 phdr->caplen, pcap_opts->interface_id);
4131 /* I don't want to hold the mutex over the debug output. So the
4132 output may be wrong */
4133 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4134 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4135 pcap_queue_bytes, pcap_queue_packets);
4139 set_80211_channel(const char *iface, const char *opt)
4141 int freq = 0, type, ret;
4142 gchar **options = NULL;
4144 options = g_strsplit_set(opt, ",", 2);
4147 freq = atoi(options[0]);
4150 type = ws80211_str_to_chan_type(options[1]);
4159 ret = ws80211_init();
4161 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4165 ret = ws80211_set_freq(iface, freq, type);
4168 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4174 pipe_write_block(2, SP_SUCCESS, NULL);
4178 g_strfreev(options);
4183 get_dumpcap_compiled_info(GString *str)
4185 /* Capture libraries */
4186 g_string_append(str, ", ");
4187 get_compiled_caplibs_version(str);
4190 g_string_append(str, ", ");
4192 g_string_append(str, "with libz ");
4194 g_string_append(str, ZLIB_VERSION);
4195 #else /* ZLIB_VERSION */
4196 g_string_append(str, "(version unknown)");
4197 #endif /* ZLIB_VERSION */
4198 #else /* HAVE_LIBZ */
4199 g_string_append(str, "without libz");
4200 #endif /* HAVE_LIBZ */
4204 get_dumpcap_runtime_info(GString *str)
4206 /* Capture libraries */
4207 g_string_append(str, ", ");
4208 get_runtime_caplibs_version(str);
4211 #if defined(HAVE_LIBZ) && !defined(_WIN32)
4212 g_string_append_printf(str, ", with libz %s", zlibVersion());
4216 /* And now our feature presentation... [ fade to music ] */
4218 main(int argc, char *argv[])
4220 GString *comp_info_str;
4221 GString *runtime_info_str;
4224 static const struct option long_options[] = {
4225 {(char *)"help", no_argument, NULL, 'h'},
4226 {(char *)"version", no_argument, NULL, 'v'},
4227 LONGOPT_CAPTURE_COMMON
4232 gboolean arg_error = FALSE;
4237 struct sigaction action, oldaction;
4240 gboolean start_capture = TRUE;
4241 gboolean stats_known;
4242 struct pcap_stat stats;
4243 GLogLevelFlags log_flags;
4244 gboolean list_interfaces = FALSE;
4245 gboolean list_link_layer_types = FALSE;
4246 #ifdef HAVE_BPF_IMAGE
4247 gboolean print_bpf_code = FALSE;
4249 gboolean set_chan = FALSE;
4250 gchar *set_chan_arg = NULL;
4251 gboolean machine_readable = FALSE;
4252 gboolean print_statistics = FALSE;
4253 int status, run_once_args = 0;
4256 #if defined(__APPLE__) && defined(__LP64__)
4257 struct utsname osinfo;
4261 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
4263 /* Get the compile-time version information string */
4264 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4266 /* Get the run-time version information string */
4267 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4269 /* Add it to the information to be reported on a crash. */
4270 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
4275 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
4278 arg_list_utf_16to8(argc, argv);
4279 create_app_running_mutex();
4282 * Initialize our DLL search path. MUST be called before LoadLibrary
4285 ws_init_dll_search_path();
4288 #ifdef HAVE_BPF_IMAGE
4289 #define OPTSTRING_d "d"
4291 #define OPTSTRING_d ""
4294 #ifdef HAVE_PCAP_REMOTE
4295 #define OPTSTRING_r "r"
4296 #define OPTSTRING_u "u"
4298 #define OPTSTRING_r ""
4299 #define OPTSTRING_u ""
4302 #ifdef HAVE_PCAP_SETSAMPLING
4303 #define OPTSTRING_m "m:"
4305 #define OPTSTRING_m ""
4308 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
4310 #ifdef DEBUG_CHILD_DUMPCAP
4311 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4312 fprintf (stderr, "Unable to open debug log file .\n");
4317 #if defined(__APPLE__) && defined(__LP64__)
4319 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4320 * a bug workaround - timeouts less than 1 second don't work with libpcap
4321 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4322 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4323 * The problem is extremely unlikely to be reintroduced in a future
4326 if (uname(&osinfo) == 0) {
4328 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
4329 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4330 * number of 10.0.0, not 10.1.0 - go figure).
4332 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4333 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4334 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4335 need_timeout_workaround = TRUE;
4340 * Determine if dumpcap is being requested to run in a special
4341 * capture_child mode by going thru the command line args to see if
4342 * a -Z is present. (-Z is a hidden option).
4344 * The primary result of running in capture_child mode is that
4345 * all messages sent out on stderr are in a special type/len/string
4346 * format to allow message processing by type. These messages include
4347 * error messages if dumpcap fails to start the operation it was
4348 * requested to do, as well as various "status" messages which are sent
4349 * when an actual capture is in progress, and a "success" message sent
4350 * if dumpcap was requested to perform an operation other than a
4353 * Capture_child mode would normally be requested by a parent process
4354 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4355 * to which dumpcap stderr has been redirected. It might also have
4356 * another pipe to obtain dumpcap stdout output; for operations other
4357 * than a capture, that information is formatted specially for easier
4358 * parsing by the parent process.
4360 * Capture_child mode needs to be determined immediately upon
4361 * startup so that any messages generated by dumpcap in this mode
4362 * (eg: during initialization) will be formatted properly.
4365 for (i=1; i<argc; i++) {
4366 if (strcmp("-Z", argv[i]) == 0) {
4367 capture_child = TRUE;
4368 machine_readable = TRUE; /* request machine-readable output */
4370 /* set output pipe to binary mode, to avoid ugly text conversions */
4371 _setmode(2, O_BINARY);
4376 /* The default_log_handler will use stdout, which makes trouble in */
4377 /* capture child mode, as it uses stdout for its sync_pipe. */
4378 /* So: the filtering is done in the console_log_handler and not here.*/
4379 /* We set the log handlers right up front to make sure that any log */
4380 /* messages when running as child will be sent back to the parent */
4381 /* with the correct format. */
4386 G_LOG_LEVEL_CRITICAL|
4387 G_LOG_LEVEL_WARNING|
4388 G_LOG_LEVEL_MESSAGE|
4392 G_LOG_FLAG_RECURSION);
4394 g_log_set_handler(NULL,
4396 console_log_handler, NULL /* user_data */);
4397 g_log_set_handler(LOG_DOMAIN_MAIN,
4399 console_log_handler, NULL /* user_data */);
4400 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4402 console_log_handler, NULL /* user_data */);
4403 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4405 console_log_handler, NULL /* user_data */);
4407 /* Initialize the pcaps list */
4408 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
4410 #if !GLIB_CHECK_VERSION(2,31,0)
4411 /* Initialize the thread system */
4412 g_thread_init(NULL);
4416 /* Load wpcap if possible. Do this before collecting the run-time version information */
4419 /* ... and also load the packet.dll from wpcap */
4420 /* XXX - currently not required, may change later. */
4421 /*wpcap_packet_load();*/
4423 /* Start windows sockets */
4424 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4426 /* Set handler for Ctrl+C key */
4427 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4429 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4430 and exit. Do the same with SIGPIPE, in case, for example,
4431 we're writing to our standard output and it's a pipe.
4432 Do the same with SIGHUP if it's not being ignored (if we're
4433 being run under nohup, it might be ignored, in which case we
4434 should leave it ignored).
4436 XXX - apparently, Coverity complained that part of action
4437 wasn't initialized. Perhaps it's running on Linux, where
4438 struct sigaction has an ignored "sa_restorer" element and
4439 where "sa_handler" and "sa_sigaction" might not be two
4440 members of a union. */
4441 memset(&action, 0, sizeof(action));
4442 action.sa_handler = capture_cleanup_handler;
4444 * Arrange that system calls not get restarted, because when
4445 * our signal handler returns we don't want to restart
4446 * a call that was waiting for packets to arrive.
4448 action.sa_flags = 0;
4449 sigemptyset(&action.sa_mask);
4450 sigaction(SIGTERM, &action, NULL);
4451 sigaction(SIGINT, &action, NULL);
4452 sigaction(SIGPIPE, &action, NULL);
4453 sigaction(SIGHUP, NULL, &oldaction);
4454 if (oldaction.sa_handler == SIG_DFL)
4455 sigaction(SIGHUP, &action, NULL);
4458 /* Catch SIGINFO and, if we get it and we're capturing in
4459 quiet mode, report the number of packets we've captured. */
4460 action.sa_handler = report_counts_siginfo;
4461 action.sa_flags = SA_RESTART;
4462 sigemptyset(&action.sa_mask);
4463 sigaction(SIGINFO, &action, NULL);
4464 #endif /* SIGINFO */
4468 enable_kernel_bpf_jit_compiler();
4471 /* ----------------------------------------------------------------- */
4472 /* Privilege and capability handling */
4474 /* 1. Running not as root or suid root; no special capabilities. */
4477 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4480 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4482 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4483 /* capabilities; Drop all other capabilities; */
4484 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4485 /* else: after pcap_open_live() in capture_loop_open_input() */
4486 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4487 /* (Note: this means that the process, although logged in */
4488 /* as root, does not have various permissions such as the */
4489 /* ability to bypass file access permissions). */
4490 /* XXX: Should we just leave capabilities alone in this case */
4491 /* so that user gets expected effect that root can do */
4494 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4496 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4497 /* else: after pcap_open_live() in capture_loop_open_input() */
4498 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4499 /* pcap_open_live). */
4501 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4503 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4504 /* capabilities; Drop all other capabilities; */
4505 /* Drop suid privileges (euid=ruid); */
4506 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4507 /* else: after pcap_open_live() in capture_loop_open_input() */
4508 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4510 /* XXX: For some Linux versions/distros with capabilities */
4511 /* a 'normal' process with any capabilities cannot be */
4512 /* 'killed' (signaled) from another (same uid) non-privileged */
4514 /* For example: If (non-suid) Wireshark forks a */
4515 /* child suid dumpcap which acts as described here (case 5), */
4516 /* Wireshark will be unable to kill (signal) the child */
4517 /* dumpcap process until the capabilities have been dropped */
4518 /* (after pcap_open_live()). */
4519 /* This behaviour will apparently be changed in the kernel */
4520 /* to allow the kill (signal) in this case. */
4521 /* See the following for details: */
4522 /* https://www.mail-archive.com/ [wrapped] */
4523 /* linux-security-module@vger.kernel.org/msg02913.html */
4525 /* It is therefore conceivable that if dumpcap somehow hangs */
4526 /* in pcap_open_live or before that wireshark will not */
4527 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4528 /* In this case, exiting wireshark will kill the child */
4529 /* dumpcap process. */
4531 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4532 /* capabilities; Using libcap. Note: capset cmd (which see) */
4533 /* used to assign capabilities to file. */
4535 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4536 /* else: after pcap_open_live() in capture_loop_open_input() */
4537 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4539 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4540 /* longer required (similar to capture). */
4542 /* ----------------------------------------------------------------- */
4544 init_process_policies();
4547 /* If 'started with special privileges' (and using libcap) */
4548 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4549 /* Set euid/egid = ruid/rgid to remove suid privileges */
4550 relinquish_privs_except_capture();
4553 /* Set the initial values in the capture options. This might be overwritten
4554 by the command line parameters. */
4555 capture_opts_init(&global_capture_opts);
4556 /* We always save to a file - if no file was specified, we save to a
4558 global_capture_opts.saving_to_file = TRUE;
4559 global_capture_opts.has_ring_num_files = TRUE;
4561 /* Pass on capture_child mode for capture_opts */
4562 global_capture_opts.capture_child = capture_child;
4564 /* Now get our args */
4565 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4567 case 'h': /* Print help and exit */
4568 printf("Dumpcap (Wireshark) %s\n"
4569 "Capture network packets and dump them into a pcapng or pcap file.\n"
4570 "See https://www.wireshark.org for more information.\n",
4571 get_ws_vcs_version_info());
4572 print_usage(stdout);
4575 case 'v': /* Show version and exit */
4577 show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4578 g_string_free(comp_info_str, TRUE);
4579 g_string_free(runtime_info_str, TRUE);
4583 /*** capture option specific ***/
4584 case 'a': /* autostop criteria */
4585 case 'b': /* Ringbuffer option */
4586 case 'c': /* Capture x packets */
4587 case 'f': /* capture filter */
4588 case 'g': /* enable group read access on file(s) */
4589 case 'i': /* Use interface x */
4590 case 'n': /* Use pcapng format */
4591 case 'p': /* Don't capture in promiscuous mode */
4592 case 'P': /* Use pcap format */
4593 case 's': /* Set the snapshot (capture) length */
4594 case 'w': /* Write to capture file x */
4595 case 'y': /* Set the pcap data link type */
4596 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4597 #ifdef HAVE_PCAP_REMOTE
4598 case 'u': /* Use UDP for data transfer */
4599 case 'r': /* Capture own RPCAP traffic too */
4600 case 'A': /* Authentication */
4602 #ifdef HAVE_PCAP_SETSAMPLING
4603 case 'm': /* Sampling */
4605 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4606 case 'B': /* Buffer size */
4607 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4608 #ifdef HAVE_PCAP_CREATE
4609 case 'I': /* Monitor mode */
4611 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4616 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4618 capture_child = TRUE;
4620 /* set output pipe to binary mode, to avoid ugly text conversions */
4621 _setmode(2, O_BINARY);
4623 * optarg = the control ID, aka the PPID, currently used for the
4626 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4627 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4628 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4629 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4631 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4632 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4633 "Signal pipe: Unable to open %s. Dead parent?",
4641 case 'q': /* Quiet */
4647 /*** all non capture option specific ***/
4648 case 'D': /* Print a list of capture devices and exit */
4649 list_interfaces = TRUE;
4652 case 'L': /* Print list of link-layer types and exit */
4653 list_link_layer_types = TRUE;
4656 #ifdef HAVE_BPF_IMAGE
4657 case 'd': /* Print BPF code for capture filter and exit */
4658 print_bpf_code = TRUE;
4662 case 'S': /* Print interface statistics once a second */
4663 print_statistics = TRUE;
4666 case 'k': /* Set wireless channel */
4668 set_chan_arg = optarg;
4671 case 'M': /* For -D, -L, and -S, print machine-readable output */
4672 machine_readable = TRUE;
4675 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4678 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4681 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4683 case '?': /* Bad flag - print usage message */
4692 /* user specified file name as regular command-line argument */
4693 /* XXX - use it as the capture file name (or something else)? */
4699 * Extra command line arguments were specified; complain.
4700 * XXX - interpret as capture filter, as tcpdump and tshark do?
4702 cmdarg_err("Invalid argument: %s", argv[0]);
4707 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4710 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4711 /* Use some default if the user hasn't specified some */
4712 /* XXX: Are these defaults good enough? */
4713 pcap_queue_byte_limit = 1000 * 1000;
4714 pcap_queue_packet_limit = 1000;
4717 print_usage(stderr);
4721 if (run_once_args > 1) {
4722 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4724 } else if (run_once_args == 1) {
4725 /* We're supposed to print some information, rather than
4726 to capture traffic; did they specify a ring buffer option? */
4727 if (global_capture_opts.multi_files_on) {
4728 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4732 /* We're supposed to capture traffic; */
4734 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4735 if (global_capture_opts.ifaces->len > 1) {
4737 global_capture_opts.use_pcapng = TRUE;
4740 if (global_capture_opts.capture_comment &&
4741 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4742 /* XXX - for ringbuffer, should we apply the comment to each file? */
4743 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4747 /* Was the ring buffer option specified and, if so, does it make sense? */
4748 if (global_capture_opts.multi_files_on) {
4749 /* Ring buffer works only under certain conditions:
4750 a) ring buffer does not work with temporary files;
4751 b) it makes no sense to enable the ring buffer if the maximum
4752 file size is set to "infinite". */
4753 if (global_capture_opts.save_file == NULL) {
4754 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4755 global_capture_opts.multi_files_on = FALSE;
4757 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4758 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4760 /* XXX - this must be redesigned as the conditions changed */
4761 global_capture_opts.multi_files_on = FALSE;
4768 * "-D" requires no interface to be selected; it's supposed to list
4771 if (list_interfaces) {
4772 /* Get the list of interfaces */
4777 if_list = capture_interface_list(&err, &err_str,NULL);
4778 if (if_list == NULL) {
4781 * If we're being run by another program, just give them
4782 * an empty list of interfaces, don't report this as
4783 * an error; that lets them decide whether to report
4784 * this as an error or not.
4786 if (!machine_readable) {
4787 cmdarg_err("There are no interfaces on which a capture can be done");
4791 cmdarg_err("%s", err_str);
4797 if (machine_readable) /* tab-separated values to stdout */
4798 print_machine_readable_interfaces(if_list);
4800 capture_opts_print_interfaces(if_list);
4801 free_interface_list(if_list);
4806 * "-S" requires no interface to be selected; it gives statistics
4807 * for all interfaces.
4809 if (print_statistics) {
4810 status = print_statistics_loop(machine_readable);
4815 interface_options interface_opts;
4817 if (global_capture_opts.ifaces->len != 1) {
4818 cmdarg_err("Need one interface");
4822 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4823 status = set_80211_channel(interface_opts.name, set_chan_arg);
4828 * "-L", "-d", and capturing act on a particular interface, so we have to
4829 * have an interface; if none was specified, pick a default.
4831 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4833 /* cmdarg_err() already called .... */
4837 /* Let the user know what interfaces were chosen. */
4838 if (capture_child) {
4839 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4840 interface_options interface_opts;
4842 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4843 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4844 interface_opts.name);
4847 str = g_string_new("");
4849 if (global_capture_opts.ifaces->len < 2)
4851 if (global_capture_opts.ifaces->len < 4)
4854 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4855 interface_options interface_opts;
4857 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4859 if (global_capture_opts.ifaces->len > 2) {
4860 g_string_append_printf(str, ",");
4862 g_string_append_printf(str, " ");
4863 if (j == global_capture_opts.ifaces->len - 1) {
4864 g_string_append_printf(str, "and ");
4867 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4870 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4872 fprintf(stderr, "Capturing on %s\n", str->str);
4873 g_string_free(str, TRUE);
4876 if (list_link_layer_types) {
4877 /* Get the list of link-layer types for the capture device. */
4878 if_capabilities_t *caps;
4882 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4883 interface_options interface_opts;
4885 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4887 caps = get_if_capabilities(interface_opts.name,
4888 interface_opts.monitor_mode, &err_str);
4890 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4891 "Please check to make sure you have sufficient permissions, and that\n"
4892 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4896 if (caps->data_link_types == NULL) {
4897 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4900 if (machine_readable) /* tab-separated values to stdout */
4901 /* XXX: We need to change the format and adopt consumers */
4902 print_machine_readable_if_capabilities(caps);
4904 /* XXX: We might want to print also the interface name */
4905 capture_opts_print_if_capabilities(caps, interface_opts.name,
4906 interface_opts.monitor_mode);
4907 free_if_capabilities(caps);
4912 /* We're supposed to do a capture, or print the BPF code for a filter.
4913 Process the snapshot length, as that affects the generated BPF code. */
4914 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4916 #ifdef HAVE_BPF_IMAGE
4917 if (print_bpf_code) {
4918 show_filter_code(&global_capture_opts);
4923 /* We're supposed to do a capture. Process the ring buffer arguments. */
4924 capture_opts_trim_ring_num_files(&global_capture_opts);
4926 /* flush stderr prior to starting the main capture loop */
4929 /* Now start the capture. */
4930 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4934 /* capture failed */
4937 return 0; /* never here, make compiler happy */
4942 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4943 const char *message, gpointer user_data _U_)
4950 /* ignore log message, if log_level isn't interesting */
4951 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4952 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4957 /* create a "timestamp" */
4959 today = localtime(&curr);
4961 switch(log_level & G_LOG_LEVEL_MASK) {
4962 case G_LOG_LEVEL_ERROR:
4965 case G_LOG_LEVEL_CRITICAL:
4968 case G_LOG_LEVEL_WARNING:
4971 case G_LOG_LEVEL_MESSAGE:
4974 case G_LOG_LEVEL_INFO:
4977 case G_LOG_LEVEL_DEBUG:
4981 fprintf(stderr, "unknown log_level %d\n", log_level);
4983 g_assert_not_reached();
4986 /* Generate the output message */
4987 if (log_level & G_LOG_LEVEL_MESSAGE) {
4988 /* normal user messages without additional infos */
4989 msg = g_strdup_printf("%s\n", message);
4991 /* info/debug messages with additional infos */
4992 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4993 today->tm_hour, today->tm_min, today->tm_sec,
4994 log_domain != NULL ? log_domain : "",
4998 /* DEBUG & INFO msgs (if we're debugging today) */
4999 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
5000 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5001 #ifdef DEBUG_DUMPCAP
5002 fprintf(stderr, "%s", msg);
5005 #ifdef DEBUG_CHILD_DUMPCAP
5006 fprintf(debug_log, "%s", msg);
5014 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
5015 /* to parent especially formatted if dumpcap running as child. */
5016 if (capture_child) {
5017 sync_pipe_errmsg_to_parent(2, msg, "");
5019 fprintf(stderr, "%s", msg);
5026 /****************************************************************************************************************/
5027 /* indication report routines */
5031 report_packet_count(unsigned int packet_count)
5033 char tmp[SP_DECISIZE+1+1];
5034 static unsigned int count = 0;
5036 if (capture_child) {
5037 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
5038 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
5039 pipe_write_block(2, SP_PACKET_COUNT, tmp);
5041 count += packet_count;
5042 fprintf(stderr, "\rPackets: %u ", count);
5043 /* stderr could be line buffered */
5049 report_new_capture_file(const char *filename)
5051 if (capture_child) {
5052 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
5053 pipe_write_block(2, SP_FILE, filename);
5057 * Prevent a SIGINFO handler from writing to the standard error
5058 * while we're doing so; instead, have it just set a flag telling
5059 * us to print that information when we're done.
5062 #endif /* SIGINFO */
5063 fprintf(stderr, "File: %s\n", filename);
5064 /* stderr could be line buffered */
5069 * Allow SIGINFO handlers to write.
5074 * If a SIGINFO handler asked us to write out capture counts, do so.
5077 report_counts_for_siginfo();
5078 #endif /* SIGINFO */
5083 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5085 interface_options interface_opts;
5086 char tmp[MSG_MAX_LENGTH+1+6];
5088 if (i < capture_opts->ifaces->len) {
5089 if (capture_child) {
5090 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5091 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5092 pipe_write_block(2, SP_BAD_FILTER, tmp);
5095 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5096 * the error message below.
5098 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
5100 "Invalid capture filter \"%s\" for interface '%s'.\n"
5102 "That string isn't a valid capture filter (%s).\n"
5103 "See the User's Guide for a description of the capture filter syntax.",
5104 interface_opts.cfilter, interface_opts.name, errmsg);
5110 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5112 if (capture_child) {
5113 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5114 "Primary Error: %s", error_msg);
5115 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5116 "Secondary Error: %s", secondary_error_msg);
5117 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5119 cmdarg_err("%s", error_msg);
5120 if (secondary_error_msg[0] != '\0')
5121 cmdarg_err_cont("%s", secondary_error_msg);
5126 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
5128 char tmp[SP_DECISIZE+1+1];
5129 guint32 total_drops = pcap_drops + drops + flushed;
5131 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5133 if (capture_child) {
5134 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5135 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5136 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
5137 /* XXX: Need to provide interface id, changes to consumers required. */
5138 pipe_write_block(2, SP_DROPS, tmp);
5141 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5142 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
5143 received ? 100.0 * received / (received + total_drops) : 0.0);
5144 /* stderr could be line buffered */
5150 /************************************************************************************************/
5151 /* signal_pipe handling */
5156 signal_pipe_check_running(void)
5158 /* any news from our parent? -> just stop the capture */
5162 /* if we are running standalone, no check required */
5163 if (!capture_child) {
5167 if (!sig_pipe_name || !sig_pipe_handle) {
5168 /* This shouldn't happen */
5169 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5170 "Signal pipe: No name or handle");
5175 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5176 * at this point. Should we check to see if the parent is still alive,
5177 * e.g. by using OpenProcess?
5180 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5182 if (!result || avail > 0) {
5183 /* peek failed or some bytes really available */
5184 /* (if not piping from stdin this would fail) */
5185 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5186 "Signal pipe: Stop capture: %s", sig_pipe_name);
5187 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5188 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
5189 sig_pipe_handle, result, avail);
5192 /* pipe ok and no bytes available */
5203 * Editor modelines - https://www.wireshark.org/tools/modelines.html
5208 * indent-tabs-mode: nil
5211 * vi: set shiftwidth=4 tabstop=8 expandtab:
5212 * :indentSize=4:tabSize=8:noTabs=true: