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_version_info.h>
77 #ifndef HAVE_GETOPT_LONG
78 #include "wsutil/wsgetopt.h"
86 # include <sys/prctl.h>
87 # include <sys/capability.h>
90 #include "ringbuffer.h"
92 #include "caputils/capture_ifinfo.h"
93 #include "caputils/capture-pcap-util.h"
94 #include "caputils/capture-pcap-util-int.h"
96 #include "caputils/capture-wpcap.h"
102 #include <wsutil/unicode-utils.h>
109 #ifdef NEED_INET_V6DEFS_H
110 # include "wsutil/inet_v6defs.h"
113 #include <wsutil/clopts_common.h>
114 #include <wsutil/privileges.h>
116 #include "sync_pipe.h"
118 #include "capture_opts.h"
119 #include <capchild/capture_session.h>
120 #include <capchild/capture_sync.h>
122 #include "conditions.h"
123 #include "capture_stop_conditions.h"
125 #include "wsutil/tempfile.h"
127 #include "wsutil/file_util.h"
128 #include "wsutil/os_version_info.h"
130 #include "caputils/ws80211_utils.h"
133 * Get information about libpcap format from "wiretap/libpcap.h".
134 * XXX - can we just use pcap_open_offline() to read the pipe?
136 #include "wiretap/libpcap.h"
138 /**#define DEBUG_DUMPCAP**/
139 /**#define DEBUG_CHILD_DUMPCAP**/
143 #include <conio.h> /* _getch() */
147 #ifdef DEBUG_CHILD_DUMPCAP
148 FILE *debug_log; /* for logging debug messages to */
149 /* a file if DEBUG_CHILD_DUMPCAP */
153 static GAsyncQueue *pcap_queue;
154 static gint64 pcap_queue_bytes;
155 static gint64 pcap_queue_packets;
156 static gint64 pcap_queue_byte_limit = 0;
157 static gint64 pcap_queue_packet_limit = 0;
159 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
161 static gchar *sig_pipe_name = NULL;
162 static HANDLE sig_pipe_handle = NULL;
163 static gboolean signal_pipe_check_running(void);
167 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
168 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
171 /** Stop a low-level capture (stops the capture child). */
172 static void capture_loop_stop(void);
173 /** Close a pipe, or socket if \a from_socket is TRUE */
174 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
178 * Enable kernel BPF JIT compiler if available.
179 * If any calls fail, just drive on - the JIT compiler might not be
180 * enabled, but filtering will still work, and it's not clear what
181 * we could do if the calls fail; should we just report the error
182 * and not continue to capture, should we report it as a warning, or
186 enable_kernel_bpf_jit_compiler(void)
190 static const char file[] = "/proc/sys/net/core/bpf_jit_enable";
192 fd = ws_open(file, O_WRONLY);
196 written = write(fd, "1", strlen("1"));
202 #if !defined (__linux__)
203 #ifndef HAVE_PCAP_BREAKLOOP
205 * We don't have pcap_breakloop(), which is the only way to ensure that
206 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
207 * won't, if the call to read the next packet or batch of packets is
208 * is interrupted by a signal on UN*X, just go back and try again to
211 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
212 * the signal handler, set a flag to stop capturing; however, without
213 * a guarantee of that sort, we can't guarantee that we'll stop capturing
214 * if the read will be retried and won't time out if no packets arrive.
216 * Therefore, on at least some platforms, we work around the lack of
217 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
218 * to wait for packets to arrive, so that we're probably going to be
219 * blocked in the select() when the signal arrives, and can just bail
220 * out of the loop at that point.
222 * However, we don't want to do that on BSD (because "select()" doesn't work
223 * correctly on BPF devices on at least some releases of some flavors of
224 * BSD), and we don't want to do it on Windows (because "select()" is
225 * something for sockets, not for arbitrary handles). (Note that "Windows"
226 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
227 * using WinPcap, not a UNIX libpcap.)
229 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
230 * on BSD times out even if no packets have arrived, so we'll eventually
231 * exit pcap_dispatch() with an indication that no packets have arrived,
232 * and will break out of the capture loop at that point.
234 * On Windows, we can't send a SIGINT to stop capturing, so none of this
235 * applies in any case.
237 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
238 * want to include it if it's not present on this platform, however.
240 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
241 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
243 # define MUST_DO_SELECT
244 # endif /* avoid select */
245 #endif /* HAVE_PCAP_BREAKLOOP */
247 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
248 * in pcap_dispatch(); on the other hand, select() works just fine there.
249 * Hence we use a select for that come what may.
251 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
252 * internally, and, with TPACKET_V3, once that's supported, it'll
253 * support timeouts, at least as I understand the way the code works.
255 #define MUST_DO_SELECT
258 /** init the capture filter */
261 INITFILTER_BAD_FILTER,
262 INITFILTER_OTHER_ERROR
263 } initfilter_status_t;
266 STATE_EXPECT_REC_HDR,
279 typedef struct _pcap_options {
284 #ifdef MUST_DO_SELECT
285 int pcap_fd; /**< pcap file descriptor */
292 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
293 /**< capture pipe (unix only "input file") */
294 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
295 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
296 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
297 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
299 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
301 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
302 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
303 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
305 char * cap_pipe_buf; /**< Pointer to the data buffer we read into */
306 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
307 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
309 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
310 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
312 cap_pipe_state_t cap_pipe_state;
313 cap_pipe_err_t cap_pipe_err;
316 GMutex *cap_pipe_read_mtx;
317 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
321 typedef struct _loop_data {
323 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
324 int err; /**< if non-zero, error seen while capturing */
325 gint packet_count; /**< Number of packets we have already captured */
326 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
327 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
329 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
335 guint64 bytes_written;
336 guint32 autostop_files;
339 typedef struct _pcap_queue_element {
340 pcap_options *pcap_opts;
341 struct pcap_pkthdr phdr;
343 } pcap_queue_element;
346 * Standard secondary message for unexpected errors.
348 static const char please_report[] =
349 "Please report this to the Wireshark developers.\n"
350 "http://bugs.wireshark.org/\n"
351 "(This is not a crash; please do not report it as such.)";
354 * This needs to be static, so that the SIGINT handler can clear the "go"
357 static loop_data global_ld;
361 * Timeout, in milliseconds, for reads from the stream of captured packets
362 * from a capture device.
364 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
365 * 64-bit applications, with sub-second timeouts not to work. The bug is
366 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
368 #if defined(__APPLE__) && defined(__LP64__)
369 static gboolean need_timeout_workaround;
371 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
373 #define CAP_READ_TIMEOUT 250
377 * Timeout, in microseconds, for reads from the stream of captured packets
378 * from a pipe. Pipes don't have the same problem that BPF devices do
379 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
380 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
381 * of the offending versions of Snow Leopard.
383 * On Windows this value is converted to milliseconds and passed to
384 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
385 * will return immediately.
388 #define PIPE_READ_TIMEOUT 100000
390 #define PIPE_READ_TIMEOUT 250000
393 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
396 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
397 const char *message, gpointer user_data _U_);
399 /* capture related options */
400 static capture_options global_capture_opts;
401 static gboolean quiet = FALSE;
402 static gboolean use_threads = FALSE;
403 static guint64 start_time;
405 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
407 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
409 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
410 int err, gboolean is_close);
412 static void WS_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
414 static void report_new_capture_file(const char *filename);
415 static void report_packet_count(unsigned int packet_count);
416 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
417 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
418 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
420 #define MSG_MAX_LENGTH 4096
422 /* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
424 create_timestamp(void) {
434 * Current time, represented as 100-nanosecond intervals since
435 * January 1, 1601, 00:00:00 UTC.
437 * I think DWORD might be signed, so cast both parts of "now"
438 * to guint32 so that the sign bit doesn't get treated specially.
440 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
441 * might want to use instead.
443 GetSystemTimeAsFileTime(&now);
444 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
445 (guint32)now.dwLowDateTime;
448 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
454 * Subtract difference, in microseconds, between January 1, 1601
455 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
457 timestamp -= G_GUINT64_CONSTANT(11644473600000000);
460 * Current time, represented as seconds and microseconds since
461 * January 1, 1970, 00:00:00 UTC.
463 gettimeofday(&now, NULL);
466 * Convert to delta in microseconds.
468 timestamp = (guint64)(now.tv_sec) * 1000000 +
469 (guint64)(now.tv_usec);
475 print_usage(FILE *output)
477 fprintf(output, "\nUsage: dumpcap [options] ...\n");
478 fprintf(output, "\n");
479 fprintf(output, "Capture interface:\n");
480 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
481 " or for remote capturing, use one of these formats:\n"
482 " rpcap://<host>/<interface>\n"
483 " TCP@<host>:<port>\n");
484 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
485 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
486 fprintf(output, " -p don't capture in promiscuous mode\n");
487 #ifdef HAVE_PCAP_CREATE
488 fprintf(output, " -I capture in monitor mode, if available\n");
490 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
491 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
493 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
494 fprintf(output, " -D print list of interfaces and exit\n");
495 fprintf(output, " -L print list of link-layer types of iface and exit\n");
496 #ifdef HAVE_BPF_IMAGE
497 fprintf(output, " -d print generated BPF code for capture filter\n");
499 fprintf(output, " -k set channel on wifi interface <freq>,[<type>]\n");
500 fprintf(output, " -S print statistics for each interface once per second\n");
501 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
502 fprintf(output, "\n");
503 #ifdef HAVE_PCAP_REMOTE
504 fprintf(output, "RPCAP options:\n");
505 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
506 fprintf(output, " -u use UDP for RPCAP data transfer\n");
507 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
508 #ifdef HAVE_PCAP_SETSAMPLING
509 fprintf(output, " -m <sampling type> use packet sampling\n");
510 fprintf(output, " count:NUM - capture one packet of every NUM\n");
511 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
514 fprintf(output, "Stop conditions:\n");
515 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
516 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
517 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
518 fprintf(output, " files:NUM - stop after NUM files\n");
519 /*fprintf(output, "\n");*/
520 fprintf(output, "Output (files):\n");
521 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
522 fprintf(output, " -g enable group read access on the output file(s)\n");
523 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
524 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
525 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
526 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
527 fprintf(output, " -P use libpcap format instead of pcapng\n");
528 fprintf(output, " --capture-comment <comment>\n");
529 fprintf(output, " add a capture comment to the output file\n");
530 fprintf(output, " (only for pcapng)\n");
531 fprintf(output, "\n");
532 fprintf(output, "Miscellaneous:\n");
533 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
534 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
535 fprintf(output, " within dumpcap\n");
536 fprintf(output, " -t use a separate thread per interface\n");
537 fprintf(output, " -q don't report packet capture counts\n");
538 fprintf(output, " -v print version information and exit\n");
539 fprintf(output, " -h display this help and exit\n");
540 fprintf(output, "\n");
542 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
543 fprintf(output, "You might want to reset it\n");
544 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
545 fprintf(output, "\n");
547 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
548 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
549 fprintf(output, "\n");
550 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
554 * Report an error in command-line arguments.
555 * If we're a capture child, send a message back to the parent, otherwise
559 dumpcap_cmdarg_err(const char *fmt, va_list ap)
563 /* Generate a 'special format' message back to parent */
564 msg = g_strdup_vprintf(fmt, ap);
565 sync_pipe_errmsg_to_parent(2, msg, "");
568 fprintf(stderr, "dumpcap: ");
569 vfprintf(stderr, fmt, ap);
570 fprintf(stderr, "\n");
575 * Report additional information for an error in command-line arguments.
576 * If we're a capture child, send a message back to the parent, otherwise
580 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
584 msg = g_strdup_vprintf(fmt, ap);
585 sync_pipe_errmsg_to_parent(2, msg, "");
588 vfprintf(stderr, fmt, ap);
589 fprintf(stderr, "\n");
595 #if 0 /* Set to enable capability debugging */
596 /* see 'man cap_to_text()' for explanation of output */
597 /* '=' means 'all= ' ie: no capabilities */
598 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
600 print_caps(const char *pfx) {
601 cap_t caps = cap_get_proc();
602 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
603 "%s: EUID: %d Capabilities: %s", pfx,
604 geteuid(), cap_to_text(caps, NULL));
607 print_caps(const char *pfx _U_) {
612 relinquish_all_capabilities(void)
614 /* Drop any and all capabilities this process may have. */
615 /* Allowed whether or not process has any privileges. */
616 cap_t caps = cap_init(); /* all capabilities initialized to off */
617 print_caps("Pre-clear");
618 if (cap_set_proc(caps)) {
619 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
621 print_caps("Post-clear");
627 open_capture_device(capture_options *capture_opts
628 #ifndef HAVE_PCAP_SET_TSTAMP_PRECISION
632 interface_options *interface_opts,
633 char (*open_err_str)[PCAP_ERRBUF_SIZE])
636 #ifdef HAVE_PCAP_CREATE
639 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
640 struct pcap_rmtauth auth;
643 /* Open the network interface to capture from it.
644 Some versions of libpcap may put warnings into the error buffer
645 if they succeed; to tell if that's happened, we have to clear
646 the error buffer, and check if it's still a null string. */
647 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Entering open_capture_device().");
648 (*open_err_str)[0] = '\0';
649 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
651 * If we're opening a remote device, use pcap_open(); that's currently
652 * the only open routine that supports remote devices.
654 if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
655 auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
656 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
657 auth.username = interface_opts->auth_username;
658 auth.password = interface_opts->auth_password;
660 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
661 "Calling pcap_open() using name %s, snaplen %d, promisc_mode %d, datatx_udp %d, nocap_rpcap %d.",
662 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode,
663 interface_opts->datatx_udp, interface_opts->nocap_rpcap);
664 pcap_h = pcap_open(interface_opts->name, interface_opts->snaplen,
666 (interface_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
667 (interface_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
668 (interface_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
669 CAP_READ_TIMEOUT, &auth, *open_err_str);
670 if (pcap_h == NULL) {
671 /* Error - did pcap actually supply an error message? */
672 if ((*open_err_str)[0] == '\0') {
673 /* Work around known WinPcap bug wherein no error message is
674 filled in on a failure to open an rpcap: URL. */
675 g_strlcpy(*open_err_str,
676 "Unknown error (pcap bug; actual error cause not reported)",
677 sizeof *open_err_str);
680 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
681 "pcap_open() returned %p.", (void *)pcap_h);
686 * If we're not opening a remote device, use pcap_create() and
687 * pcap_activate() if we have them, so that we can set the buffer
688 * size, otherwise use pcap_open_live().
690 #ifdef HAVE_PCAP_CREATE
691 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
692 "Calling pcap_create() using %s.", interface_opts->name);
693 pcap_h = pcap_create(interface_opts->name, *open_err_str);
694 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
695 "pcap_create() returned %p.", (void *)pcap_h);
696 if (pcap_h != NULL) {
697 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
698 "Calling pcap_set_snaplen() with snaplen %d.", interface_opts->snaplen);
699 pcap_set_snaplen(pcap_h, interface_opts->snaplen);
700 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
701 "Calling pcap_set_promisc() with promisc_mode %d.", interface_opts->promisc_mode);
702 pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
703 pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
705 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
707 * If we're writing pcap-ng files, try to enable
708 * nanosecond-resolution capture; any code that
709 * can read pcap-ng files must be able to handle
710 * nanosecond-resolution time stamps.
712 * If we're writing pcap files, don't try to enable
713 * nanosecond-resolution capture, as not all code
714 * that reads pcap files recognizes the nanosecond-
715 * resolution pcap file magic number.
717 if (capture_opts->use_pcapng)
718 request_high_resolution_timestamp(pcap_h);
719 #endif /* HAVE_PCAP_SET_TSTAMP_PRECISION */
721 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
722 "buffersize %d.", interface_opts->buffer_size);
723 if (interface_opts->buffer_size != 0) {
724 pcap_set_buffer_size(pcap_h, interface_opts->buffer_size * 1024 * 1024);
726 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
727 "monitor_mode %d.", interface_opts->monitor_mode);
728 if (interface_opts->monitor_mode)
729 pcap_set_rfmon(pcap_h, 1);
730 err = pcap_activate(pcap_h);
731 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
732 "pcap_activate() returned %d.", err);
734 /* Failed to activate, set to NULL */
735 if (err == PCAP_ERROR)
736 g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
738 g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
744 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
745 "pcap_open_live() calling using name %s, snaplen %d, promisc_mode %d.",
746 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode);
747 pcap_h = pcap_open_live(interface_opts->name, interface_opts->snaplen,
748 interface_opts->promisc_mode, CAP_READ_TIMEOUT,
750 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
751 "pcap_open_live() returned %p.", (void *)pcap_h);
754 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_capture_device %s : %s", pcap_h ? "SUCCESS" : "FAILURE", interface_opts->name);
759 get_capture_device_open_failure_messages(const char *open_err_str,
761 char *errmsg, size_t errmsg_len,
762 char *secondary_errmsg,
763 size_t secondary_errmsg_len)
766 const char *libpcap_warn;
767 static const char ppamsg[] = "can't find PPA for ";
770 g_snprintf(errmsg, (gulong) errmsg_len,
771 "The capture session could not be initiated on interface '%s' (%s).",
772 iface, open_err_str);
775 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
777 "In order to capture packets, WinPcap must be installed; see\n"
779 " http://www.winpcap.org/\n"
783 " http://www.mirrors.wiretapped.net/security/packet-capture/winpcap/\n"
787 " http://winpcap.cs.pu.edu.tw/\n"
789 "for a downloadable version of WinPcap and for instructions on how to install\n"
792 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
794 "Please check that \"%s\" is the proper interface.\n"
797 "Help can be found at:\n"
799 " http://wiki.wireshark.org/WinPcap\n"
800 " http://wiki.wireshark.org/CaptureSetup\n",
804 /* If we got a "can't find PPA for X" message, warn the user (who
805 is running dumpcap on HP-UX) that they don't have a version of
806 libpcap that properly handles HP-UX (libpcap 0.6.x and later
807 versions, which properly handle HP-UX, say "can't find /dev/dlpi
808 PPA for X" rather than "can't find PPA for X"). */
809 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
812 "You are running (T)Wireshark with a version of the libpcap library\n"
813 "that doesn't handle HP-UX network devices well; this means that\n"
814 "(T)Wireshark may not be able to capture packets.\n"
816 "To fix this, you should install libpcap 0.6.2, or a later version\n"
817 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
818 "packaged binary form from the Software Porting And Archive Centre\n"
819 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
820 "at the URL lists a number of mirror sites.";
824 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
825 "Please check to make sure you have sufficient permissions, and that you have "
826 "the proper interface or pipe specified.%s", libpcap_warn);
830 /* Set the data link type on a pcap. */
832 set_pcap_linktype(pcap_t *pcap_h, int linktype, char *name,
833 char *errmsg, size_t errmsg_len,
834 char *secondary_errmsg, size_t secondary_errmsg_len)
836 char *set_linktype_err_str;
839 return TRUE; /* just use the default */
840 #ifdef HAVE_PCAP_SET_DATALINK
841 if (pcap_set_datalink(pcap_h, linktype) == 0)
842 return TRUE; /* no error */
843 set_linktype_err_str = pcap_geterr(pcap_h);
845 /* Let them set it to the type it is; reject any other request. */
846 if (get_pcap_linktype(pcap_h, name) == linktype)
847 return TRUE; /* no error */
848 set_linktype_err_str =
849 "That DLT isn't one of the DLTs supported by this device";
851 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type on interface '%s' (%s).",
852 name, set_linktype_err_str);
854 * If the error isn't "XXX is not one of the DLTs supported by this device",
855 * tell the user to tell the Wireshark developers about it.
857 if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
858 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
860 secondary_errmsg[0] = '\0';
865 compile_capture_filter(const char *iface, pcap_t *pcap_h,
866 struct bpf_program *fcode, const char *cfilter)
868 bpf_u_int32 netnum, netmask;
869 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
871 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
873 * Well, we can't get the netmask for this interface; it's used
874 * only for filters that check for broadcast IP addresses, so
875 * we just punt and use 0. It might be nice to warn the user,
876 * but that's a pain in a GUI application, as it'd involve popping
877 * up a message box, and it's not clear how often this would make
878 * a difference (only filters that check for IP broadcast addresses
882 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
887 * Sigh. Older versions of libpcap don't properly declare the
888 * third argument to pcap_compile() as a const pointer. Cast
891 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
896 #ifdef HAVE_BPF_IMAGE
898 show_filter_code(capture_options *capture_opts)
900 interface_options interface_opts;
902 gchar open_err_str[PCAP_ERRBUF_SIZE];
903 char errmsg[MSG_MAX_LENGTH+1];
904 char secondary_errmsg[MSG_MAX_LENGTH+1];
905 struct bpf_program fcode;
906 struct bpf_insn *insn;
910 for (j = 0; j < capture_opts->ifaces->len; j++) {
911 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
912 pcap_h = open_capture_device(capture_opts, &interface_opts, &open_err_str);
913 if (pcap_h == NULL) {
914 /* Open failed; get messages */
915 get_capture_device_open_failure_messages(open_err_str,
917 errmsg, sizeof errmsg,
919 sizeof secondary_errmsg);
920 /* And report them */
921 report_capture_error(errmsg, secondary_errmsg);
925 /* Set the link-layer type. */
926 if (!set_pcap_linktype(pcap_h, interface_opts.linktype, interface_opts.name,
927 errmsg, sizeof errmsg,
928 secondary_errmsg, sizeof secondary_errmsg)) {
930 report_capture_error(errmsg, secondary_errmsg);
934 /* OK, try to compile the capture filter. */
935 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
936 interface_opts.cfilter)) {
938 report_cfilter_error(capture_opts, j, errmsg);
943 /* Now print the filter code. */
944 insn = fcode.bf_insns;
946 for (i = 0; i < fcode.bf_len; insn++, i++)
947 printf("%s\n", bpf_image(insn, i));
949 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
950 /* to remove any suid privileges. */
951 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
952 /* (euid/egid have already previously been set to ruid/rgid. */
953 /* (See comment in main() for details) */
955 relinquish_special_privs_perm();
957 relinquish_all_capabilities();
960 /* Let our parent know we succeeded. */
961 pipe_write_block(2, SP_SUCCESS, NULL);
968 * capture_interface_list() is expected to do the right thing to get
969 * a list of interfaces.
971 * In most of the programs in the Wireshark suite, "the right thing"
972 * is to run dumpcap and ask it for the list, because dumpcap may
973 * be the only program in the suite with enough privileges to get
976 * In dumpcap itself, however, we obviously can't run dumpcap to
977 * ask for the list. Therefore, our capture_interface_list() should
978 * just call get_interface_list().
981 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
983 return get_interface_list(err, err_str);
987 * Get the data-link type for a libpcap device.
988 * This works around AIX 5.x's non-standard and incompatible-with-the-
989 * rest-of-the-universe libpcap.
992 get_pcap_linktype(pcap_t *pch, const char *devicename
1000 const char *ifacename;
1003 linktype = pcap_datalink(pch);
1007 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
1008 * rather than DLT_ values for link-layer types; the ifType values
1009 * for LAN devices are:
1016 * and the ifType value for a loopback device is 24.
1018 * The AIX names for LAN devices begin with:
1025 * and the AIX names for loopback devices begin with "lo".
1027 * (The difference between "Ethernet" and "802.3" is presumably
1028 * whether packets have an Ethernet header, with a packet type,
1029 * or an 802.3 header, with a packet length, followed by an 802.2
1030 * header and possibly a SNAP header.)
1032 * If the device name matches "linktype" interpreted as an ifType
1033 * value, rather than as a DLT_ value, we will assume this is AIX's
1034 * non-standard, incompatible libpcap, rather than a standard libpcap,
1035 * and will map the link-layer type to the standard DLT_ value for
1036 * that link-layer type, as that's what the rest of Wireshark expects.
1038 * (This means the capture files won't be readable by a tcpdump
1039 * linked with AIX's non-standard libpcap, but so it goes. They
1040 * *will* be readable by standard versions of tcpdump, Wireshark,
1043 * XXX - if we conclude we're using AIX libpcap, should we also
1044 * set a flag to cause us to assume the time stamps are in
1045 * seconds-and-nanoseconds form, and to convert them to
1046 * seconds-and-microseconds form before processing them and
1051 * Find the last component of the device name, which is the
1054 ifacename = strchr(devicename, '/');
1055 if (ifacename == NULL)
1056 ifacename = devicename;
1058 /* See if it matches any of the LAN device names. */
1059 if (strncmp(ifacename, "en", 2) == 0) {
1060 if (linktype == 6) {
1062 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
1066 } else if (strncmp(ifacename, "et", 2) == 0) {
1067 if (linktype == 7) {
1069 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
1070 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
1075 } else if (strncmp(ifacename, "tr", 2) == 0) {
1076 if (linktype == 9) {
1078 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
1079 * DLT_IEEE802, which is what's used for Token Ring.
1083 } else if (strncmp(ifacename, "fi", 2) == 0) {
1084 if (linktype == 15) {
1086 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
1090 } else if (strncmp(ifacename, "lo", 2) == 0) {
1091 if (linktype == 24) {
1093 * That's the RFC 1573 value for "software loopback" devices; map it
1094 * to DLT_NULL, which is what's used for loopback devices on BSD.
1104 static data_link_info_t *
1105 create_data_link_info(int dlt)
1107 data_link_info_t *data_link_info;
1110 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
1111 data_link_info->dlt = dlt;
1112 text = pcap_datalink_val_to_name(dlt);
1114 data_link_info->name = g_strdup(text);
1116 data_link_info->name = g_strdup_printf("DLT %d", dlt);
1117 text = pcap_datalink_val_to_description(dlt);
1119 data_link_info->description = g_strdup(text);
1121 data_link_info->description = NULL;
1122 return data_link_info;
1126 * Get the capabilities of a network device.
1128 static if_capabilities_t *
1129 get_if_capabilities(const char *devicename, gboolean monitor_mode
1130 #ifndef HAVE_PCAP_CREATE
1135 if_capabilities_t *caps;
1136 char errbuf[PCAP_ERRBUF_SIZE];
1138 #ifdef HAVE_PCAP_CREATE
1142 #ifdef HAVE_PCAP_LIST_DATALINKS
1146 data_link_info_t *data_link_info;
1149 * Allocate the interface capabilities structure.
1151 caps = (if_capabilities_t *)g_malloc(sizeof *caps);
1154 * WinPcap 4.1.2, and possibly earlier versions, have a bug
1155 * wherein, when an open with an rpcap: URL fails, the error
1156 * message for the error is not copied to errbuf and whatever
1157 * on-the-stack junk is in errbuf is treated as the error
1160 * To work around that (and any other bugs of that sort, we
1161 * initialize errbuf to an empty string. If we get an error
1162 * and the string is empty, we report it as an unknown error.
1163 * (If we *don't* get an error, and the string is *non*-empty,
1164 * that could be a warning returned, such as "can't turn
1165 * promiscuous mode on"; we currently don't do so.)
1168 #ifdef HAVE_PCAP_OPEN
1169 pch = pcap_open(devicename, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1170 caps->can_set_rfmon = FALSE;
1172 if (err_str != NULL)
1173 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1177 #elif defined(HAVE_PCAP_CREATE)
1178 pch = pcap_create(devicename, errbuf);
1180 if (err_str != NULL)
1181 *err_str = g_strdup(errbuf);
1185 status = pcap_can_set_rfmon(pch);
1188 if (status == PCAP_ERROR)
1189 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1192 *err_str = g_strdup(pcap_statustostr(status));
1198 caps->can_set_rfmon = FALSE;
1199 else if (status == 1) {
1200 caps->can_set_rfmon = TRUE;
1202 pcap_set_rfmon(pch, 1);
1204 if (err_str != NULL) {
1205 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1213 status = pcap_activate(pch);
1215 /* Error. We ignore warnings (status > 0). */
1216 if (err_str != NULL) {
1217 if (status == PCAP_ERROR)
1218 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1221 *err_str = g_strdup(pcap_statustostr(status));
1228 pch = pcap_open_live(devicename, MIN_PACKET_SIZE, 0, 0, errbuf);
1229 caps->can_set_rfmon = FALSE;
1231 if (err_str != NULL)
1232 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1237 deflt = get_pcap_linktype(pch, devicename);
1238 #ifdef HAVE_PCAP_LIST_DATALINKS
1239 nlt = pcap_list_datalinks(pch, &linktypes);
1240 if (nlt == 0 || linktypes == NULL) {
1242 if (err_str != NULL)
1243 *err_str = NULL; /* an empty list doesn't mean an error */
1247 caps->data_link_types = NULL;
1248 for (i = 0; i < nlt; i++) {
1249 data_link_info = create_data_link_info(linktypes[i]);
1252 * XXX - for 802.11, make the most detailed 802.11
1253 * version the default, rather than the one the
1254 * device has as the default?
1256 if (linktypes[i] == deflt)
1257 caps->data_link_types = g_list_prepend(caps->data_link_types,
1260 caps->data_link_types = g_list_append(caps->data_link_types,
1263 #ifdef HAVE_PCAP_FREE_DATALINKS
1264 pcap_free_datalinks(linktypes);
1267 * In Windows, there's no guarantee that if you have a library
1268 * built with one version of the MSVC++ run-time library, and
1269 * it returns a pointer to allocated data, you can free that
1270 * data from a program linked with another version of the
1271 * MSVC++ run-time library.
1273 * This is not an issue on UN*X.
1275 * See the mail threads starting at
1277 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1281 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1284 #define xx_free free /* hack so checkAPIs doesn't complain */
1287 #endif /* HAVE_PCAP_FREE_DATALINKS */
1288 #else /* HAVE_PCAP_LIST_DATALINKS */
1290 data_link_info = create_data_link_info(deflt);
1291 caps->data_link_types = g_list_append(caps->data_link_types,
1293 #endif /* HAVE_PCAP_LIST_DATALINKS */
1297 if (err_str != NULL)
1302 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1304 * Output a machine readable list of the interfaces
1305 * This list is retrieved by the sync_interface_list_open() function
1306 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
1309 print_machine_readable_interfaces(GList *if_list)
1316 char addr_str[ADDRSTRLEN];
1318 if (capture_child) {
1319 /* Let our parent know we succeeded. */
1320 pipe_write_block(2, SP_SUCCESS, NULL);
1323 i = 1; /* Interface id number */
1324 for (if_entry = g_list_first(if_list); if_entry != NULL;
1325 if_entry = g_list_next(if_entry)) {
1326 if_info = (if_info_t *)if_entry->data;
1327 printf("%d. %s\t", i++, if_info->name);
1330 * Print the contents of the if_entry struct in a parseable format.
1331 * Each if_entry element is tab-separated. Addresses are comma-
1334 /* XXX - Make sure our description doesn't contain a tab */
1335 if (if_info->vendor_description != NULL)
1336 printf("%s\t", if_info->vendor_description);
1340 /* XXX - Make sure our friendly name doesn't contain a tab */
1341 if (if_info->friendly_name != NULL)
1342 printf("%s\t", if_info->friendly_name);
1346 printf("%i\t", if_info->type);
1348 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1349 addr = g_slist_next(addr)) {
1350 if (addr != g_slist_nth(if_info->addrs, 0))
1353 if_addr = (if_addr_t *)addr->data;
1354 switch(if_addr->ifat_type) {
1356 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1358 printf("%s", addr_str);
1360 printf("<unknown IPv4>");
1364 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1365 addr_str, ADDRSTRLEN)) {
1366 printf("%s", addr_str);
1368 printf("<unknown IPv6>");
1372 printf("<type unknown %i>", if_addr->ifat_type);
1376 if (if_info->loopback)
1377 printf("\tloopback");
1379 printf("\tnetwork");
1381 printf("\t%s", if_info->extcap);
1388 * If you change the machine-readable output format of this function,
1389 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1392 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1395 data_link_info_t *data_link_info;
1396 const gchar *desc_str;
1398 if (capture_child) {
1399 /* Let our parent know we succeeded. */
1400 pipe_write_block(2, SP_SUCCESS, NULL);
1403 if (caps->can_set_rfmon)
1407 for (lt_entry = caps->data_link_types; lt_entry != NULL;
1408 lt_entry = g_list_next(lt_entry)) {
1409 data_link_info = (data_link_info_t *)lt_entry->data;
1410 if (data_link_info->description != NULL)
1411 desc_str = data_link_info->description;
1413 desc_str = "(not supported)";
1414 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1424 /* Print the number of packets captured for each interface until we're killed. */
1426 print_statistics_loop(gboolean machine_readable)
1428 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1434 char errbuf[PCAP_ERRBUF_SIZE];
1435 struct pcap_stat ps;
1437 if_list = get_interface_list(&err, &err_str);
1438 if (if_list == NULL) {
1440 cmdarg_err("There are no interfaces on which a capture can be done");
1442 cmdarg_err("%s", err_str);
1448 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1449 if_info = (if_info_t *)if_entry->data;
1450 #ifdef HAVE_PCAP_OPEN
1451 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1453 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1457 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1458 if_stat->name = g_strdup(if_info->name);
1460 stat_list = g_list_append(stat_list, if_stat);
1465 cmdarg_err("There are no interfaces on which a capture can be done");
1469 if (capture_child) {
1470 /* Let our parent know we succeeded. */
1471 pipe_write_block(2, SP_SUCCESS, NULL);
1474 if (!machine_readable) {
1475 printf("%-15s %10s %10s\n", "Interface", "Received",
1479 global_ld.go = TRUE;
1480 while (global_ld.go) {
1481 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1482 if_stat = (if_stat_t *)stat_entry->data;
1483 pcap_stats(if_stat->pch, &ps);
1485 if (!machine_readable) {
1486 printf("%-15s %10u %10u\n", if_stat->name,
1487 ps.ps_recv, ps.ps_drop);
1489 printf("%s\t%u\t%u\n", if_stat->name,
1490 ps.ps_recv, ps.ps_drop);
1495 /* If we have a dummy signal pipe check it */
1496 if (!signal_pipe_check_running()) {
1497 global_ld.go = FALSE;
1505 /* XXX - Not reached. Should we look for 'q' in stdin? */
1506 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1507 if_stat = (if_stat_t *)stat_entry->data;
1508 pcap_close(if_stat->pch);
1509 g_free(if_stat->name);
1512 g_list_free(stat_list);
1513 free_interface_list(if_list);
1521 capture_cleanup_handler(DWORD dwCtrlType)
1523 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1524 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1525 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1526 like SIGTERM at least when the machine's shutting down.
1528 For now, if we're running as a command rather than a capture child,
1529 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1530 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1531 in that way on UN*X.
1533 If we're not running as a capture child, we might be running as
1534 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1535 user logs out. (XXX - can we explicitly check whether we're
1536 running as a service?) */
1538 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1539 "Console: Control signal");
1540 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1541 "Console: Control signal, CtrlType: %u", dwCtrlType);
1543 /* Keep capture running if we're a service and a user logs off */
1544 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1545 capture_loop_stop();
1553 capture_cleanup_handler(int signum _U_)
1555 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1556 SIGTERM. We assume that if the user wanted it to keep running
1557 after they logged out, they'd have nohupped it. */
1559 /* Note: don't call g_log() in the signal handler: if we happened to be in
1560 * g_log() in process context when the signal came in, g_log will detect
1561 * the "recursion" and abort.
1564 capture_loop_stop();
1570 report_capture_count(gboolean reportit)
1572 /* Don't print this if we're a capture child. */
1573 if (!capture_child && reportit) {
1574 fprintf(stderr, "\rPackets captured: %u\n", global_ld.packet_count);
1575 /* stderr could be line buffered */
1583 report_counts_for_siginfo(void)
1585 report_capture_count(quiet);
1586 infoprint = FALSE; /* we just reported it */
1590 report_counts_siginfo(int signum _U_)
1592 int sav_errno = errno;
1594 /* If we've been told to delay printing, just set a flag asking
1595 that we print counts (if we're supposed to), otherwise print
1596 the count of packets captured (if we're supposed to). */
1600 report_counts_for_siginfo();
1603 #endif /* SIGINFO */
1606 exit_main(int status)
1609 /* Shutdown windows sockets */
1612 /* can be helpful for debugging */
1613 #ifdef DEBUG_DUMPCAP
1614 printf("Press any key\n");
1625 * If we were linked with libcap (not related to libpcap), make sure we have
1626 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1627 * (See comment in main() for details)
1630 relinquish_privs_except_capture(void)
1632 /* If 'started_with_special_privs' (ie: suid) then enable for
1633 * ourself the NET_ADMIN and NET_RAW capabilities and then
1634 * drop our suid privileges.
1636 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1637 * stuff we don't need (and shouldn't have).
1638 * CAP_NET_RAW: Packet capture (raw sockets).
1641 if (started_with_special_privs()) {
1642 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1643 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1645 cap_t caps = cap_init(); /* all capabilities initialized to off */
1647 print_caps("Pre drop, pre set");
1649 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1650 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1653 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1654 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1656 if (cap_set_proc(caps)) {
1657 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1659 print_caps("Pre drop, post set");
1661 relinquish_special_privs_perm();
1663 print_caps("Post drop, pre set");
1664 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1665 if (cap_set_proc(caps)) {
1666 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1668 print_caps("Post drop, post set");
1674 #endif /* HAVE_LIBCAP */
1676 /* Take care of byte order in the libpcap headers read from pipes.
1677 * (function taken from wiretap/libpcap.c) */
1679 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1682 /* Byte-swap the record header fields. */
1683 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1684 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1685 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1686 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1689 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1690 swapped, in order to match the BPF header layout.
1692 Unfortunately, some files were, according to a comment in the "libpcap"
1693 source, written with version 2.3 in their headers but without the
1694 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1695 would make no sense - we assume that we need to swap them. */
1696 if (hdr->version_major == 2 &&
1697 (hdr->version_minor < 3 ||
1698 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1701 temp = rechdr->orig_len;
1702 rechdr->orig_len = rechdr->incl_len;
1703 rechdr->incl_len = temp;
1707 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1711 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1715 return recv(pipe_fd, buf, (int)sz, 0);
1720 return ws_read(pipe_fd, buf, sz);
1726 * Thread function that reads from a pipe and pushes the data
1727 * to the main application thread.
1730 * XXX Right now we use async queues for basic signaling. The main thread
1731 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1732 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1733 * Iff the read is successful cap_pipe_read pushes an item onto
1734 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1735 * the queues themselves (yet).
1737 * We might want to move some of the cap_pipe_dispatch logic here so that
1738 * we can let cap_thread_read run independently, queuing up multiple reads
1739 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1741 static void *cap_thread_read(void *arg)
1743 pcap_options *pcap_opts;
1746 DWORD b, last_err, bytes_read;
1752 pcap_opts = (pcap_options *)arg;
1753 while (pcap_opts->cap_pipe_err == PIPOK) {
1754 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1755 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1757 while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1758 if ((pcap_opts->from_cap_socket)
1764 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1765 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1768 pcap_opts->cap_pipe_err = PIPEOF;
1772 pcap_opts->cap_pipe_err = PIPERR;
1783 /* If we try to use read() on a named pipe on Windows with partial
1784 * data it appears to return EOF.
1786 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1787 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1792 last_err = GetLastError();
1793 if (last_err == ERROR_MORE_DATA) {
1795 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1796 pcap_opts->cap_pipe_err = PIPEOF;
1800 pcap_opts->cap_pipe_err = PIPERR;
1803 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1804 pcap_opts->cap_pipe_err = PIPEOF;
1811 pcap_opts->cap_pipe_bytes_read = bytes_read;
1812 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1813 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1815 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1821 /* Provide select() functionality for a single file descriptor
1822 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1824 * Returns the same values as select.
1827 cap_pipe_select(int pipe_fd)
1830 struct timeval timeout;
1833 FD_SET(pipe_fd, &rfds);
1835 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1836 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1838 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1841 #define DEF_TCP_PORT 19000
1844 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1846 char *sockname = pipename + 4;
1847 struct sockaddr_in sa;
1854 memset(&sa, 0, sizeof(sa));
1856 p = strchr(sockname, ':');
1858 len = strlen(sockname);
1859 port = DEF_TCP_PORT;
1863 port = strtoul(p + 1, &p, 10);
1864 if (*p || port > 65535) {
1873 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1875 if (inet_pton(AF_INET, buf, &sa.sin_addr) <= 0) {
1879 sa.sin_family = AF_INET;
1880 sa.sin_port = g_htons((u_short)port);
1882 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1883 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1885 LPTSTR errorText = NULL;
1888 lastError = WSAGetLastError();
1889 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1890 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1891 FORMAT_MESSAGE_IGNORE_INSERTS,
1892 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1893 (LPTSTR)&errorText, 0, NULL);
1895 g_snprintf(errmsg, errmsgl,
1896 "The capture session could not be initiated due to the socket error: \n"
1898 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1900 LocalFree(errorText);
1902 " %d: %s", errno, g_strerror(errno));
1904 pcap_opts->cap_pipe_err = PIPERR;
1907 cap_pipe_close(fd, TRUE);
1911 pcap_opts->from_cap_socket = TRUE;
1915 g_snprintf(errmsg, errmsgl,
1916 "The capture session could not be initiated because\n"
1917 "\"%s\" is not a valid socket specification", pipename);
1918 pcap_opts->cap_pipe_err = PIPERR;
1922 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1926 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1930 closesocket(pipe_fd);
1937 /* Mimic pcap_open_live() for pipe captures
1939 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1940 * open it, and read the header.
1942 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1943 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1945 cap_pipe_open_live(char *pipename,
1946 pcap_options *pcap_opts,
1947 struct pcap_hdr *hdr,
1948 char *errmsg, int errmsgl)
1951 ws_statb64 pipe_stat;
1952 struct sockaddr_un sa;
1956 interface_options interface_opts;
1959 int fd = -1, sel_ret;
1962 pcap_opts->cap_pipe_fd = -1;
1964 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1966 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1969 * XXX - this blocks until a pcap per-file header has been written to
1970 * the pipe, so it could block indefinitely.
1972 if (strcmp(pipename, "-") == 0) {
1974 fd = 0; /* read from stdin */
1976 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1978 } else if (!strncmp(pipename, "TCP@", 4)) {
1979 if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
1984 if (ws_stat64(pipename, &pipe_stat) < 0) {
1985 if (errno == ENOENT || errno == ENOTDIR)
1986 pcap_opts->cap_pipe_err = PIPNEXIST;
1988 g_snprintf(errmsg, errmsgl,
1989 "The capture session could not be initiated "
1990 "due to error getting information on pipe/socket: %s", g_strerror(errno));
1991 pcap_opts->cap_pipe_err = PIPERR;
1995 if (S_ISFIFO(pipe_stat.st_mode)) {
1996 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1998 g_snprintf(errmsg, errmsgl,
1999 "The capture session could not be initiated "
2000 "due to error on pipe open: %s", g_strerror(errno));
2001 pcap_opts->cap_pipe_err = PIPERR;
2004 } else if (S_ISSOCK(pipe_stat.st_mode)) {
2005 fd = socket(AF_UNIX, SOCK_STREAM, 0);
2007 g_snprintf(errmsg, errmsgl,
2008 "The capture session could not be initiated "
2009 "due to error on socket create: %s", g_strerror(errno));
2010 pcap_opts->cap_pipe_err = PIPERR;
2013 sa.sun_family = AF_UNIX;
2015 * The Single UNIX Specification says:
2017 * The size of sun_path has intentionally been left undefined.
2018 * This is because different implementations use different sizes.
2019 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
2020 * of 104. Since most implementations originate from BSD versions,
2021 * the size is typically in the range 92 to 108.
2023 * Applications should not assume a particular length for sun_path
2024 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
2028 * The <sys/un.h> header shall define the sockaddr_un structure,
2029 * which shall include at least the following members:
2031 * sa_family_t sun_family Address family.
2032 * char sun_path[] Socket pathname.
2034 * so we assume that it's an array, with a specified size,
2035 * and that the size reflects the maximum path length.
2037 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
2038 /* Path name too long */
2039 g_snprintf(errmsg, errmsgl,
2040 "The capture session coud not be initiated "
2041 "due to error on socket connect: Path name too long");
2042 pcap_opts->cap_pipe_err = PIPERR;
2046 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
2048 g_snprintf(errmsg, errmsgl,
2049 "The capture session coud not be initiated "
2050 "due to error on socket connect: %s", g_strerror(errno));
2051 pcap_opts->cap_pipe_err = PIPERR;
2056 if (S_ISCHR(pipe_stat.st_mode)) {
2058 * Assume the user specified an interface on a system where
2059 * interfaces are in /dev. Pretend we haven't seen it.
2061 pcap_opts->cap_pipe_err = PIPNEXIST;
2063 g_snprintf(errmsg, errmsgl,
2064 "The capture session could not be initiated because\n"
2065 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
2066 pcap_opts->cap_pipe_err = PIPERR;
2071 #define PIPE_STR "\\pipe\\"
2072 /* Under Windows, named pipes _must_ have the form
2073 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
2075 pncopy = g_strdup(pipename);
2076 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
2077 pos = strchr(pncopy + 3, '\\');
2078 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
2085 g_snprintf(errmsg, errmsgl,
2086 "The capture session could not be initiated because\n"
2087 "\"%s\" is neither an interface nor a pipe", pipename);
2088 pcap_opts->cap_pipe_err = PIPNEXIST;
2092 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
2094 /* Wait for the pipe to appear */
2097 if(strncmp(interface_opts.name,"\\\\.\\pipe\\",9)== 0)
2098 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
2100 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
2101 OPEN_EXISTING, 0, NULL);
2103 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
2106 if (GetLastError() != ERROR_PIPE_BUSY) {
2107 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2108 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2109 g_snprintf(errmsg, errmsgl,
2110 "The capture session on \"%s\" could not be started "
2111 "due to error on pipe open: %s (error %d)",
2112 pipename, utf_16to8(err_str), GetLastError());
2114 pcap_opts->cap_pipe_err = PIPERR;
2118 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
2119 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2120 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2121 g_snprintf(errmsg, errmsgl,
2122 "The capture session on \"%s\" timed out during "
2123 "pipe open: %s (error %d)",
2124 pipename, utf_16to8(err_str), GetLastError());
2126 pcap_opts->cap_pipe_err = PIPERR;
2133 pcap_opts->from_cap_pipe = TRUE;
2136 if (pcap_opts->from_cap_socket)
2139 /* read the pcap header */
2141 while (bytes_read < sizeof magic) {
2143 g_snprintf(errmsg, errmsgl, "Invalid file descriptor");
2147 sel_ret = cap_pipe_select(fd);
2149 g_snprintf(errmsg, errmsgl,
2150 "Unexpected error from select: %s", g_strerror(errno));
2152 } else if (sel_ret > 0) {
2153 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
2154 sizeof magic-bytes_read,
2155 pcap_opts->from_cap_socket);
2158 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2160 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2170 #if GLIB_CHECK_VERSION(2,31,0)
2171 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
2173 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
2176 pcap_opts->cap_pipe_buf = (char *) &magic;
2177 pcap_opts->cap_pipe_bytes_read = 0;
2178 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
2179 /* We don't have to worry about cap_pipe_read_mtx here */
2180 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2181 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2182 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2183 if (pcap_opts->cap_pipe_bytes_read == 0)
2184 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2186 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2195 case PCAP_NSEC_MAGIC:
2196 /* Host that wrote it has our byte order, and was running
2197 a program using either standard or ss990417 libpcap. */
2198 pcap_opts->cap_pipe_byte_swapped = FALSE;
2199 pcap_opts->cap_pipe_modified = FALSE;
2200 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
2202 case PCAP_MODIFIED_MAGIC:
2203 /* Host that wrote it has our byte order, but was running
2204 a program using either ss990915 or ss991029 libpcap. */
2205 pcap_opts->cap_pipe_byte_swapped = FALSE;
2206 pcap_opts->cap_pipe_modified = TRUE;
2208 case PCAP_SWAPPED_MAGIC:
2209 case PCAP_SWAPPED_NSEC_MAGIC:
2210 /* Host that wrote it has a byte order opposite to ours,
2211 and was running a program using either standard or
2212 ss990417 libpcap. */
2213 pcap_opts->cap_pipe_byte_swapped = TRUE;
2214 pcap_opts->cap_pipe_modified = FALSE;
2215 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2217 case PCAP_SWAPPED_MODIFIED_MAGIC:
2218 /* Host that wrote it out has a byte order opposite to
2219 ours, and was running a program using either ss990915
2220 or ss991029 libpcap. */
2221 pcap_opts->cap_pipe_byte_swapped = TRUE;
2222 pcap_opts->cap_pipe_modified = TRUE;
2225 /* Not a "libpcap" type we know about. */
2226 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2231 if (pcap_opts->from_cap_socket)
2234 /* Read the rest of the header */
2236 while (bytes_read < sizeof(struct pcap_hdr)) {
2237 sel_ret = cap_pipe_select(fd);
2239 g_snprintf(errmsg, errmsgl,
2240 "Unexpected error from select: %s", g_strerror(errno));
2242 } else if (sel_ret > 0) {
2243 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2244 sizeof(struct pcap_hdr) - bytes_read,
2245 pcap_opts->from_cap_socket);
2248 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2250 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
2260 pcap_opts->cap_pipe_buf = (char *) hdr;
2261 pcap_opts->cap_pipe_bytes_read = 0;
2262 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
2263 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2264 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2265 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2266 if (pcap_opts->cap_pipe_bytes_read == 0)
2267 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2269 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
2276 if (pcap_opts->cap_pipe_byte_swapped) {
2277 /* Byte-swap the header fields about which we care. */
2278 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
2279 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
2280 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
2281 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
2283 pcap_opts->linktype = hdr->network;
2285 if (hdr->version_major < 2) {
2286 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2290 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2291 pcap_opts->cap_pipe_err = PIPOK;
2292 pcap_opts->cap_pipe_fd = fd;
2296 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2297 pcap_opts->cap_pipe_err = PIPERR;
2298 cap_pipe_close(fd, pcap_opts->from_cap_socket);
2299 pcap_opts->cap_pipe_fd = -1;
2303 /* We read one record from the pipe, take care of byte order in the record
2304 * header, write the record to the capture file, and update capture statistics. */
2306 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2308 struct pcap_pkthdr phdr;
2309 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2312 #if !GLIB_CHECK_VERSION(2,31,18)
2320 #ifdef LOG_CAPTURE_VERBOSE
2321 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2324 switch (pcap_opts->cap_pipe_state) {
2326 case STATE_EXPECT_REC_HDR:
2328 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2331 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2332 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2333 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2334 pcap_opts->cap_pipe_bytes_read = 0;
2337 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2338 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2339 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2344 case STATE_READ_REC_HDR:
2346 if (pcap_opts->from_cap_socket)
2349 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2350 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
2353 result = PD_PIPE_EOF;
2355 result = PD_PIPE_ERR;
2358 pcap_opts->cap_pipe_bytes_read += b;
2362 #if GLIB_CHECK_VERSION(2,31,18)
2363 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2365 g_get_current_time(&wait_time);
2366 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2367 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2369 if (pcap_opts->cap_pipe_err == PIPEOF) {
2370 result = PD_PIPE_EOF;
2372 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2373 result = PD_PIPE_ERR;
2381 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2383 result = PD_REC_HDR_READ;
2386 case STATE_EXPECT_DATA:
2388 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2391 pcap_opts->cap_pipe_state = STATE_READ_DATA;
2392 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2393 pcap_opts->cap_pipe_bytes_read = 0;
2396 pcap_opts->cap_pipe_buf = (char *) data;
2397 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2398 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2403 case STATE_READ_DATA:
2405 if (pcap_opts->from_cap_socket)
2408 b = cap_pipe_read(pcap_opts->cap_pipe_fd,
2409 data+pcap_opts->cap_pipe_bytes_read,
2410 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
2411 pcap_opts->from_cap_socket);
2414 result = PD_PIPE_EOF;
2416 result = PD_PIPE_ERR;
2419 pcap_opts->cap_pipe_bytes_read += b;
2424 #if GLIB_CHECK_VERSION(2,31,18)
2425 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2427 g_get_current_time(&wait_time);
2428 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2429 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2430 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2431 if (pcap_opts->cap_pipe_err == PIPEOF) {
2432 result = PD_PIPE_EOF;
2434 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2435 result = PD_PIPE_ERR;
2443 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2445 result = PD_DATA_READ;
2449 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2452 } /* switch (pcap_opts->cap_pipe_state) */
2455 * We've now read as much data as we were expecting, so process it.
2459 case PD_REC_HDR_READ:
2460 /* We've read the header. Take care of byte order. */
2461 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2462 &pcap_opts->cap_pipe_rechdr.hdr);
2463 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2464 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2465 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2469 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2470 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2473 /* no data to read? fall through */
2476 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2477 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2478 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2479 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2480 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2483 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2485 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2487 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2491 pcap_opts->cap_pipe_err = PIPEOF;
2496 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2497 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2498 g_snprintf(errmsg, errmsgl,
2499 "Error reading from pipe: %s (error %d)",
2500 utf_16to8(err_str), GetLastError());
2503 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2511 pcap_opts->cap_pipe_err = PIPERR;
2512 /* Return here rather than inside the switch to prevent GCC warning */
2517 /** Open the capture input file (pcap or capture pipe).
2518 * Returns TRUE if it succeeds, FALSE otherwise. */
2520 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2521 char *errmsg, size_t errmsg_len,
2522 char *secondary_errmsg, size_t secondary_errmsg_len)
2524 gchar open_err_str[PCAP_ERRBUF_SIZE];
2525 gchar *sync_msg_str;
2526 interface_options interface_opts;
2527 pcap_options *pcap_opts;
2531 gchar *sync_secondary_msg_str;
2532 WORD wVersionRequested;
2536 /* XXX - opening Winsock on tshark? */
2538 /* Initialize Windows Socket if we are in a WIN32 OS
2539 This needs to be done before querying the interface for network/netmask */
2541 /* XXX - do we really require 1.1 or earlier?
2542 Are there any versions that support only 2.0 or higher? */
2543 wVersionRequested = MAKEWORD(1, 1);
2544 err = WSAStartup(wVersionRequested, &wsaData);
2548 case WSASYSNOTREADY:
2549 g_snprintf(errmsg, (gulong) errmsg_len,
2550 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2553 case WSAVERNOTSUPPORTED:
2554 g_snprintf(errmsg, (gulong) errmsg_len,
2555 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2556 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2559 case WSAEINPROGRESS:
2560 g_snprintf(errmsg, (gulong) errmsg_len,
2561 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2565 g_snprintf(errmsg, (gulong) errmsg_len,
2566 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2570 g_snprintf(errmsg, (gulong) errmsg_len,
2571 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2575 g_snprintf(errmsg, (gulong) errmsg_len,
2576 "Couldn't initialize Windows Sockets: error %d", err);
2579 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2583 if ((use_threads == FALSE) &&
2584 (capture_opts->ifaces->len > 1)) {
2585 g_snprintf(errmsg, (gulong) errmsg_len,
2586 "Using threads is required for capturing on multiple interfaces.");
2590 for (i = 0; i < capture_opts->ifaces->len; i++) {
2591 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2592 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2593 if (pcap_opts == NULL) {
2594 g_snprintf(errmsg, (gulong) errmsg_len,
2595 "Could not allocate memory.");
2598 pcap_opts->received = 0;
2599 pcap_opts->dropped = 0;
2600 pcap_opts->flushed = 0;
2601 pcap_opts->pcap_h = NULL;
2602 #ifdef MUST_DO_SELECT
2603 pcap_opts->pcap_fd = -1;
2605 pcap_opts->pcap_err = FALSE;
2606 pcap_opts->interface_id = i;
2607 pcap_opts->tid = NULL;
2608 pcap_opts->snaplen = 0;
2609 pcap_opts->linktype = -1;
2610 pcap_opts->ts_nsec = FALSE;
2611 pcap_opts->from_cap_pipe = FALSE;
2612 pcap_opts->from_cap_socket = FALSE;
2613 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2614 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2616 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2618 pcap_opts->cap_pipe_fd = -1;
2619 pcap_opts->cap_pipe_modified = FALSE;
2620 pcap_opts->cap_pipe_byte_swapped = FALSE;
2622 pcap_opts->cap_pipe_buf = NULL;
2624 pcap_opts->cap_pipe_bytes_to_read = 0;
2625 pcap_opts->cap_pipe_bytes_read = 0;
2626 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2627 pcap_opts->cap_pipe_err = PIPOK;
2629 #if GLIB_CHECK_VERSION(2,31,0)
2630 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2631 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2633 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2635 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2636 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2638 g_array_append_val(ld->pcaps, pcap_opts);
2640 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2641 pcap_opts->pcap_h = open_capture_device(capture_opts, &interface_opts, &open_err_str);
2643 if (pcap_opts->pcap_h != NULL) {
2644 /* we've opened "iface" as a network device */
2646 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2647 /* Find out if we're getting nanosecond-precision time stamps */
2648 pcap_opts->ts_nsec = have_high_resolution_timestamp(pcap_opts->pcap_h);
2652 /* try to set the capture buffer size */
2653 if (interface_opts.buffer_size > 1 &&
2654 pcap_setbuff(pcap_opts->pcap_h, interface_opts.buffer_size * 1024 * 1024) != 0) {
2655 sync_secondary_msg_str = g_strdup_printf(
2656 "The capture buffer size of %d MiB seems to be too high for your machine,\n"
2657 "the default of %d MiB will be used.\n"
2659 "Nonetheless, the capture is started.\n",
2660 interface_opts.buffer_size, DEFAULT_CAPTURE_BUFFER_SIZE);
2661 report_capture_error("Couldn't set the capture buffer size.",
2662 sync_secondary_msg_str);
2663 g_free(sync_secondary_msg_str);
2667 #if defined(HAVE_PCAP_SETSAMPLING)
2668 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2669 struct pcap_samp *samp;
2671 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2672 switch (interface_opts.sampling_method) {
2673 case CAPTURE_SAMP_BY_COUNT:
2674 samp->method = PCAP_SAMP_1_EVERY_N;
2677 case CAPTURE_SAMP_BY_TIMER:
2678 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2682 sync_msg_str = g_strdup_printf(
2683 "Unknown sampling method %d specified,\n"
2684 "continue without packet sampling",
2685 interface_opts.sampling_method);
2686 report_capture_error("Couldn't set the capture "
2687 "sampling", sync_msg_str);
2688 g_free(sync_msg_str);
2690 samp->value = interface_opts.sampling_param;
2692 report_capture_error("Couldn't set the capture sampling",
2693 "Cannot get packet sampling data structure");
2698 /* setting the data link type only works on real interfaces */
2699 if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2701 secondary_errmsg, secondary_errmsg_len)) {
2704 pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2706 /* We couldn't open "iface" as a network device. */
2707 /* Try to open it as a pipe */
2708 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2711 if (pcap_opts->cap_pipe_fd == -1) {
2713 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2715 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2716 /* Pipe doesn't exist, so output message for interface */
2717 get_capture_device_open_failure_messages(open_err_str,
2718 interface_opts.name,
2722 secondary_errmsg_len);
2725 * Else pipe (or file) does exist and cap_pipe_open_live() has
2730 /* cap_pipe_open_live() succeeded; don't want
2731 error message from pcap_open_live() */
2732 open_err_str[0] = '\0';
2736 /* XXX - will this work for tshark? */
2737 #ifdef MUST_DO_SELECT
2738 if (!pcap_opts->from_cap_pipe) {
2739 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2740 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2742 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2747 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2748 returned a warning; print it, but keep capturing. */
2749 if (open_err_str[0] != '\0') {
2750 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2751 report_capture_error(sync_msg_str, "");
2752 g_free(sync_msg_str);
2754 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2755 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2758 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2759 /* to remove any suid privileges. */
2760 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2761 /* (euid/egid have already previously been set to ruid/rgid. */
2762 /* (See comment in main() for details) */
2764 relinquish_special_privs_perm();
2766 relinquish_all_capabilities();
2771 /* close the capture input file (pcap or capture pipe) */
2772 static void capture_loop_close_input(loop_data *ld)
2775 pcap_options *pcap_opts;
2777 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2779 for (i = 0; i < ld->pcaps->len; i++) {
2780 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2781 /* if open, close the capture pipe "input file" */
2782 if (pcap_opts->cap_pipe_fd >= 0) {
2783 g_assert(pcap_opts->from_cap_pipe);
2784 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2785 pcap_opts->cap_pipe_fd = -1;
2788 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2789 CloseHandle(pcap_opts->cap_pipe_h);
2790 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2793 /* if open, close the pcap "input file" */
2794 if (pcap_opts->pcap_h != NULL) {
2795 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2796 pcap_close(pcap_opts->pcap_h);
2797 pcap_opts->pcap_h = NULL;
2804 /* Shut down windows sockets */
2810 /* init the capture filter */
2811 static initfilter_status_t
2812 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2813 const gchar * name, const gchar * cfilter)
2815 struct bpf_program fcode;
2817 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2819 /* capture filters only work on real interfaces */
2820 if (cfilter && !from_cap_pipe) {
2821 /* A capture filter was specified; set it up. */
2822 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2823 /* Treat this specially - our caller might try to compile this
2824 as a display filter and, if that succeeds, warn the user that
2825 the display and capture filter syntaxes are different. */
2826 return INITFILTER_BAD_FILTER;
2828 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2829 #ifdef HAVE_PCAP_FREECODE
2830 pcap_freecode(&fcode);
2832 return INITFILTER_OTHER_ERROR;
2834 #ifdef HAVE_PCAP_FREECODE
2835 pcap_freecode(&fcode);
2839 return INITFILTER_NO_ERROR;
2843 /* set up to write to the already-opened capture output file/files */
2845 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2849 pcap_options *pcap_opts;
2850 interface_options interface_opts;
2851 gboolean successful;
2853 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2855 if ((capture_opts->use_pcapng == FALSE) &&
2856 (capture_opts->ifaces->len > 1)) {
2857 g_snprintf(errmsg, errmsg_len,
2858 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
2862 /* Set up to write to the capture file. */
2863 if (capture_opts->multi_files_on) {
2864 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2866 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2867 if (ld->pdh == NULL) {
2872 if (capture_opts->use_pcapng) {
2874 GString *os_info_str;
2876 os_info_str = g_string_new("");
2877 get_os_version_info(os_info_str);
2879 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2880 successful = pcapng_write_session_header_block(ld->pdh,
2881 (const char *)capture_opts->capture_comment, /* Comment*/
2883 os_info_str->str, /* OS*/
2885 -1, /* section_length */
2890 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2891 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2892 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2893 if (pcap_opts->from_cap_pipe) {
2894 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2896 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2898 successful = pcapng_write_interface_description_block(global_ld.pdh,
2899 NULL, /* OPT_COMMENT 1 */
2900 interface_opts.name, /* IDB_NAME 2 */
2901 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2902 interface_opts.cfilter, /* IDB_FILTER 11 */
2903 os_info_str->str, /* IDB_OS 12 */
2904 pcap_opts->linktype,
2906 &(global_ld.bytes_written),
2907 0, /* IDB_IF_SPEED 8 */
2908 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2912 g_string_free(os_info_str, TRUE);
2915 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2916 if (pcap_opts->from_cap_pipe) {
2917 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2919 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2921 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2922 pcap_opts->ts_nsec, &ld->bytes_written, &err);
2930 if (ld->pdh == NULL) {
2931 /* We couldn't set up to write to the capture file. */
2932 /* XXX - use cf_open_error_message from tshark instead? */
2937 g_snprintf(errmsg, errmsg_len,
2938 "The file to which the capture would be"
2939 " saved (\"%s\") could not be opened: Error %d.",
2940 capture_opts->save_file, err);
2942 g_snprintf(errmsg, errmsg_len,
2943 "The file to which the capture would be"
2944 " saved (\"%s\") could not be opened: %s.",
2945 capture_opts->save_file, g_strerror(err));
2957 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2961 pcap_options *pcap_opts;
2962 guint64 end_time = create_timestamp();
2964 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2966 if (capture_opts->multi_files_on) {
2967 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2969 if (capture_opts->use_pcapng) {
2970 for (i = 0; i < global_ld.pcaps->len; i++) {
2971 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2972 if (!pcap_opts->from_cap_pipe) {
2973 guint64 isb_ifrecv, isb_ifdrop;
2974 struct pcap_stat stats;
2976 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
2977 isb_ifrecv = pcap_opts->received;
2978 isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
2980 isb_ifrecv = G_MAXUINT64;
2981 isb_ifdrop = G_MAXUINT64;
2983 pcapng_write_interface_statistics_block(ld->pdh,
2986 "Counters provided by dumpcap",
2995 if (fclose(ld->pdh) == EOF) {
2996 if (err_close != NULL) {
3006 /* dispatch incoming packets (pcap or capture pipe)
3008 * Waits for incoming packets to be available, and calls pcap_dispatch()
3009 * to cause them to be processed.
3011 * Returns the number of packets which were processed.
3013 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3014 * packet-batching behaviour does not cause packets to get held back
3018 capture_loop_dispatch(loop_data *ld,
3019 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
3022 gint packet_count_before;
3023 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
3028 packet_count_before = ld->packet_count;
3029 if (pcap_opts->from_cap_pipe) {
3030 /* dispatch from capture pipe */
3031 #ifdef LOG_CAPTURE_VERBOSE
3032 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3035 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
3037 if (sel_ret < 0 && errno != EINTR) {
3038 g_snprintf(errmsg, errmsg_len,
3039 "Unexpected error from select: %s", g_strerror(errno));
3040 report_capture_error(errmsg, please_report);
3045 * "select()" says we can read from the pipe without blocking
3048 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
3058 /* dispatch from pcap */
3059 #ifdef MUST_DO_SELECT
3061 * If we have "pcap_get_selectable_fd()", we use it to get the
3062 * descriptor on which to select; if that's -1, it means there
3063 * is no descriptor on which you can do a "select()" (perhaps
3064 * because you're capturing on a special device, and that device's
3065 * driver unfortunately doesn't support "select()", in which case
3066 * we don't do the select - which means it might not be possible
3067 * to stop a capture until a packet arrives. If that's unacceptable,
3068 * plead with whoever supplies the software for that device to add
3069 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3070 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3071 * later, so it can use pcap_breakloop().
3073 #ifdef LOG_CAPTURE_VERBOSE
3074 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3076 if (pcap_opts->pcap_fd != -1) {
3077 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
3080 * "select()" says we can read from it without blocking; go for
3083 * We don't have pcap_breakloop(), so we only process one packet
3084 * per pcap_dispatch() call, to allow a signal to stop the
3085 * processing immediately, rather than processing all packets
3086 * in a batch before quitting.
3089 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3091 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3095 /* Error, rather than pcap_breakloop(). */
3096 pcap_opts->pcap_err = TRUE;
3098 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3101 if (sel_ret < 0 && errno != EINTR) {
3102 g_snprintf(errmsg, errmsg_len,
3103 "Unexpected error from select: %s", g_strerror(errno));
3104 report_capture_error(errmsg, please_report);
3110 #endif /* MUST_DO_SELECT */
3112 /* dispatch from pcap without select */
3114 #ifdef LOG_CAPTURE_VERBOSE
3115 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3119 * On Windows, we don't support asynchronously telling a process to
3120 * stop capturing; instead, we check for an indication on a pipe
3121 * after processing packets. We therefore process only one packet
3122 * at a time, so that we can check the pipe after every packet.
3125 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3127 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3131 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3133 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3138 /* Error, rather than pcap_breakloop(). */
3139 pcap_opts->pcap_err = TRUE;
3141 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3143 #else /* pcap_next_ex */
3144 #ifdef LOG_CAPTURE_VERBOSE
3145 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3147 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3150 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3151 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
3152 * This should be fixed in the WinPcap 4.0 alpha release.
3154 * For reference, an example remote interface:
3155 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3158 /* emulate dispatch from pcap */
3161 struct pcap_pkthdr *pkt_header;
3166 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
3168 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3170 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3175 pcap_opts->pcap_err = TRUE;
3179 #endif /* pcap_next_ex */
3183 #ifdef LOG_CAPTURE_VERBOSE
3184 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3187 return ld->packet_count - packet_count_before;
3191 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3192 * want to grab only the characters between the '{' and '}' delimiters.
3194 * Returns a GString that must be freed with g_string_free(). */
3196 isolate_uuid(const char *iface)
3201 ptr = strchr(iface, '{');
3203 return g_string_new(iface);
3204 gstr = g_string_new(ptr + 1);
3206 ptr = strchr(gstr->str, '}');
3210 gstr = g_string_truncate(gstr, ptr - gstr->str);
3215 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3216 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3218 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3219 char *errmsg, int errmsg_len)
3222 gchar *capfile_name;
3224 gboolean is_tempfile;
3226 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3227 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3229 if (capture_opts->save_file != NULL) {
3230 /* We return to the caller while the capture is in progress.
3231 * Therefore we need to take a copy of save_file in
3232 * case the caller destroys it after we return.
3234 capfile_name = g_strdup(capture_opts->save_file);
3236 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3237 if (capture_opts->multi_files_on) {
3238 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3239 g_snprintf(errmsg, errmsg_len,
3240 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3241 g_free(capfile_name);
3244 if (strcmp(capfile_name, "-") == 0) {
3245 /* write to stdout */
3248 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3249 _setmode(1, O_BINARY);
3252 } /* if (...output_to_pipe ... */
3255 if (capture_opts->multi_files_on) {
3256 /* ringbuffer is enabled */
3257 *save_file_fd = ringbuf_init(capfile_name,
3258 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3259 capture_opts->group_read_access);
3261 /* we need the ringbuf name */
3262 if (*save_file_fd != -1) {
3263 g_free(capfile_name);
3264 capfile_name = g_strdup(ringbuf_current_filename());
3267 /* Try to open/create the specified file for use as a capture buffer. */
3268 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
3269 (capture_opts->group_read_access) ? 0640 : 0600);
3272 is_tempfile = FALSE;
3274 /* Choose a random name for the temporary capture buffer */
3275 if (global_capture_opts.ifaces->len > 1) {
3276 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3279 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
3281 /* use the generic portion of the interface guid to form the basis of the filename */
3282 if (strncmp("NPF_{", basename, 5)==0)
3284 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3286 iface = isolate_uuid(basename);
3288 basename = g_strdup(iface->str);
3289 g_string_free(iface, TRUE);
3292 /* generate the temp file name prefix...
3293 * It would be nice if we could specify a pcapng/pcap filename suffix,
3294 * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
3295 if (capture_opts->use_pcapng) {
3296 prefix = g_strconcat("wireshark_pcapng_", basename, NULL);
3298 prefix = g_strconcat("wireshark_pcap_", basename, NULL);
3302 *save_file_fd = create_tempfile(&tmpname, prefix);
3304 capfile_name = g_strdup(tmpname);
3308 /* did we fail to open the output file? */
3309 if (*save_file_fd == -1) {
3311 g_snprintf(errmsg, errmsg_len,
3312 "The temporary file to which the capture would be saved (\"%s\") "
3313 "could not be opened: %s.", capfile_name, g_strerror(errno));
3315 if (capture_opts->multi_files_on) {
3316 ringbuf_error_cleanup();
3319 g_snprintf(errmsg, errmsg_len,
3320 "The file to which the capture would be saved (\"%s\") "
3321 "could not be opened: %s.", capfile_name,
3324 g_free(capfile_name);
3328 if (capture_opts->save_file != NULL) {
3329 g_free(capture_opts->save_file);
3331 capture_opts->save_file = capfile_name;
3332 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3333 "g_free(capfile_name)". */
3339 /* Do the work of handling either the file size or file duration capture
3340 conditions being reached, and switching files or stopping. */
3342 do_file_switch_or_stop(capture_options *capture_opts,
3343 condition *cnd_autostop_files,
3344 condition *cnd_autostop_size,
3345 condition *cnd_file_duration)
3348 pcap_options *pcap_opts;
3349 interface_options interface_opts;
3350 gboolean successful;
3352 if (capture_opts->multi_files_on) {
3353 if (cnd_autostop_files != NULL &&
3354 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
3355 /* no files left: stop here */
3356 global_ld.go = FALSE;
3360 /* Switch to the next ringbuffer file */
3361 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3362 &global_ld.save_file_fd, &global_ld.err)) {
3364 /* File switch succeeded: reset the conditions */
3365 global_ld.bytes_written = 0;
3366 if (capture_opts->use_pcapng) {
3368 GString *os_info_str;
3370 os_info_str = g_string_new("");
3371 get_os_version_info(os_info_str);
3373 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
3374 successful = pcapng_write_session_header_block(global_ld.pdh,
3377 os_info_str->str, /* OS */
3379 -1, /* section_length */
3380 &(global_ld.bytes_written),
3384 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3385 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3386 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3387 successful = pcapng_write_interface_description_block(global_ld.pdh,
3388 NULL, /* OPT_COMMENT 1 */
3389 interface_opts.name, /* IDB_NAME 2 */
3390 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3391 interface_opts.cfilter, /* IDB_FILTER 11 */
3392 os_info_str->str, /* IDB_OS 12 */
3393 pcap_opts->linktype,
3395 &(global_ld.bytes_written),
3396 0, /* IDB_IF_SPEED 8 */
3397 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3401 g_string_free(os_info_str, TRUE);
3404 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3405 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3406 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3409 fclose(global_ld.pdh);
3410 global_ld.pdh = NULL;
3411 global_ld.go = FALSE;
3414 if (cnd_autostop_size)
3415 cnd_reset(cnd_autostop_size);
3416 if (cnd_file_duration)
3417 cnd_reset(cnd_file_duration);
3418 fflush(global_ld.pdh);
3420 report_packet_count(global_ld.inpkts_to_sync_pipe);
3421 global_ld.inpkts_to_sync_pipe = 0;
3422 report_new_capture_file(capture_opts->save_file);
3424 /* File switch failed: stop here */
3425 global_ld.go = FALSE;
3429 /* single file, stop now */
3430 global_ld.go = FALSE;
3437 pcap_read_handler(void* arg)
3439 pcap_options *pcap_opts;
3440 char errmsg[MSG_MAX_LENGTH+1];
3442 pcap_opts = (pcap_options *)arg;
3444 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3445 pcap_opts->interface_id);
3447 while (global_ld.go) {
3448 /* dispatch incoming packets */
3449 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3451 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3452 pcap_opts->interface_id);
3453 g_thread_exit(NULL);
3457 /* Do the low-level work of a capture.
3458 Returns TRUE if it succeeds, FALSE otherwise. */
3460 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3463 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3465 struct timeval upd_time, cur_time;
3469 condition *cnd_file_duration = NULL;
3470 condition *cnd_autostop_files = NULL;
3471 condition *cnd_autostop_size = NULL;
3472 condition *cnd_autostop_duration = NULL;
3475 gboolean cfilter_error = FALSE;
3476 char errmsg[MSG_MAX_LENGTH+1];
3477 char secondary_errmsg[MSG_MAX_LENGTH+1];
3478 pcap_options *pcap_opts;
3479 interface_options interface_opts;
3480 guint i, error_index = 0;
3483 *secondary_errmsg = '\0';
3485 /* init the loop data */
3486 global_ld.go = TRUE;
3487 global_ld.packet_count = 0;
3489 global_ld.report_packet_count = FALSE;
3491 if (capture_opts->has_autostop_packets)
3492 global_ld.packet_max = capture_opts->autostop_packets;
3494 global_ld.packet_max = 0; /* no limit */
3495 global_ld.inpkts_to_sync_pipe = 0;
3496 global_ld.err = 0; /* no error seen yet */
3497 global_ld.pdh = NULL;
3498 global_ld.autostop_files = 0;
3499 global_ld.save_file_fd = -1;
3501 /* We haven't yet gotten the capture statistics. */
3502 *stats_known = FALSE;
3504 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3505 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3507 /* open the "input file" from network interface or capture pipe */
3508 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3509 secondary_errmsg, sizeof(secondary_errmsg))) {
3512 for (i = 0; i < capture_opts->ifaces->len; i++) {
3513 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3514 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3515 /* init the input filter from the network interface (capture pipe will do nothing) */
3517 * When remote capturing WinPCap crashes when the capture filter
3518 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3521 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3522 interface_opts.name,
3523 interface_opts.cfilter?interface_opts.cfilter:"")) {
3525 case INITFILTER_NO_ERROR:
3528 case INITFILTER_BAD_FILTER:
3529 cfilter_error = TRUE;
3531 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3534 case INITFILTER_OTHER_ERROR:
3535 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3536 pcap_geterr(pcap_opts->pcap_h));
3537 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3542 /* If we're supposed to write to a capture file, open it for output
3543 (temporary/specified name/ringbuffer) */
3544 if (capture_opts->saving_to_file) {
3545 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3546 errmsg, sizeof(errmsg))) {
3550 /* set up to write to the already-opened capture output file/files */
3551 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3556 /* XXX - capture SIGTERM and close the capture, in case we're on a
3557 Linux 2.0[.x] system and you have to explicitly close the capture
3558 stream in order to turn promiscuous mode off? We need to do that
3559 in other places as well - and I don't think that works all the
3560 time in any case, due to libpcap bugs. */
3562 /* Well, we should be able to start capturing.
3564 Sync out the capture file, so the header makes it to the file system,
3565 and send a "capture started successfully and capture file created"
3566 message to our parent so that they'll open the capture file and
3567 update its windows to indicate that we have a live capture in
3569 fflush(global_ld.pdh);
3570 report_new_capture_file(capture_opts->save_file);
3573 /* initialize capture stop (and alike) conditions */
3574 init_capture_stop_conditions();
3575 /* create stop conditions */
3576 if (capture_opts->has_autostop_filesize) {
3577 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3578 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3581 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3583 if (capture_opts->has_autostop_duration)
3584 cnd_autostop_duration =
3585 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3587 if (capture_opts->multi_files_on) {
3588 if (capture_opts->has_file_duration)
3590 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3592 if (capture_opts->has_autostop_files)
3593 cnd_autostop_files =
3594 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3597 /* init the time values */
3599 upd_time = GetTickCount();
3601 gettimeofday(&upd_time, NULL);
3603 start_time = create_timestamp();
3604 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3606 /* WOW, everything is prepared! */
3607 /* please fasten your seat belts, we will enter now the actual capture loop */
3609 pcap_queue = g_async_queue_new();
3610 pcap_queue_bytes = 0;
3611 pcap_queue_packets = 0;
3612 for (i = 0; i < global_ld.pcaps->len; i++) {
3613 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3614 #if GLIB_CHECK_VERSION(2,31,0)
3615 /* XXX - Add an interface name here? */
3616 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3618 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3622 while (global_ld.go) {
3623 /* dispatch incoming packets */
3625 pcap_queue_element *queue_element;
3626 #if GLIB_CHECK_VERSION(2,31,18)
3628 g_async_queue_lock(pcap_queue);
3629 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3631 GTimeVal write_thread_time;
3633 g_get_current_time(&write_thread_time);
3634 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3635 g_async_queue_lock(pcap_queue);
3636 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3638 if (queue_element) {
3639 pcap_queue_bytes -= queue_element->phdr.caplen;
3640 pcap_queue_packets -= 1;
3642 g_async_queue_unlock(pcap_queue);
3643 if (queue_element) {
3644 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3645 "Dequeued a packet of length %d captured on interface %d.",
3646 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3648 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3649 &queue_element->phdr,
3651 g_free(queue_element->pd);
3652 g_free(queue_element);
3658 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3659 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3660 sizeof(errmsg), pcap_opts);
3663 /* Were we asked to print packet counts by the SIGINFO handler? */
3664 if (global_ld.report_packet_count) {
3665 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3666 plurality(global_ld.packet_count, "", "s"));
3667 global_ld.report_packet_count = FALSE;
3672 /* any news from our parent (signal pipe)? -> just stop the capture */
3673 if (!signal_pipe_check_running()) {
3674 global_ld.go = FALSE;
3679 global_ld.inpkts_to_sync_pipe += inpkts;
3681 /* check capture size condition */
3682 if (cnd_autostop_size != NULL &&
3683 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3684 /* Capture size limit reached, do we have another file? */
3685 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3686 cnd_autostop_size, cnd_file_duration))
3688 } /* cnd_autostop_size */
3689 if (capture_opts->output_to_pipe) {
3690 fflush(global_ld.pdh);
3694 /* Only update once every 500ms so as not to overload slow displays.
3695 * This also prevents too much context-switching between the dumpcap
3696 * and wireshark processes.
3698 #define DUMPCAP_UPD_TIME 500
3701 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3702 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3704 gettimeofday(&cur_time, NULL);
3705 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3706 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3709 upd_time = cur_time;
3712 if (pcap_stats(pch, stats) >= 0) {
3713 *stats_known = TRUE;
3716 /* Let the parent process know. */
3717 if (global_ld.inpkts_to_sync_pipe) {
3719 fflush(global_ld.pdh);
3721 /* Send our parent a message saying we've written out
3722 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3724 report_packet_count(global_ld.inpkts_to_sync_pipe);
3726 global_ld.inpkts_to_sync_pipe = 0;
3729 /* check capture duration condition */
3730 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3731 /* The maximum capture time has elapsed; stop the capture. */
3732 global_ld.go = FALSE;
3736 /* check capture file duration condition */
3737 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3738 /* duration limit reached, do we have another file? */
3739 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3740 cnd_autostop_size, cnd_file_duration))
3742 } /* cnd_file_duration */
3746 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3748 pcap_queue_element *queue_element;
3750 for (i = 0; i < global_ld.pcaps->len; i++) {
3751 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3752 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3753 pcap_opts->interface_id);
3754 g_thread_join(pcap_opts->tid);
3755 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3756 pcap_opts->interface_id);
3759 g_async_queue_lock(pcap_queue);
3760 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3761 if (queue_element) {
3762 pcap_queue_bytes -= queue_element->phdr.caplen;
3763 pcap_queue_packets -= 1;
3765 g_async_queue_unlock(pcap_queue);
3766 if (queue_element == NULL) {
3769 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3770 "Dequeued a packet of length %d captured on interface %d.",
3771 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3772 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3773 &queue_element->phdr,
3775 g_free(queue_element->pd);
3776 g_free(queue_element);
3777 global_ld.inpkts_to_sync_pipe += 1;
3778 if (capture_opts->output_to_pipe) {
3779 fflush(global_ld.pdh);
3785 /* delete stop conditions */
3786 if (cnd_file_duration != NULL)
3787 cnd_delete(cnd_file_duration);
3788 if (cnd_autostop_files != NULL)
3789 cnd_delete(cnd_autostop_files);
3790 if (cnd_autostop_size != NULL)
3791 cnd_delete(cnd_autostop_size);
3792 if (cnd_autostop_duration != NULL)
3793 cnd_delete(cnd_autostop_duration);
3795 /* did we have a pcap (input) error? */
3796 for (i = 0; i < capture_opts->ifaces->len; i++) {
3797 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3798 if (pcap_opts->pcap_err) {
3799 /* On Linux, if an interface goes down while you're capturing on it,
3800 you'll get a "recvfrom: Network is down" or
3801 "The interface went down" error (ENETDOWN).
3802 (At least you will if g_strerror() doesn't show a local translation
3805 On FreeBSD and OS X, if a network adapter disappears while
3806 you're capturing on it, you'll get a "read: Device not configured"
3807 error (ENXIO). (See previous parenthetical note.)
3809 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3811 These should *not* be reported to the Wireshark developers. */
3814 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3815 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3816 strcmp(cap_err_str, "The interface went down") == 0 ||
3817 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3818 strcmp(cap_err_str, "read: I/O error") == 0 ||
3819 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3820 report_capture_error("The network adapter on which the capture was being done "
3821 "is no longer running; the capture has stopped.",
3824 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3826 report_capture_error(errmsg, please_report);
3829 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3830 report_capture_error(errmsg, "");
3834 /* did we have an output error while capturing? */
3835 if (global_ld.err == 0) {
3838 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3839 global_ld.err, FALSE);
3840 report_capture_error(errmsg, please_report);
3844 if (capture_opts->saving_to_file) {
3845 /* close the output file */
3846 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3850 /* there might be packets not yet notified to the parent */
3851 /* (do this after closing the file, so all packets are already flushed) */
3852 if (global_ld.inpkts_to_sync_pipe) {
3854 report_packet_count(global_ld.inpkts_to_sync_pipe);
3855 global_ld.inpkts_to_sync_pipe = 0;
3858 /* If we've displayed a message about a write error, there's no point
3859 in displaying another message about an error on close. */
3860 if (!close_ok && write_ok) {
3861 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3863 report_capture_error(errmsg, "");
3867 * XXX We exhibit different behaviour between normal mode and sync mode
3868 * when the pipe is stdin and not already at EOF. If we're a child, the
3869 * parent's stdin isn't closed, so if the user starts another capture,
3870 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3871 * will say "Unrecognized libpcap format". On the other hand, in normal
3872 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3875 report_capture_count(TRUE);
3877 /* get packet drop statistics from pcap */
3878 for (i = 0; i < capture_opts->ifaces->len; i++) {
3880 guint32 pcap_dropped = 0;
3882 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3883 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3884 received = pcap_opts->received;
3885 if (pcap_opts->pcap_h != NULL) {
3886 g_assert(!pcap_opts->from_cap_pipe);
3887 /* Get the capture statistics, so we know how many packets were dropped. */
3889 * Older versions of libpcap didn't set ps_ifdrop on some
3890 * platforms; initialize it to 0 to handle that.
3892 stats->ps_ifdrop = 0;
3893 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3894 *stats_known = TRUE;
3895 /* Let the parent process know. */
3896 pcap_dropped += stats->ps_drop;
3898 g_snprintf(errmsg, sizeof(errmsg),
3899 "Can't get packet-drop statistics: %s",
3900 pcap_geterr(pcap_opts->pcap_h));
3901 report_capture_error(errmsg, please_report);
3904 report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
3907 /* close the input file (pcap or capture pipe) */
3908 capture_loop_close_input(&global_ld);
3910 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
3912 /* ok, if the write and the close were successful. */
3913 return write_ok && close_ok;
3916 if (capture_opts->multi_files_on) {
3917 /* cleanup ringbuffer */
3918 ringbuf_error_cleanup();
3920 /* We can't use the save file, and we have no FILE * for the stream
3921 to close in order to close it, so close the FD directly. */
3922 if (global_ld.save_file_fd != -1) {
3923 ws_close(global_ld.save_file_fd);
3926 /* We couldn't even start the capture, so get rid of the capture
3928 if (capture_opts->save_file != NULL) {
3929 ws_unlink(capture_opts->save_file);
3930 g_free(capture_opts->save_file);
3933 capture_opts->save_file = NULL;
3935 report_cfilter_error(capture_opts, error_index, errmsg);
3937 report_capture_error(errmsg, secondary_errmsg);
3939 /* close the input file (pcap or cap_pipe) */
3940 capture_loop_close_input(&global_ld);
3942 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3949 capture_loop_stop(void)
3951 #ifdef HAVE_PCAP_BREAKLOOP
3953 pcap_options *pcap_opts;
3955 for (i = 0; i < global_ld.pcaps->len; i++) {
3956 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3957 if (pcap_opts->pcap_h != NULL)
3958 pcap_breakloop(pcap_opts->pcap_h);
3961 global_ld.go = FALSE;
3966 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3967 int err, gboolean is_close)
3972 g_snprintf(errmsg, errmsglen,
3973 "Not all the packets could be written to the file"
3974 " to which the capture was being saved\n"
3975 "(\"%s\") because there is no space left on the file system\n"
3976 "on which that file resides.",
3982 g_snprintf(errmsg, errmsglen,
3983 "Not all the packets could be written to the file"
3984 " to which the capture was being saved\n"
3985 "(\"%s\") because you are too close to, or over,"
3986 " your disk quota\n"
3987 "on the file system on which that file resides.",
3994 g_snprintf(errmsg, errmsglen,
3995 "The file to which the capture was being saved\n"
3996 "(\"%s\") could not be closed: %s.",
3997 fname, g_strerror(err));
3999 g_snprintf(errmsg, errmsglen,
4000 "An error occurred while writing to the file"
4001 " to which the capture was being saved\n"
4003 fname, g_strerror(err));
4010 /* one packet was captured, process it */
4012 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4015 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4017 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
4019 /* We may be called multiple times from pcap_dispatch(); if we've set
4020 the "stop capturing" flag, ignore this packet, as we're not
4021 supposed to be saving any more packets. */
4022 if (!global_ld.go) {
4023 pcap_opts->flushed++;
4027 if (global_ld.pdh) {
4028 gboolean successful;
4030 /* We're supposed to write the packet to a file; do so.
4031 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4032 "ld->err" to the error. */
4033 if (global_capture_opts.use_pcapng) {
4034 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4036 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4037 phdr->caplen, phdr->len,
4038 pcap_opts->interface_id,
4041 &global_ld.bytes_written, &err);
4043 successful = libpcap_write_packet(global_ld.pdh,
4044 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4045 phdr->caplen, phdr->len,
4047 &global_ld.bytes_written, &err);
4050 global_ld.go = FALSE;
4051 global_ld.err = err;
4052 pcap_opts->dropped++;
4054 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4055 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4056 "Wrote a packet of length %d captured on interface %u.",
4057 phdr->caplen, pcap_opts->interface_id);
4059 global_ld.packet_count++;
4060 pcap_opts->received++;
4061 /* if the user told us to stop after x packets, do we already have enough? */
4062 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4063 global_ld.go = FALSE;
4069 /* one packet was captured, queue it */
4071 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4074 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4075 pcap_queue_element *queue_element;
4076 gboolean limit_reached;
4078 /* We may be called multiple times from pcap_dispatch(); if we've set
4079 the "stop capturing" flag, ignore this packet, as we're not
4080 supposed to be saving any more packets. */
4081 if (!global_ld.go) {
4082 pcap_opts->flushed++;
4086 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4087 if (queue_element == NULL) {
4088 pcap_opts->dropped++;
4091 queue_element->pcap_opts = pcap_opts;
4092 queue_element->phdr = *phdr;
4093 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4094 if (queue_element->pd == NULL) {
4095 pcap_opts->dropped++;
4096 g_free(queue_element);
4099 memcpy(queue_element->pd, pd, phdr->caplen);
4100 g_async_queue_lock(pcap_queue);
4101 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4102 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4103 limit_reached = FALSE;
4104 g_async_queue_push_unlocked(pcap_queue, queue_element);
4105 pcap_queue_bytes += phdr->caplen;
4106 pcap_queue_packets += 1;
4108 limit_reached = TRUE;
4110 g_async_queue_unlock(pcap_queue);
4111 if (limit_reached) {
4112 pcap_opts->dropped++;
4113 g_free(queue_element->pd);
4114 g_free(queue_element);
4115 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4116 "Dropped a packet of length %d captured on interface %u.",
4117 phdr->caplen, pcap_opts->interface_id);
4119 pcap_opts->received++;
4120 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4121 "Queued a packet of length %d captured on interface %u.",
4122 phdr->caplen, pcap_opts->interface_id);
4124 /* I don't want to hold the mutex over the debug output. So the
4125 output may be wrong */
4126 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4127 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4128 pcap_queue_bytes, pcap_queue_packets);
4132 set_80211_channel(const char *iface, const char *opt)
4134 int freq = 0, type, ret;
4135 gchar **options = NULL;
4137 options = g_strsplit_set(opt, ",", 2);
4140 freq = atoi(options[0]);
4143 type = ws80211_str_to_chan_type(options[1]);
4152 ret = ws80211_init();
4154 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4158 ret = ws80211_set_freq(iface, freq, type);
4161 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4167 pipe_write_block(2, SP_SUCCESS, NULL);
4171 g_strfreev(options);
4176 get_dumpcap_compiled_info(GString *str)
4178 /* Capture libraries */
4179 g_string_append(str, ", ");
4180 get_compiled_caplibs_version(str);
4183 g_string_append(str, ", ");
4185 g_string_append(str, "with libz ");
4187 g_string_append(str, ZLIB_VERSION);
4188 #else /* ZLIB_VERSION */
4189 g_string_append(str, "(version unknown)");
4190 #endif /* ZLIB_VERSION */
4191 #else /* HAVE_LIBZ */
4192 g_string_append(str, "without libz");
4193 #endif /* HAVE_LIBZ */
4197 get_dumpcap_runtime_info(GString *str)
4199 /* Capture libraries */
4200 g_string_append(str, ", ");
4201 get_runtime_caplibs_version(str);
4204 #if defined(HAVE_LIBZ) && !defined(_WIN32)
4205 g_string_append_printf(str, ", with libz %s", zlibVersion());
4209 /* And now our feature presentation... [ fade to music ] */
4211 main(int argc, char *argv[])
4213 GString *comp_info_str;
4214 GString *runtime_info_str;
4216 static const struct option long_options[] = {
4217 {(char *)"help", no_argument, NULL, 'h'},
4218 {(char *)"version", no_argument, NULL, 'v'},
4219 LONGOPT_CAPTURE_COMMON
4223 gboolean arg_error = FALSE;
4228 struct sigaction action, oldaction;
4231 gboolean start_capture = TRUE;
4232 gboolean stats_known;
4233 struct pcap_stat stats;
4234 GLogLevelFlags log_flags;
4235 gboolean list_interfaces = FALSE;
4236 gboolean list_link_layer_types = FALSE;
4237 #ifdef HAVE_BPF_IMAGE
4238 gboolean print_bpf_code = FALSE;
4240 gboolean set_chan = FALSE;
4241 gchar *set_chan_arg = NULL;
4242 gboolean machine_readable = FALSE;
4243 gboolean print_statistics = FALSE;
4244 int status, run_once_args = 0;
4247 #if defined(__APPLE__) && defined(__LP64__)
4248 struct utsname osinfo;
4252 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
4254 /* Get the compile-time version information string */
4255 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4257 /* Get the run-time version information string */
4258 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4260 /* Add it to the information to be reported on a crash. */
4261 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
4266 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
4269 arg_list_utf_16to8(argc, argv);
4270 create_app_running_mutex();
4273 * Initialize our DLL search path. MUST be called before LoadLibrary
4276 ws_init_dll_search_path();
4279 #ifdef HAVE_BPF_IMAGE
4280 #define OPTSTRING_d "d"
4282 #define OPTSTRING_d ""
4285 #ifdef HAVE_PCAP_REMOTE
4286 #define OPTSTRING_r "r"
4287 #define OPTSTRING_u "u"
4289 #define OPTSTRING_r ""
4290 #define OPTSTRING_u ""
4293 #ifdef HAVE_PCAP_SETSAMPLING
4294 #define OPTSTRING_m "m:"
4296 #define OPTSTRING_m ""
4299 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
4301 #ifdef DEBUG_CHILD_DUMPCAP
4302 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4303 fprintf (stderr, "Unable to open debug log file .\n");
4308 #if defined(__APPLE__) && defined(__LP64__)
4310 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4311 * a bug workaround - timeouts less than 1 second don't work with libpcap
4312 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4313 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4314 * The problem is extremely unlikely to be reintroduced in a future
4317 if (uname(&osinfo) == 0) {
4319 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
4320 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4321 * number of 10.0.0, not 10.1.0 - go figure).
4323 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4324 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4325 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4326 need_timeout_workaround = TRUE;
4331 * Determine if dumpcap is being requested to run in a special
4332 * capture_child mode by going thru the command line args to see if
4333 * a -Z is present. (-Z is a hidden option).
4335 * The primary result of running in capture_child mode is that
4336 * all messages sent out on stderr are in a special type/len/string
4337 * format to allow message processing by type. These messages include
4338 * error messages if dumpcap fails to start the operation it was
4339 * requested to do, as well as various "status" messages which are sent
4340 * when an actual capture is in progress, and a "success" message sent
4341 * if dumpcap was requested to perform an operation other than a
4344 * Capture_child mode would normally be requested by a parent process
4345 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4346 * to which dumpcap stderr has been redirected. It might also have
4347 * another pipe to obtain dumpcap stdout output; for operations other
4348 * than a capture, that information is formatted specially for easier
4349 * parsing by the parent process.
4351 * Capture_child mode needs to be determined immediately upon
4352 * startup so that any messages generated by dumpcap in this mode
4353 * (eg: during initialization) will be formatted properly.
4356 for (i=1; i<argc; i++) {
4357 if (strcmp("-Z", argv[i]) == 0) {
4358 capture_child = TRUE;
4359 machine_readable = TRUE; /* request machine-readable output */
4361 /* set output pipe to binary mode, to avoid ugly text conversions */
4362 _setmode(2, O_BINARY);
4367 /* The default_log_handler will use stdout, which makes trouble in */
4368 /* capture child mode, as it uses stdout for its sync_pipe. */
4369 /* So: the filtering is done in the console_log_handler and not here.*/
4370 /* We set the log handlers right up front to make sure that any log */
4371 /* messages when running as child will be sent back to the parent */
4372 /* with the correct format. */
4377 G_LOG_LEVEL_CRITICAL|
4378 G_LOG_LEVEL_WARNING|
4379 G_LOG_LEVEL_MESSAGE|
4383 G_LOG_FLAG_RECURSION);
4385 g_log_set_handler(NULL,
4387 console_log_handler, NULL /* user_data */);
4388 g_log_set_handler(LOG_DOMAIN_MAIN,
4390 console_log_handler, NULL /* user_data */);
4391 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4393 console_log_handler, NULL /* user_data */);
4394 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4396 console_log_handler, NULL /* user_data */);
4398 /* Initialize the pcaps list */
4399 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
4401 #if !GLIB_CHECK_VERSION(2,31,0)
4402 /* Initialize the thread system */
4403 g_thread_init(NULL);
4407 /* Load wpcap if possible. Do this before collecting the run-time version information */
4410 /* ... and also load the packet.dll from wpcap */
4411 /* XXX - currently not required, may change later. */
4412 /*wpcap_packet_load();*/
4414 /* Start windows sockets */
4415 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4417 /* Set handler for Ctrl+C key */
4418 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4420 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4421 and exit. Do the same with SIGPIPE, in case, for example,
4422 we're writing to our standard output and it's a pipe.
4423 Do the same with SIGHUP if it's not being ignored (if we're
4424 being run under nohup, it might be ignored, in which case we
4425 should leave it ignored).
4427 XXX - apparently, Coverity complained that part of action
4428 wasn't initialized. Perhaps it's running on Linux, where
4429 struct sigaction has an ignored "sa_restorer" element and
4430 where "sa_handler" and "sa_sigaction" might not be two
4431 members of a union. */
4432 memset(&action, 0, sizeof(action));
4433 action.sa_handler = capture_cleanup_handler;
4435 * Arrange that system calls not get restarted, because when
4436 * our signal handler returns we don't want to restart
4437 * a call that was waiting for packets to arrive.
4439 action.sa_flags = 0;
4440 sigemptyset(&action.sa_mask);
4441 sigaction(SIGTERM, &action, NULL);
4442 sigaction(SIGINT, &action, NULL);
4443 sigaction(SIGPIPE, &action, NULL);
4444 sigaction(SIGHUP, NULL, &oldaction);
4445 if (oldaction.sa_handler == SIG_DFL)
4446 sigaction(SIGHUP, &action, NULL);
4449 /* Catch SIGINFO and, if we get it and we're capturing in
4450 quiet mode, report the number of packets we've captured. */
4451 action.sa_handler = report_counts_siginfo;
4452 action.sa_flags = SA_RESTART;
4453 sigemptyset(&action.sa_mask);
4454 sigaction(SIGINFO, &action, NULL);
4455 #endif /* SIGINFO */
4459 enable_kernel_bpf_jit_compiler();
4462 /* ----------------------------------------------------------------- */
4463 /* Privilege and capability handling */
4465 /* 1. Running not as root or suid root; no special capabilities. */
4468 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4471 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4473 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4474 /* capabilities; Drop all other capabilities; */
4475 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4476 /* else: after pcap_open_live() in capture_loop_open_input() */
4477 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4478 /* (Note: this means that the process, although logged in */
4479 /* as root, does not have various permissions such as the */
4480 /* ability to bypass file access permissions). */
4481 /* XXX: Should we just leave capabilities alone in this case */
4482 /* so that user gets expected effect that root can do */
4485 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4487 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4488 /* else: after pcap_open_live() in capture_loop_open_input() */
4489 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4490 /* pcap_open_live). */
4492 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4494 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4495 /* capabilities; Drop all other capabilities; */
4496 /* Drop suid privileges (euid=ruid); */
4497 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4498 /* else: after pcap_open_live() in capture_loop_open_input() */
4499 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4501 /* XXX: For some Linux versions/distros with capabilities */
4502 /* a 'normal' process with any capabilities cannot be */
4503 /* 'killed' (signaled) from another (same uid) non-privileged */
4505 /* For example: If (non-suid) Wireshark forks a */
4506 /* child suid dumpcap which acts as described here (case 5), */
4507 /* Wireshark will be unable to kill (signal) the child */
4508 /* dumpcap process until the capabilities have been dropped */
4509 /* (after pcap_open_live()). */
4510 /* This behaviour will apparently be changed in the kernel */
4511 /* to allow the kill (signal) in this case. */
4512 /* See the following for details: */
4513 /* http://www.mail-archive.com/ [wrapped] */
4514 /* linux-security-module@vger.kernel.org/msg02913.html */
4516 /* It is therefore conceivable that if dumpcap somehow hangs */
4517 /* in pcap_open_live or before that wireshark will not */
4518 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4519 /* In this case, exiting wireshark will kill the child */
4520 /* dumpcap process. */
4522 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4523 /* capabilities; Using libcap. Note: capset cmd (which see) */
4524 /* used to assign capabilities to file. */
4526 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4527 /* else: after pcap_open_live() in capture_loop_open_input() */
4528 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4530 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4531 /* longer required (similar to capture). */
4533 /* ----------------------------------------------------------------- */
4535 init_process_policies();
4538 /* If 'started with special privileges' (and using libcap) */
4539 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4540 /* Set euid/egid = ruid/rgid to remove suid privileges */
4541 relinquish_privs_except_capture();
4544 /* Set the initial values in the capture options. This might be overwritten
4545 by the command line parameters. */
4546 capture_opts_init(&global_capture_opts);
4547 /* We always save to a file - if no file was specified, we save to a
4549 global_capture_opts.saving_to_file = TRUE;
4550 global_capture_opts.has_ring_num_files = TRUE;
4552 /* Pass on capture_child mode for capture_opts */
4553 global_capture_opts.capture_child = capture_child;
4555 /* Now get our args */
4556 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4558 case 'h': /* Print help and exit */
4559 printf("Dumpcap (Wireshark) %s\n"
4560 "Capture network packets and dump them into a pcapng or pcap file.\n"
4561 "See http://www.wireshark.org for more information.\n",
4562 get_ws_vcs_version_info());
4563 print_usage(stdout);
4566 case 'v': /* Show version and exit */
4568 show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4569 g_string_free(comp_info_str, TRUE);
4570 g_string_free(runtime_info_str, TRUE);
4574 /*** capture option specific ***/
4575 case 'a': /* autostop criteria */
4576 case 'b': /* Ringbuffer option */
4577 case 'c': /* Capture x packets */
4578 case 'f': /* capture filter */
4579 case 'g': /* enable group read access on file(s) */
4580 case 'i': /* Use interface x */
4581 case 'n': /* Use pcapng format */
4582 case 'p': /* Don't capture in promiscuous mode */
4583 case 'P': /* Use pcap format */
4584 case 's': /* Set the snapshot (capture) length */
4585 case 'w': /* Write to capture file x */
4586 case 'y': /* Set the pcap data link type */
4587 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4588 #ifdef HAVE_PCAP_REMOTE
4589 case 'u': /* Use UDP for data transfer */
4590 case 'r': /* Capture own RPCAP traffic too */
4591 case 'A': /* Authentication */
4593 #ifdef HAVE_PCAP_SETSAMPLING
4594 case 'm': /* Sampling */
4596 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4597 case 'B': /* Buffer size */
4598 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4599 #ifdef HAVE_PCAP_CREATE
4600 case 'I': /* Monitor mode */
4602 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4607 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4609 capture_child = TRUE;
4611 /* set output pipe to binary mode, to avoid ugly text conversions */
4612 _setmode(2, O_BINARY);
4614 * optarg = the control ID, aka the PPID, currently used for the
4617 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4618 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4619 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4620 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4622 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4623 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4624 "Signal pipe: Unable to open %s. Dead parent?",
4632 case 'q': /* Quiet */
4638 /*** all non capture option specific ***/
4639 case 'D': /* Print a list of capture devices and exit */
4640 list_interfaces = TRUE;
4643 case 'L': /* Print list of link-layer types and exit */
4644 list_link_layer_types = TRUE;
4647 #ifdef HAVE_BPF_IMAGE
4648 case 'd': /* Print BPF code for capture filter and exit */
4649 print_bpf_code = TRUE;
4653 case 'S': /* Print interface statistics once a second */
4654 print_statistics = TRUE;
4657 case 'k': /* Set wireless channel */
4659 set_chan_arg = optarg;
4662 case 'M': /* For -D, -L, and -S, print machine-readable output */
4663 machine_readable = TRUE;
4666 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4669 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4672 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4674 case '?': /* Bad flag - print usage message */
4683 /* user specified file name as regular command-line argument */
4684 /* XXX - use it as the capture file name (or something else)? */
4690 * Extra command line arguments were specified; complain.
4691 * XXX - interpret as capture filter, as tcpdump and tshark do?
4693 cmdarg_err("Invalid argument: %s", argv[0]);
4698 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4701 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4702 /* Use some default if the user hasn't specified some */
4703 /* XXX: Are these defaults good enough? */
4704 pcap_queue_byte_limit = 1000 * 1000;
4705 pcap_queue_packet_limit = 1000;
4708 print_usage(stderr);
4712 if (run_once_args > 1) {
4713 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4715 } else if (run_once_args == 1) {
4716 /* We're supposed to print some information, rather than
4717 to capture traffic; did they specify a ring buffer option? */
4718 if (global_capture_opts.multi_files_on) {
4719 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4723 /* We're supposed to capture traffic; */
4725 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4726 if (global_capture_opts.ifaces->len > 1) {
4728 global_capture_opts.use_pcapng = TRUE;
4731 if (global_capture_opts.capture_comment &&
4732 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4733 /* XXX - for ringbuffer, should we apply the comment to each file? */
4734 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4738 /* Was the ring buffer option specified and, if so, does it make sense? */
4739 if (global_capture_opts.multi_files_on) {
4740 /* Ring buffer works only under certain conditions:
4741 a) ring buffer does not work with temporary files;
4742 b) it makes no sense to enable the ring buffer if the maximum
4743 file size is set to "infinite". */
4744 if (global_capture_opts.save_file == NULL) {
4745 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4746 global_capture_opts.multi_files_on = FALSE;
4748 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4749 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4751 /* XXX - this must be redesigned as the conditions changed */
4752 global_capture_opts.multi_files_on = FALSE;
4759 * "-D" requires no interface to be selected; it's supposed to list
4762 if (list_interfaces) {
4763 /* Get the list of interfaces */
4768 if_list = capture_interface_list(&err, &err_str,NULL);
4769 if (if_list == NULL) {
4772 * If we're being run by another program, just give them
4773 * an empty list of interfaces, don't report this as
4774 * an error; that lets them decide whether to report
4775 * this as an error or not.
4777 if (!machine_readable) {
4778 cmdarg_err("There are no interfaces on which a capture can be done");
4782 cmdarg_err("%s", err_str);
4788 if (machine_readable) /* tab-separated values to stdout */
4789 print_machine_readable_interfaces(if_list);
4791 capture_opts_print_interfaces(if_list);
4792 free_interface_list(if_list);
4797 * "-S" requires no interface to be selected; it gives statistics
4798 * for all interfaces.
4800 if (print_statistics) {
4801 status = print_statistics_loop(machine_readable);
4806 interface_options interface_opts;
4808 if (global_capture_opts.ifaces->len != 1) {
4809 cmdarg_err("Need one interface");
4813 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4814 status = set_80211_channel(interface_opts.name, set_chan_arg);
4819 * "-L", "-d", and capturing act on a particular interface, so we have to
4820 * have an interface; if none was specified, pick a default.
4822 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4824 /* cmdarg_err() already called .... */
4828 /* Let the user know what interfaces were chosen. */
4829 if (capture_child) {
4830 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4831 interface_options interface_opts;
4833 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4834 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4835 interface_opts.name);
4838 str = g_string_new("");
4840 if (global_capture_opts.ifaces->len < 2)
4842 if (global_capture_opts.ifaces->len < 4)
4845 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4846 interface_options interface_opts;
4848 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4850 if (global_capture_opts.ifaces->len > 2) {
4851 g_string_append_printf(str, ",");
4853 g_string_append_printf(str, " ");
4854 if (j == global_capture_opts.ifaces->len - 1) {
4855 g_string_append_printf(str, "and ");
4858 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4861 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4863 fprintf(stderr, "Capturing on %s\n", str->str);
4864 g_string_free(str, TRUE);
4867 if (list_link_layer_types) {
4868 /* Get the list of link-layer types for the capture device. */
4869 if_capabilities_t *caps;
4873 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4874 interface_options interface_opts;
4876 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4878 caps = get_if_capabilities(interface_opts.name,
4879 interface_opts.monitor_mode, &err_str);
4881 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4882 "Please check to make sure you have sufficient permissions, and that\n"
4883 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4887 if (caps->data_link_types == NULL) {
4888 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4891 if (machine_readable) /* tab-separated values to stdout */
4892 /* XXX: We need to change the format and adopt consumers */
4893 print_machine_readable_if_capabilities(caps);
4895 /* XXX: We might want to print also the interface name */
4896 capture_opts_print_if_capabilities(caps, interface_opts.name,
4897 interface_opts.monitor_mode);
4898 free_if_capabilities(caps);
4903 /* We're supposed to do a capture, or print the BPF code for a filter.
4904 Process the snapshot length, as that affects the generated BPF code. */
4905 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4907 #ifdef HAVE_BPF_IMAGE
4908 if (print_bpf_code) {
4909 show_filter_code(&global_capture_opts);
4914 /* We're supposed to do a capture. Process the ring buffer arguments. */
4915 capture_opts_trim_ring_num_files(&global_capture_opts);
4917 /* flush stderr prior to starting the main capture loop */
4920 /* Now start the capture. */
4921 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4925 /* capture failed */
4928 return 0; /* never here, make compiler happy */
4933 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4934 const char *message, gpointer user_data _U_)
4941 /* ignore log message, if log_level isn't interesting */
4942 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4943 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4948 /* create a "timestamp" */
4950 today = localtime(&curr);
4952 switch(log_level & G_LOG_LEVEL_MASK) {
4953 case G_LOG_LEVEL_ERROR:
4956 case G_LOG_LEVEL_CRITICAL:
4959 case G_LOG_LEVEL_WARNING:
4962 case G_LOG_LEVEL_MESSAGE:
4965 case G_LOG_LEVEL_INFO:
4968 case G_LOG_LEVEL_DEBUG:
4972 fprintf(stderr, "unknown log_level %u\n", log_level);
4974 g_assert_not_reached();
4977 /* Generate the output message */
4978 if (log_level & G_LOG_LEVEL_MESSAGE) {
4979 /* normal user messages without additional infos */
4980 msg = g_strdup_printf("%s\n", message);
4982 /* info/debug messages with additional infos */
4983 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4984 today->tm_hour, today->tm_min, today->tm_sec,
4985 log_domain != NULL ? log_domain : "",
4989 /* DEBUG & INFO msgs (if we're debugging today) */
4990 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4991 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4992 #ifdef DEBUG_DUMPCAP
4993 fprintf(stderr, "%s", msg);
4996 #ifdef DEBUG_CHILD_DUMPCAP
4997 fprintf(debug_log, "%s", msg);
5005 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
5006 /* to parent especially formatted if dumpcap running as child. */
5007 if (capture_child) {
5008 sync_pipe_errmsg_to_parent(2, msg, "");
5010 fprintf(stderr, "%s", msg);
5017 /****************************************************************************************************************/
5018 /* indication report routines */
5022 report_packet_count(unsigned int packet_count)
5024 char tmp[SP_DECISIZE+1+1];
5025 static unsigned int count = 0;
5027 if (capture_child) {
5028 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
5029 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
5030 pipe_write_block(2, SP_PACKET_COUNT, tmp);
5032 count += packet_count;
5033 fprintf(stderr, "\rPackets: %u ", count);
5034 /* stderr could be line buffered */
5040 report_new_capture_file(const char *filename)
5042 if (capture_child) {
5043 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
5044 pipe_write_block(2, SP_FILE, filename);
5048 * Prevent a SIGINFO handler from writing to the standard error
5049 * while we're doing so; instead, have it just set a flag telling
5050 * us to print that information when we're done.
5053 #endif /* SIGINFO */
5054 fprintf(stderr, "File: %s\n", filename);
5055 /* stderr could be line buffered */
5060 * Allow SIGINFO handlers to write.
5065 * If a SIGINFO handler asked us to write out capture counts, do so.
5068 report_counts_for_siginfo();
5069 #endif /* SIGINFO */
5074 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5076 interface_options interface_opts;
5077 char tmp[MSG_MAX_LENGTH+1+6];
5079 if (i < capture_opts->ifaces->len) {
5080 if (capture_child) {
5081 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5082 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5083 pipe_write_block(2, SP_BAD_FILTER, tmp);
5086 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5087 * the error message below.
5089 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
5091 "Invalid capture filter \"%s\" for interface '%s'.\n"
5093 "That string isn't a valid capture filter (%s).\n"
5094 "See the User's Guide for a description of the capture filter syntax.",
5095 interface_opts.cfilter, interface_opts.name, errmsg);
5101 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5103 if (capture_child) {
5104 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5105 "Primary Error: %s", error_msg);
5106 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5107 "Secondary Error: %s", secondary_error_msg);
5108 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5110 cmdarg_err("%s", error_msg);
5111 if (secondary_error_msg[0] != '\0')
5112 cmdarg_err_cont("%s", secondary_error_msg);
5117 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
5119 char tmp[SP_DECISIZE+1+1];
5120 guint32 total_drops = pcap_drops + drops + flushed;
5122 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5124 if (capture_child) {
5125 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5126 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5127 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
5128 /* XXX: Need to provide interface id, changes to consumers required. */
5129 pipe_write_block(2, SP_DROPS, tmp);
5132 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5133 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
5134 received ? 100.0 * received / (received + total_drops) : 0.0);
5135 /* stderr could be line buffered */
5141 /************************************************************************************************/
5142 /* signal_pipe handling */
5147 signal_pipe_check_running(void)
5149 /* any news from our parent? -> just stop the capture */
5153 /* if we are running standalone, no check required */
5154 if (!capture_child) {
5158 if (!sig_pipe_name || !sig_pipe_handle) {
5159 /* This shouldn't happen */
5160 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5161 "Signal pipe: No name or handle");
5166 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5167 * at this point. Should we check to see if the parent is still alive,
5168 * e.g. by using OpenProcess?
5171 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5173 if (!result || avail > 0) {
5174 /* peek failed or some bytes really available */
5175 /* (if not piping from stdin this would fail) */
5176 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5177 "Signal pipe: Stop capture: %s", sig_pipe_name);
5178 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5179 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
5180 sig_pipe_handle, result, avail);
5183 /* pipe ok and no bytes available */
5194 * Editor modelines - http://www.wireshark.org/tools/modelines.html
5199 * indent-tabs-mode: nil
5202 * vi: set shiftwidth=4 tabstop=8 expandtab:
5203 * :indentSize=4:tabSize=8:noTabs=true: