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>
46 #ifdef HAVE_ARPA_INET_H
47 #include <arpa/inet.h>
50 #if defined(__APPLE__) && defined(__LP64__)
51 #include <sys/utsname.h>
55 * Linux bonding devices mishandle unknown ioctls; they fail
56 * with ENODEV rather than ENOTSUP, EOPNOTSUPP, or ENOTTY,
57 * so pcap_can_set_rfmon() returns a "no such device" indication
58 * if we try to do SIOCGIWMODE on them.
60 * So, on Linux, we check for bonding devices, if we can, before
61 * trying pcap_can_set_rfmon(), as pcap_can_set_rfmon() will
62 * end up trying SIOCGIWMODE on the device if that ioctl exists.
64 #if defined(HAVE_PCAP_CREATE) && defined(__linux__)
66 #include <sys/ioctl.h>
69 * If we're building for a Linux version that supports bonding,
70 * HAVE_BONDING will be defined.
73 #ifdef HAVE_LINUX_SOCKIOS_H
74 #include <linux/sockios.h>
77 #ifdef HAVE_LINUX_IF_BONDING_H
78 #include <linux/if_bonding.h>
81 #if defined(BOND_INFO_QUERY_OLD) || defined(SIOCBONDINFOQUERY)
85 #endif /* defined(HAVE_PCAP_CREATE) && defined(__linux__) */
91 #include <zlib.h> /* to get the libz version number */
94 #include <wsutil/cmdarg_err.h>
95 #include <wsutil/crash_info.h>
96 #include <wsutil/ws_diag_control.h>
97 #include <wsutil/ws_version_info.h>
99 #ifndef HAVE_GETOPT_LONG
100 #include "wsutil/wsgetopt.h"
108 # include <sys/prctl.h>
109 # include <sys/capability.h>
112 #include "ringbuffer.h"
114 #include "caputils/capture_ifinfo.h"
115 #include "caputils/capture-pcap-util.h"
116 #include "caputils/capture-pcap-util-int.h"
118 #include "caputils/capture-wpcap.h"
124 #include <wsutil/unicode-utils.h>
131 #ifdef NEED_INET_V6DEFS_H
132 # include "wsutil/inet_v6defs.h"
135 #include <wsutil/clopts_common.h>
136 #include <wsutil/privileges.h>
138 #include "sync_pipe.h"
140 #include "capture_opts.h"
141 #include <capchild/capture_session.h>
142 #include <capchild/capture_sync.h>
144 #include "conditions.h"
145 #include "capture_stop_conditions.h"
147 #include "wsutil/tempfile.h"
149 #include "wsutil/file_util.h"
150 #include "wsutil/os_version_info.h"
151 #include "wsutil/str_util.h"
153 #include "caputils/ws80211_utils.h"
160 * Get information about libpcap format from "wiretap/libpcap.h".
161 * XXX - can we just use pcap_open_offline() to read the pipe?
163 #include "wiretap/libpcap.h"
165 /**#define DEBUG_DUMPCAP**/
166 /**#define DEBUG_CHILD_DUMPCAP**/
170 #include <conio.h> /* _getch() */
174 #ifdef DEBUG_CHILD_DUMPCAP
175 FILE *debug_log; /* for logging debug messages to */
176 /* a file if DEBUG_CHILD_DUMPCAP */
180 static GAsyncQueue *pcap_queue;
181 static gint64 pcap_queue_bytes;
182 static gint64 pcap_queue_packets;
183 static gint64 pcap_queue_byte_limit = 0;
184 static gint64 pcap_queue_packet_limit = 0;
186 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
188 static gchar *sig_pipe_name = NULL;
189 static HANDLE sig_pipe_handle = NULL;
190 static gboolean signal_pipe_check_running(void);
194 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
195 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
198 /** Stop a low-level capture (stops the capture child). */
199 static void capture_loop_stop(void);
200 /** Close a pipe, or socket if \a from_socket is TRUE */
201 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
205 * Enable kernel BPF JIT compiler if available.
206 * If any calls fail, just drive on - the JIT compiler might not be
207 * enabled, but filtering will still work, and it's not clear what
208 * we could do if the calls fail; should we just report the error
209 * and not continue to capture, should we report it as a warning, or
213 enable_kernel_bpf_jit_compiler(void)
217 static const char file[] = "/proc/sys/net/core/bpf_jit_enable";
219 fd = ws_open(file, O_WRONLY);
223 written = ws_write(fd, "1", strlen("1"));
229 #if !defined (__linux__)
230 #ifndef HAVE_PCAP_BREAKLOOP
232 * We don't have pcap_breakloop(), which is the only way to ensure that
233 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
234 * won't, if the call to read the next packet or batch of packets is
235 * is interrupted by a signal on UN*X, just go back and try again to
238 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
239 * the signal handler, set a flag to stop capturing; however, without
240 * a guarantee of that sort, we can't guarantee that we'll stop capturing
241 * if the read will be retried and won't time out if no packets arrive.
243 * Therefore, on at least some platforms, we work around the lack of
244 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
245 * to wait for packets to arrive, so that we're probably going to be
246 * blocked in the select() when the signal arrives, and can just bail
247 * out of the loop at that point.
249 * However, we don't want to do that on BSD (because "select()" doesn't work
250 * correctly on BPF devices on at least some releases of some flavors of
251 * BSD), and we don't want to do it on Windows (because "select()" is
252 * something for sockets, not for arbitrary handles). (Note that "Windows"
253 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
254 * using WinPcap, not a UNIX libpcap.)
256 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
257 * on BSD times out even if no packets have arrived, so we'll eventually
258 * exit pcap_dispatch() with an indication that no packets have arrived,
259 * and will break out of the capture loop at that point.
261 * On Windows, we can't send a SIGINT to stop capturing, so none of this
262 * applies in any case.
264 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
265 * want to include it if it's not present on this platform, however.
267 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
268 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
270 # define MUST_DO_SELECT
271 # endif /* avoid select */
272 #endif /* HAVE_PCAP_BREAKLOOP */
274 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
275 * in pcap_dispatch(); on the other hand, select() works just fine there.
276 * Hence we use a select for that come what may.
278 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
279 * internally, and, with TPACKET_V3, once that's supported, it'll
280 * support timeouts, at least as I understand the way the code works.
282 #define MUST_DO_SELECT
285 /** init the capture filter */
288 INITFILTER_BAD_FILTER,
289 INITFILTER_OTHER_ERROR
290 } initfilter_status_t;
293 STATE_EXPECT_REC_HDR,
306 typedef struct _pcap_options {
311 #ifdef MUST_DO_SELECT
312 int pcap_fd; /**< pcap file descriptor */
319 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
320 /**< capture pipe (unix only "input file") */
321 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
322 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
323 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
324 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
326 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
328 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
329 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
330 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
332 char * cap_pipe_buf; /**< Pointer to the data buffer we read into */
333 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
334 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
336 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
337 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
339 cap_pipe_state_t cap_pipe_state;
340 cap_pipe_err_t cap_pipe_err;
343 GMutex *cap_pipe_read_mtx;
344 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
348 typedef struct _loop_data {
350 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
351 int err; /**< if non-zero, error seen while capturing */
352 gint packet_count; /**< Number of packets we have already captured */
353 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
354 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
356 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
362 guint64 bytes_written;
363 guint32 autostop_files;
366 typedef struct _pcap_queue_element {
367 pcap_options *pcap_opts;
368 struct pcap_pkthdr phdr;
370 } pcap_queue_element;
373 * Standard secondary message for unexpected errors.
375 static const char please_report[] =
376 "Please report this to the Wireshark developers.\n"
377 "https://bugs.wireshark.org/\n"
378 "(This is not a crash; please do not report it as such.)";
381 * This needs to be static, so that the SIGINT handler can clear the "go"
384 static loop_data global_ld;
388 * Timeout, in milliseconds, for reads from the stream of captured packets
389 * from a capture device.
391 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
392 * 64-bit applications, with sub-second timeouts not to work. The bug is
393 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
395 #if defined(__APPLE__) && defined(__LP64__)
396 static gboolean need_timeout_workaround;
398 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
400 #define CAP_READ_TIMEOUT 250
404 * Timeout, in microseconds, for reads from the stream of captured packets
405 * from a pipe. Pipes don't have the same problem that BPF devices do
406 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
407 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
408 * of the offending versions of Snow Leopard.
410 * On Windows this value is converted to milliseconds and passed to
411 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
412 * will return immediately.
415 #define PIPE_READ_TIMEOUT 100000
417 #define PIPE_READ_TIMEOUT 250000
420 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
423 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
424 const char *message, gpointer user_data _U_);
426 /* capture related options */
427 static capture_options global_capture_opts;
428 static gboolean quiet = FALSE;
429 static gboolean use_threads = FALSE;
430 static guint64 start_time;
432 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
434 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
436 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
437 int err, gboolean is_close);
439 static void WS_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
441 static void report_new_capture_file(const char *filename);
442 static void report_packet_count(unsigned int packet_count);
443 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
444 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
445 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
447 #define MSG_MAX_LENGTH 4096
449 /* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
451 create_timestamp(void) {
461 * Current time, represented as 100-nanosecond intervals since
462 * January 1, 1601, 00:00:00 UTC.
464 * I think DWORD might be signed, so cast both parts of "now"
465 * to guint32 so that the sign bit doesn't get treated specially.
467 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
468 * might want to use instead.
470 GetSystemTimeAsFileTime(&now);
471 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
472 (guint32)now.dwLowDateTime;
475 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
481 * Subtract difference, in microseconds, between January 1, 1601
482 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
484 timestamp -= G_GUINT64_CONSTANT(11644473600000000);
487 * Current time, represented as seconds and microseconds since
488 * January 1, 1970, 00:00:00 UTC.
490 gettimeofday(&now, NULL);
493 * Convert to delta in microseconds.
495 timestamp = (guint64)(now.tv_sec) * 1000000 +
496 (guint64)(now.tv_usec);
502 print_usage(FILE *output)
504 fprintf(output, "\nUsage: dumpcap [options] ...\n");
505 fprintf(output, "\n");
506 fprintf(output, "Capture interface:\n");
507 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
508 " or for remote capturing, use one of these formats:\n"
509 " rpcap://<host>/<interface>\n"
510 " TCP@<host>:<port>\n");
511 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
512 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
513 fprintf(output, " -p don't capture in promiscuous mode\n");
514 #ifdef HAVE_PCAP_CREATE
515 fprintf(output, " -I capture in monitor mode, if available\n");
517 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
518 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
520 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
521 fprintf(output, " -D print list of interfaces and exit\n");
522 fprintf(output, " -L print list of link-layer types of iface and exit\n");
523 #ifdef HAVE_BPF_IMAGE
524 fprintf(output, " -d print generated BPF code for capture filter\n");
526 fprintf(output, " -k set channel on wifi interface <freq>,[<type>]\n");
527 fprintf(output, " -S print statistics for each interface once per second\n");
528 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
529 fprintf(output, "\n");
530 #ifdef HAVE_PCAP_REMOTE
531 fprintf(output, "RPCAP options:\n");
532 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
533 fprintf(output, " -u use UDP for RPCAP data transfer\n");
534 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
535 #ifdef HAVE_PCAP_SETSAMPLING
536 fprintf(output, " -m <sampling type> use packet sampling\n");
537 fprintf(output, " count:NUM - capture one packet of every NUM\n");
538 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
541 fprintf(output, "Stop conditions:\n");
542 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
543 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
544 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
545 fprintf(output, " files:NUM - stop after NUM files\n");
546 /*fprintf(output, "\n");*/
547 fprintf(output, "Output (files):\n");
548 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
549 fprintf(output, " -g enable group read access on the output file(s)\n");
550 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
551 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
552 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
553 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
554 fprintf(output, " -P use libpcap format instead of pcapng\n");
555 fprintf(output, " --capture-comment <comment>\n");
556 fprintf(output, " add a capture comment to the output file\n");
557 fprintf(output, " (only for pcapng)\n");
558 fprintf(output, "\n");
559 fprintf(output, "Miscellaneous:\n");
560 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
561 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
562 fprintf(output, " within dumpcap\n");
563 fprintf(output, " -t use a separate thread per interface\n");
564 fprintf(output, " -q don't report packet capture counts\n");
565 fprintf(output, " -v print version information and exit\n");
566 fprintf(output, " -h display this help and exit\n");
567 fprintf(output, "\n");
569 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
570 fprintf(output, "You might want to reset it\n");
571 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
572 fprintf(output, "\n");
574 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
575 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
576 fprintf(output, "\n");
577 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
581 * Report an error in command-line arguments.
582 * If we're a capture child, send a message back to the parent, otherwise
586 dumpcap_cmdarg_err(const char *fmt, va_list ap)
590 /* Generate a 'special format' message back to parent */
591 msg = g_strdup_vprintf(fmt, ap);
592 sync_pipe_errmsg_to_parent(2, msg, "");
595 fprintf(stderr, "dumpcap: ");
596 vfprintf(stderr, fmt, ap);
597 fprintf(stderr, "\n");
602 * Report additional information for an error in command-line arguments.
603 * If we're a capture child, send a message back to the parent, otherwise
607 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
611 msg = g_strdup_vprintf(fmt, ap);
612 sync_pipe_errmsg_to_parent(2, msg, "");
615 vfprintf(stderr, fmt, ap);
616 fprintf(stderr, "\n");
622 #if 0 /* Set to enable capability debugging */
623 /* see 'man cap_to_text()' for explanation of output */
624 /* '=' means 'all= ' ie: no capabilities */
625 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
627 print_caps(const char *pfx) {
628 cap_t caps = cap_get_proc();
629 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
630 "%s: EUID: %d Capabilities: %s", pfx,
631 geteuid(), cap_to_text(caps, NULL));
634 print_caps(const char *pfx _U_) {
639 relinquish_all_capabilities(void)
641 /* Drop any and all capabilities this process may have. */
642 /* Allowed whether or not process has any privileges. */
643 cap_t caps = cap_init(); /* all capabilities initialized to off */
644 print_caps("Pre-clear");
645 if (cap_set_proc(caps)) {
646 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
648 print_caps("Post-clear");
654 open_capture_device(capture_options *capture_opts
655 #ifndef HAVE_PCAP_SET_TSTAMP_PRECISION
659 interface_options *interface_opts,
660 char (*open_err_str)[PCAP_ERRBUF_SIZE])
663 #ifdef HAVE_PCAP_CREATE
666 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
667 struct pcap_rmtauth auth;
670 /* Open the network interface to capture from it.
671 Some versions of libpcap may put warnings into the error buffer
672 if they succeed; to tell if that's happened, we have to clear
673 the error buffer, and check if it's still a null string. */
674 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Entering open_capture_device().");
675 (*open_err_str)[0] = '\0';
676 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
678 * If we're opening a remote device, use pcap_open(); that's currently
679 * the only open routine that supports remote devices.
681 if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
682 auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
683 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
684 auth.username = interface_opts->auth_username;
685 auth.password = interface_opts->auth_password;
687 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
688 "Calling pcap_open() using name %s, snaplen %d, promisc_mode %d, datatx_udp %d, nocap_rpcap %d.",
689 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode,
690 interface_opts->datatx_udp, interface_opts->nocap_rpcap);
691 pcap_h = pcap_open(interface_opts->name, interface_opts->snaplen,
693 (interface_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
694 (interface_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
695 (interface_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
696 CAP_READ_TIMEOUT, &auth, *open_err_str);
697 if (pcap_h == NULL) {
698 /* Error - did pcap actually supply an error message? */
699 if ((*open_err_str)[0] == '\0') {
700 /* Work around known WinPcap bug wherein no error message is
701 filled in on a failure to open an rpcap: URL. */
702 g_strlcpy(*open_err_str,
703 "Unknown error (pcap bug; actual error cause not reported)",
704 sizeof *open_err_str);
707 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
708 "pcap_open() returned %p.", (void *)pcap_h);
713 * If we're not opening a remote device, use pcap_create() and
714 * pcap_activate() if we have them, so that we can set the buffer
715 * size, otherwise use pcap_open_live().
717 #ifdef HAVE_PCAP_CREATE
718 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
719 "Calling pcap_create() using %s.", interface_opts->name);
720 pcap_h = pcap_create(interface_opts->name, *open_err_str);
721 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
722 "pcap_create() returned %p.", (void *)pcap_h);
723 if (pcap_h != NULL) {
724 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
725 "Calling pcap_set_snaplen() with snaplen %d.", interface_opts->snaplen);
726 pcap_set_snaplen(pcap_h, interface_opts->snaplen);
727 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
728 "Calling pcap_set_promisc() with promisc_mode %d.", interface_opts->promisc_mode);
729 pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
730 pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
732 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
734 * If we're writing pcap-ng files, try to enable
735 * nanosecond-resolution capture; any code that
736 * can read pcap-ng files must be able to handle
737 * nanosecond-resolution time stamps.
739 * If we're writing pcap files, don't try to enable
740 * nanosecond-resolution capture, as not all code
741 * that reads pcap files recognizes the nanosecond-
742 * resolution pcap file magic number.
744 if (capture_opts->use_pcapng)
745 request_high_resolution_timestamp(pcap_h);
746 #endif /* HAVE_PCAP_SET_TSTAMP_PRECISION */
748 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
749 "buffersize %d.", interface_opts->buffer_size);
750 if (interface_opts->buffer_size != 0) {
751 pcap_set_buffer_size(pcap_h, interface_opts->buffer_size * 1024 * 1024);
753 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
754 "monitor_mode %d.", interface_opts->monitor_mode);
755 if (interface_opts->monitor_mode)
756 pcap_set_rfmon(pcap_h, 1);
757 err = pcap_activate(pcap_h);
758 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
759 "pcap_activate() returned %d.", err);
761 /* Failed to activate, set to NULL */
762 if (err == PCAP_ERROR)
763 g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
765 g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
771 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
772 "pcap_open_live() calling using name %s, snaplen %d, promisc_mode %d.",
773 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode);
774 pcap_h = pcap_open_live(interface_opts->name, interface_opts->snaplen,
775 interface_opts->promisc_mode, CAP_READ_TIMEOUT,
777 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
778 "pcap_open_live() returned %p.", (void *)pcap_h);
780 /* Windows doesn't have pcap_create() yet */
782 /* try to set the capture buffer size -- but not for remote devices */
783 if (pcap_h && interface_opts->buffer_size > 1 &&
784 pcap_setbuff(pcap_h, interface_opts->buffer_size * 1024 * 1024) != 0) {
785 gchar *sync_secondary_msg_str;
787 sync_secondary_msg_str = g_strdup_printf(
788 "Unable to set a capture buffer size of %d MiB.\n"
789 "Capturing using the default size of %d MiB instead.",
790 interface_opts->buffer_size, DEFAULT_CAPTURE_BUFFER_SIZE);
791 report_capture_error("Couldn't set the capture buffer size.",
792 sync_secondary_msg_str);
793 g_free(sync_secondary_msg_str);
798 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_capture_device %s : %s", pcap_h ? "SUCCESS" : "FAILURE", interface_opts->name);
803 get_capture_device_open_failure_messages(const char *open_err_str,
805 char *errmsg, size_t errmsg_len,
806 char *secondary_errmsg,
807 size_t secondary_errmsg_len)
810 const char *libpcap_warn;
811 static const char ppamsg[] = "can't find PPA for ";
814 g_snprintf(errmsg, (gulong) errmsg_len,
815 "The capture session could not be initiated on interface '%s' (%s).",
816 iface, open_err_str);
819 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
821 "In order to capture packets, WinPcap must be installed; see\n"
823 " https://www.winpcap.org/\n"
825 "for a downloadable version of WinPcap and for instructions on how to install\n"
828 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
830 "Please check that \"%s\" is the proper interface.\n"
833 "Help can be found at:\n"
835 " https://wiki.wireshark.org/WinPcap\n"
836 " https://wiki.wireshark.org/CaptureSetup\n",
840 /* If we got a "can't find PPA for X" message, warn the user (who
841 is running dumpcap on HP-UX) that they don't have a version of
842 libpcap that properly handles HP-UX (libpcap 0.6.x and later
843 versions, which properly handle HP-UX, say "can't find /dev/dlpi
844 PPA for X" rather than "can't find PPA for X"). */
845 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
848 "You are running (T)Wireshark with a version of the libpcap library\n"
849 "that doesn't handle HP-UX network devices well; this means that\n"
850 "(T)Wireshark may not be able to capture packets.\n"
852 "To fix this, you should install libpcap 0.6.2, or a later version\n"
853 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
854 "packaged binary form from the Software Porting And Archive Centre\n"
855 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
856 "at the URL lists a number of mirror sites.";
860 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
861 "Please check to make sure you have sufficient permissions, and that you have "
862 "the proper interface or pipe specified.%s", libpcap_warn);
866 /* Set the data link type on a pcap. */
868 set_pcap_linktype(pcap_t *pcap_h, int linktype, char *name,
869 char *errmsg, size_t errmsg_len,
870 char *secondary_errmsg, size_t secondary_errmsg_len)
872 char *set_linktype_err_str;
875 return TRUE; /* just use the default */
876 #ifdef HAVE_PCAP_SET_DATALINK
877 if (pcap_set_datalink(pcap_h, linktype) == 0)
878 return TRUE; /* no error */
879 set_linktype_err_str = pcap_geterr(pcap_h);
881 /* Let them set it to the type it is; reject any other request. */
882 if (get_pcap_linktype(pcap_h, name) == linktype)
883 return TRUE; /* no error */
884 set_linktype_err_str =
885 "That DLT isn't one of the DLTs supported by this device";
887 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type on interface '%s' (%s).",
888 name, set_linktype_err_str);
890 * If the error isn't "XXX is not one of the DLTs supported by this device",
891 * tell the user to tell the Wireshark developers about it.
893 if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
894 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
896 secondary_errmsg[0] = '\0';
901 compile_capture_filter(const char *iface, pcap_t *pcap_h,
902 struct bpf_program *fcode, const char *cfilter)
904 bpf_u_int32 netnum, netmask;
905 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
907 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
909 * Well, we can't get the netmask for this interface; it's used
910 * only for filters that check for broadcast IP addresses, so
911 * we just punt and use 0. It might be nice to warn the user,
912 * but that's a pain in a GUI application, as it'd involve popping
913 * up a message box, and it's not clear how often this would make
914 * a difference (only filters that check for IP broadcast addresses
918 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
923 * Sigh. Older versions of libpcap don't properly declare the
924 * third argument to pcap_compile() as a const pointer. Cast
928 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
934 #ifdef HAVE_BPF_IMAGE
936 show_filter_code(capture_options *capture_opts)
938 interface_options interface_opts;
940 gchar open_err_str[PCAP_ERRBUF_SIZE];
941 char errmsg[MSG_MAX_LENGTH+1];
942 char secondary_errmsg[MSG_MAX_LENGTH+1];
943 struct bpf_program fcode;
944 struct bpf_insn *insn;
948 for (j = 0; j < capture_opts->ifaces->len; j++) {
949 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
950 pcap_h = open_capture_device(capture_opts, &interface_opts, &open_err_str);
951 if (pcap_h == NULL) {
952 /* Open failed; get messages */
953 get_capture_device_open_failure_messages(open_err_str,
955 errmsg, sizeof errmsg,
957 sizeof secondary_errmsg);
958 /* And report them */
959 report_capture_error(errmsg, secondary_errmsg);
963 /* Set the link-layer type. */
964 if (!set_pcap_linktype(pcap_h, interface_opts.linktype, interface_opts.name,
965 errmsg, sizeof errmsg,
966 secondary_errmsg, sizeof secondary_errmsg)) {
968 report_capture_error(errmsg, secondary_errmsg);
972 /* OK, try to compile the capture filter. */
973 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
974 interface_opts.cfilter)) {
976 report_cfilter_error(capture_opts, j, errmsg);
981 /* Now print the filter code. */
982 insn = fcode.bf_insns;
984 for (i = 0; i < fcode.bf_len; insn++, i++)
985 printf("%s\n", bpf_image(insn, i));
987 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
988 /* to remove any suid privileges. */
989 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
990 /* (euid/egid have already previously been set to ruid/rgid. */
991 /* (See comment in main() for details) */
993 relinquish_special_privs_perm();
995 relinquish_all_capabilities();
998 /* Let our parent know we succeeded. */
999 pipe_write_block(2, SP_SUCCESS, NULL);
1006 * capture_interface_list() is expected to do the right thing to get
1007 * a list of interfaces.
1009 * In most of the programs in the Wireshark suite, "the right thing"
1010 * is to run dumpcap and ask it for the list, because dumpcap may
1011 * be the only program in the suite with enough privileges to get
1014 * In dumpcap itself, however, we obviously can't run dumpcap to
1015 * ask for the list. Therefore, our capture_interface_list() should
1016 * just call get_interface_list().
1019 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
1021 return get_interface_list(err, err_str);
1025 * Get the data-link type for a libpcap device.
1026 * This works around AIX 5.x's non-standard and incompatible-with-the-
1027 * rest-of-the-universe libpcap.
1030 get_pcap_linktype(pcap_t *pch, const char *devicename
1038 const char *ifacename;
1041 linktype = pcap_datalink(pch);
1045 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
1046 * rather than DLT_ values for link-layer types; the ifType values
1047 * for LAN devices are:
1054 * and the ifType value for a loopback device is 24.
1056 * The AIX names for LAN devices begin with:
1063 * and the AIX names for loopback devices begin with "lo".
1065 * (The difference between "Ethernet" and "802.3" is presumably
1066 * whether packets have an Ethernet header, with a packet type,
1067 * or an 802.3 header, with a packet length, followed by an 802.2
1068 * header and possibly a SNAP header.)
1070 * If the device name matches "linktype" interpreted as an ifType
1071 * value, rather than as a DLT_ value, we will assume this is AIX's
1072 * non-standard, incompatible libpcap, rather than a standard libpcap,
1073 * and will map the link-layer type to the standard DLT_ value for
1074 * that link-layer type, as that's what the rest of Wireshark expects.
1076 * (This means the capture files won't be readable by a tcpdump
1077 * linked with AIX's non-standard libpcap, but so it goes. They
1078 * *will* be readable by standard versions of tcpdump, Wireshark,
1081 * XXX - if we conclude we're using AIX libpcap, should we also
1082 * set a flag to cause us to assume the time stamps are in
1083 * seconds-and-nanoseconds form, and to convert them to
1084 * seconds-and-microseconds form before processing them and
1089 * Find the last component of the device name, which is the
1092 ifacename = strchr(devicename, '/');
1093 if (ifacename == NULL)
1094 ifacename = devicename;
1096 /* See if it matches any of the LAN device names. */
1097 if (strncmp(ifacename, "en", 2) == 0) {
1098 if (linktype == 6) {
1100 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
1104 } else if (strncmp(ifacename, "et", 2) == 0) {
1105 if (linktype == 7) {
1107 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
1108 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
1113 } else if (strncmp(ifacename, "tr", 2) == 0) {
1114 if (linktype == 9) {
1116 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
1117 * DLT_IEEE802, which is what's used for Token Ring.
1121 } else if (strncmp(ifacename, "fi", 2) == 0) {
1122 if (linktype == 15) {
1124 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
1128 } else if (strncmp(ifacename, "lo", 2) == 0) {
1129 if (linktype == 24) {
1131 * That's the RFC 1573 value for "software loopback" devices; map it
1132 * to DLT_NULL, which is what's used for loopback devices on BSD.
1142 static data_link_info_t *
1143 create_data_link_info(int dlt)
1145 data_link_info_t *data_link_info;
1148 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
1149 data_link_info->dlt = dlt;
1150 text = pcap_datalink_val_to_name(dlt);
1152 data_link_info->name = g_strdup(text);
1154 data_link_info->name = g_strdup_printf("DLT %d", dlt);
1155 text = pcap_datalink_val_to_description(dlt);
1157 data_link_info->description = g_strdup(text);
1159 data_link_info->description = NULL;
1160 return data_link_info;
1163 #if defined(HAVE_BONDING) && defined(HAVE_PCAP_CREATE)
1165 is_linux_bonding_device(const char *ifname)
1171 fd = socket(PF_INET, SOCK_DGRAM, 0);
1175 memset(&ifr, 0, sizeof ifr);
1176 g_strlcpy(ifr.ifr_name, ifname, sizeof ifr.ifr_name);
1177 memset(&ifb, 0, sizeof ifb);
1178 ifr.ifr_data = (caddr_t)&ifb;
1179 #if defined(SIOCBONDINFOQUERY)
1180 if (ioctl(fd, SIOCBONDINFOQUERY, &ifr) == 0) {
1185 if (ioctl(fd, BOND_INFO_QUERY_OLD, &ifr) == 0) {
1194 #elif defined(HAVE_PCAP_CREATE)
1196 is_linux_bonding_device(const char *ifname _U_)
1203 * Get the capabilities of a network device.
1205 static if_capabilities_t *
1206 get_if_capabilities(interface_options *interface_opts, char **err_str)
1208 if_capabilities_t *caps;
1209 char errbuf[PCAP_ERRBUF_SIZE];
1211 #ifdef HAVE_PCAP_CREATE
1215 #ifdef HAVE_PCAP_LIST_DATALINKS
1219 data_link_info_t *data_link_info;
1222 * Allocate the interface capabilities structure.
1224 caps = (if_capabilities_t *)g_malloc(sizeof *caps);
1227 * WinPcap 4.1.2, and possibly earlier versions, have a bug
1228 * wherein, when an open with an rpcap: URL fails, the error
1229 * message for the error is not copied to errbuf and whatever
1230 * on-the-stack junk is in errbuf is treated as the error
1233 * To work around that (and any other bugs of that sort, we
1234 * initialize errbuf to an empty string. If we get an error
1235 * and the string is empty, we report it as an unknown error.
1236 * (If we *don't* get an error, and the string is *non*-empty,
1237 * that could be a warning returned, such as "can't turn
1238 * promiscuous mode on"; we currently don't do so.)
1241 #ifdef HAVE_PCAP_OPEN
1242 #ifdef HAVE_PCAP_REMOTE
1243 if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
1244 struct pcap_rmtauth auth;
1246 auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
1247 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1248 auth.username = interface_opts->auth_username;
1249 auth.password = interface_opts->auth_password;
1251 pch = pcap_open(interface_opts->name, MIN_PACKET_SIZE, 0, 0, &auth, errbuf);
1254 pch = pcap_open(interface_opts->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1255 caps->can_set_rfmon = FALSE;
1257 if (err_str != NULL)
1258 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1262 #elif defined(HAVE_PCAP_CREATE)
1263 pch = pcap_create(interface_opts->name, errbuf);
1265 if (err_str != NULL)
1266 *err_str = g_strdup(errbuf);
1270 if (is_linux_bonding_device(interface_opts->name)) {
1272 * Linux bonding device; not Wi-Fi, so no monitor mode, and
1273 * calling pcap_can_set_rfmon() might get a "no such device"
1279 * Not a Linux bonding device, so go ahead.
1281 status = pcap_can_set_rfmon(pch);
1285 if (status == PCAP_ERROR)
1286 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1289 *err_str = g_strdup(pcap_statustostr(status));
1295 caps->can_set_rfmon = FALSE;
1296 else if (status == 1) {
1297 caps->can_set_rfmon = TRUE;
1298 if (interface_opts->monitor_mode)
1299 pcap_set_rfmon(pch, 1);
1301 if (err_str != NULL) {
1302 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1310 status = pcap_activate(pch);
1312 /* Error. We ignore warnings (status > 0). */
1313 if (err_str != NULL) {
1314 if (status == PCAP_ERROR)
1315 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1318 *err_str = g_strdup(pcap_statustostr(status));
1325 pch = pcap_open_live(interface_opts->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1326 caps->can_set_rfmon = FALSE;
1328 if (err_str != NULL)
1329 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1334 deflt = get_pcap_linktype(pch, interface_opts->name);
1335 #ifdef HAVE_PCAP_LIST_DATALINKS
1336 nlt = pcap_list_datalinks(pch, &linktypes);
1337 if (nlt == 0 || linktypes == NULL) {
1339 if (err_str != NULL)
1340 *err_str = NULL; /* an empty list doesn't mean an error */
1344 caps->data_link_types = NULL;
1345 for (i = 0; i < nlt; i++) {
1346 data_link_info = create_data_link_info(linktypes[i]);
1349 * XXX - for 802.11, make the most detailed 802.11
1350 * version the default, rather than the one the
1351 * device has as the default?
1353 if (linktypes[i] == deflt)
1354 caps->data_link_types = g_list_prepend(caps->data_link_types,
1357 caps->data_link_types = g_list_append(caps->data_link_types,
1360 #ifdef HAVE_PCAP_FREE_DATALINKS
1361 pcap_free_datalinks(linktypes);
1364 * In Windows, there's no guarantee that if you have a library
1365 * built with one version of the MSVC++ run-time library, and
1366 * it returns a pointer to allocated data, you can free that
1367 * data from a program linked with another version of the
1368 * MSVC++ run-time library.
1370 * This is not an issue on UN*X.
1372 * See the mail threads starting at
1374 * https://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1378 * https://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1381 #define xx_free free /* hack so checkAPIs doesn't complain */
1384 #endif /* HAVE_PCAP_FREE_DATALINKS */
1385 #else /* HAVE_PCAP_LIST_DATALINKS */
1387 data_link_info = create_data_link_info(deflt);
1388 caps->data_link_types = g_list_append(caps->data_link_types,
1390 #endif /* HAVE_PCAP_LIST_DATALINKS */
1394 if (err_str != NULL)
1399 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1401 * Output a machine readable list of the interfaces
1402 * This list is retrieved by the sync_interface_list_open() function
1403 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
1406 print_machine_readable_interfaces(GList *if_list)
1413 char addr_str[ADDRSTRLEN];
1415 if (capture_child) {
1416 /* Let our parent know we succeeded. */
1417 pipe_write_block(2, SP_SUCCESS, NULL);
1420 i = 1; /* Interface id number */
1421 for (if_entry = g_list_first(if_list); if_entry != NULL;
1422 if_entry = g_list_next(if_entry)) {
1423 if_info = (if_info_t *)if_entry->data;
1424 printf("%d. %s\t", i++, if_info->name);
1427 * Print the contents of the if_entry struct in a parseable format.
1428 * Each if_entry element is tab-separated. Addresses are comma-
1431 /* XXX - Make sure our description doesn't contain a tab */
1432 if (if_info->vendor_description != NULL)
1433 printf("%s\t", if_info->vendor_description);
1437 /* XXX - Make sure our friendly name doesn't contain a tab */
1438 if (if_info->friendly_name != NULL)
1439 printf("%s\t", if_info->friendly_name);
1443 printf("%i\t", if_info->type);
1445 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1446 addr = g_slist_next(addr)) {
1447 if (addr != g_slist_nth(if_info->addrs, 0))
1450 if_addr = (if_addr_t *)addr->data;
1451 switch(if_addr->ifat_type) {
1453 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1455 printf("%s", addr_str);
1457 printf("<unknown IPv4>");
1461 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1462 addr_str, ADDRSTRLEN)) {
1463 printf("%s", addr_str);
1465 printf("<unknown IPv6>");
1469 printf("<type unknown %i>", if_addr->ifat_type);
1473 if (if_info->loopback)
1474 printf("\tloopback");
1476 printf("\tnetwork");
1478 printf("\t%s", if_info->extcap);
1485 * If you change the machine-readable output format of this function,
1486 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1489 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1492 data_link_info_t *data_link_info;
1493 const gchar *desc_str;
1495 if (capture_child) {
1496 /* Let our parent know we succeeded. */
1497 pipe_write_block(2, SP_SUCCESS, NULL);
1500 if (caps->can_set_rfmon)
1504 for (lt_entry = caps->data_link_types; lt_entry != NULL;
1505 lt_entry = g_list_next(lt_entry)) {
1506 data_link_info = (data_link_info_t *)lt_entry->data;
1507 if (data_link_info->description != NULL)
1508 desc_str = data_link_info->description;
1510 desc_str = "(not supported)";
1511 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1521 /* Print the number of packets captured for each interface until we're killed. */
1523 print_statistics_loop(gboolean machine_readable)
1525 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1531 char errbuf[PCAP_ERRBUF_SIZE];
1532 struct pcap_stat ps;
1534 if_list = get_interface_list(&err, &err_str);
1535 if (if_list == NULL) {
1537 cmdarg_err("There are no interfaces on which a capture can be done");
1539 cmdarg_err("%s", err_str);
1545 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1546 if_info = (if_info_t *)if_entry->data;
1549 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
1550 * connections. We avoid collecting stats on them.
1552 if (!strncmp(if_info->name, "nf", 2)) {
1553 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
1559 #ifdef HAVE_PCAP_OPEN
1560 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1562 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1566 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1567 if_stat->name = g_strdup(if_info->name);
1569 stat_list = g_list_append(stat_list, if_stat);
1574 cmdarg_err("There are no interfaces on which a capture can be done");
1578 if (capture_child) {
1579 /* Let our parent know we succeeded. */
1580 pipe_write_block(2, SP_SUCCESS, NULL);
1583 if (!machine_readable) {
1584 printf("%-15s %10s %10s\n", "Interface", "Received",
1588 global_ld.go = TRUE;
1589 while (global_ld.go) {
1590 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1591 if_stat = (if_stat_t *)stat_entry->data;
1592 pcap_stats(if_stat->pch, &ps);
1594 if (!machine_readable) {
1595 printf("%-15s %10u %10u\n", if_stat->name,
1596 ps.ps_recv, ps.ps_drop);
1598 printf("%s\t%u\t%u\n", if_stat->name,
1599 ps.ps_recv, ps.ps_drop);
1604 /* If we have a dummy signal pipe check it */
1605 if (!signal_pipe_check_running()) {
1606 global_ld.go = FALSE;
1614 /* XXX - Not reached. Should we look for 'q' in stdin? */
1615 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1616 if_stat = (if_stat_t *)stat_entry->data;
1617 pcap_close(if_stat->pch);
1618 g_free(if_stat->name);
1621 g_list_free(stat_list);
1622 free_interface_list(if_list);
1630 capture_cleanup_handler(DWORD dwCtrlType)
1632 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1633 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1634 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1635 like SIGTERM at least when the machine's shutting down.
1637 For now, if we're running as a command rather than a capture child,
1638 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1639 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1640 in that way on UN*X.
1642 If we're not running as a capture child, we might be running as
1643 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1644 user logs out. (XXX - can we explicitly check whether we're
1645 running as a service?) */
1647 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1648 "Console: Control signal");
1649 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1650 "Console: Control signal, CtrlType: %u", dwCtrlType);
1652 /* Keep capture running if we're a service and a user logs off */
1653 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1654 capture_loop_stop();
1662 capture_cleanup_handler(int signum _U_)
1664 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1665 SIGTERM. We assume that if the user wanted it to keep running
1666 after they logged out, they'd have nohupped it. */
1668 /* Note: don't call g_log() in the signal handler: if we happened to be in
1669 * g_log() in process context when the signal came in, g_log will detect
1670 * the "recursion" and abort.
1673 capture_loop_stop();
1679 report_capture_count(gboolean reportit)
1681 /* Don't print this if we're a capture child. */
1682 if (!capture_child && reportit) {
1683 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packet_count);
1684 /* stderr could be line buffered */
1692 report_counts_for_siginfo(void)
1694 report_capture_count(quiet);
1695 infoprint = FALSE; /* we just reported it */
1699 report_counts_siginfo(int signum _U_)
1701 int sav_errno = errno;
1703 /* If we've been told to delay printing, just set a flag asking
1704 that we print counts (if we're supposed to), otherwise print
1705 the count of packets captured (if we're supposed to). */
1709 report_counts_for_siginfo();
1712 #endif /* SIGINFO */
1715 exit_main(int status)
1718 /* Shutdown windows sockets */
1721 /* can be helpful for debugging */
1722 #ifdef DEBUG_DUMPCAP
1723 printf("Press any key\n");
1734 * If we were linked with libcap (not related to libpcap), make sure we have
1735 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1736 * (See comment in main() for details)
1739 relinquish_privs_except_capture(void)
1741 /* If 'started_with_special_privs' (ie: suid) then enable for
1742 * ourself the NET_ADMIN and NET_RAW capabilities and then
1743 * drop our suid privileges.
1745 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1746 * stuff we don't need (and shouldn't have).
1747 * CAP_NET_RAW: Packet capture (raw sockets).
1750 if (started_with_special_privs()) {
1751 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1752 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1754 cap_t caps = cap_init(); /* all capabilities initialized to off */
1756 print_caps("Pre drop, pre set");
1758 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1759 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1762 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1763 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1765 if (cap_set_proc(caps)) {
1766 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1768 print_caps("Pre drop, post set");
1770 relinquish_special_privs_perm();
1772 print_caps("Post drop, pre set");
1773 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1774 if (cap_set_proc(caps)) {
1775 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1777 print_caps("Post drop, post set");
1783 #endif /* HAVE_LIBCAP */
1785 /* Take care of byte order in the libpcap headers read from pipes.
1786 * (function taken from wiretap/libpcap.c) */
1788 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1791 /* Byte-swap the record header fields. */
1792 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1793 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1794 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1795 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1798 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1799 swapped, in order to match the BPF header layout.
1801 Unfortunately, some files were, according to a comment in the "libpcap"
1802 source, written with version 2.3 in their headers but without the
1803 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1804 would make no sense - we assume that we need to swap them. */
1805 if (hdr->version_major == 2 &&
1806 (hdr->version_minor < 3 ||
1807 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1810 temp = rechdr->orig_len;
1811 rechdr->orig_len = rechdr->incl_len;
1812 rechdr->incl_len = temp;
1816 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1820 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1824 return recv(pipe_fd, buf, (int)sz, 0);
1829 return ws_read(pipe_fd, buf, sz);
1835 * Thread function that reads from a pipe and pushes the data
1836 * to the main application thread.
1839 * XXX Right now we use async queues for basic signaling. The main thread
1840 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1841 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1842 * Iff the read is successful cap_pipe_read pushes an item onto
1843 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1844 * the queues themselves (yet).
1846 * We might want to move some of the cap_pipe_dispatch logic here so that
1847 * we can let cap_thread_read run independently, queuing up multiple reads
1848 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1850 static void *cap_thread_read(void *arg)
1852 pcap_options *pcap_opts;
1855 DWORD b, last_err, bytes_read;
1861 pcap_opts = (pcap_options *)arg;
1862 while (pcap_opts->cap_pipe_err == PIPOK) {
1863 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1864 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1866 while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1867 if ((pcap_opts->from_cap_socket)
1873 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1874 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1877 pcap_opts->cap_pipe_err = PIPEOF;
1881 pcap_opts->cap_pipe_err = PIPERR;
1892 /* If we try to use read() on a named pipe on Windows with partial
1893 * data it appears to return EOF.
1895 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1896 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1901 last_err = GetLastError();
1902 if (last_err == ERROR_MORE_DATA) {
1904 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1905 pcap_opts->cap_pipe_err = PIPEOF;
1909 pcap_opts->cap_pipe_err = PIPERR;
1912 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1913 pcap_opts->cap_pipe_err = PIPEOF;
1920 pcap_opts->cap_pipe_bytes_read = bytes_read;
1921 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1922 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1924 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1930 /* Provide select() functionality for a single file descriptor
1931 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1933 * Returns the same values as select.
1936 cap_pipe_select(int pipe_fd)
1939 struct timeval timeout;
1942 FD_SET(pipe_fd, &rfds);
1944 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1945 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1947 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1950 #define DEF_TCP_PORT 19000
1953 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1955 char *sockname = pipename + 4;
1956 struct sockaddr_in sa;
1963 memset(&sa, 0, sizeof(sa));
1965 p = strchr(sockname, ':');
1967 len = strlen(sockname);
1968 port = DEF_TCP_PORT;
1972 port = strtoul(p + 1, &p, 10);
1973 if (*p || port > 65535) {
1982 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1984 if (inet_pton(AF_INET, buf, &sa.sin_addr) <= 0) {
1988 sa.sin_family = AF_INET;
1989 sa.sin_port = g_htons((u_short)port);
1991 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1992 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1994 LPTSTR errorText = NULL;
1997 lastError = WSAGetLastError();
1998 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1999 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2000 FORMAT_MESSAGE_IGNORE_INSERTS,
2001 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2002 (LPTSTR)&errorText, 0, NULL);
2004 g_snprintf(errmsg, errmsgl,
2005 "The capture session could not be initiated due to the socket error: \n"
2007 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
2009 LocalFree(errorText);
2011 " %d: %s", errno, g_strerror(errno));
2013 pcap_opts->cap_pipe_err = PIPERR;
2016 cap_pipe_close(fd, TRUE);
2020 pcap_opts->from_cap_socket = TRUE;
2024 g_snprintf(errmsg, errmsgl,
2025 "The capture session could not be initiated because\n"
2026 "\"%s\" is not a valid socket specification", pipename);
2027 pcap_opts->cap_pipe_err = PIPERR;
2031 /* Wrapper: distinguish between closesocket on Windows; use ws_close
2035 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
2039 closesocket(pipe_fd);
2046 /* Mimic pcap_open_live() for pipe captures
2048 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
2049 * open it, and read the header.
2051 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
2052 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
2054 cap_pipe_open_live(char *pipename,
2055 pcap_options *pcap_opts,
2056 struct pcap_hdr *hdr,
2057 char *errmsg, int errmsgl)
2060 ws_statb64 pipe_stat;
2061 struct sockaddr_un sa;
2065 interface_options interface_opts;
2067 char* extcap_pipe_name;
2068 gboolean extcap_pipe;
2072 int fd = -1, sel_ret;
2075 pcap_opts->cap_pipe_fd = -1;
2077 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2080 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
2083 * XXX - this blocks until a pcap per-file header has been written to
2084 * the pipe, so it could block indefinitely.
2086 if (strcmp(pipename, "-") == 0) {
2088 fd = 0; /* read from stdin */
2090 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
2092 } else if (!strncmp(pipename, "TCP@", 4)) {
2093 if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
2098 if (ws_stat64(pipename, &pipe_stat) < 0) {
2099 if (errno == ENOENT || errno == ENOTDIR)
2100 pcap_opts->cap_pipe_err = PIPNEXIST;
2102 g_snprintf(errmsg, errmsgl,
2103 "The capture session could not be initiated "
2104 "due to error getting information on pipe/socket: %s", g_strerror(errno));
2105 pcap_opts->cap_pipe_err = PIPERR;
2109 if (S_ISFIFO(pipe_stat.st_mode)) {
2110 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
2112 g_snprintf(errmsg, errmsgl,
2113 "The capture session could not be initiated "
2114 "due to error on pipe open: %s", g_strerror(errno));
2115 pcap_opts->cap_pipe_err = PIPERR;
2118 } else if (S_ISSOCK(pipe_stat.st_mode)) {
2119 fd = socket(AF_UNIX, SOCK_STREAM, 0);
2121 g_snprintf(errmsg, errmsgl,
2122 "The capture session could not be initiated "
2123 "due to error on socket create: %s", g_strerror(errno));
2124 pcap_opts->cap_pipe_err = PIPERR;
2127 sa.sun_family = AF_UNIX;
2129 * The Single UNIX Specification says:
2131 * The size of sun_path has intentionally been left undefined.
2132 * This is because different implementations use different sizes.
2133 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
2134 * of 104. Since most implementations originate from BSD versions,
2135 * the size is typically in the range 92 to 108.
2137 * Applications should not assume a particular length for sun_path
2138 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
2142 * The <sys/un.h> header shall define the sockaddr_un structure,
2143 * which shall include at least the following members:
2145 * sa_family_t sun_family Address family.
2146 * char sun_path[] Socket pathname.
2148 * so we assume that it's an array, with a specified size,
2149 * and that the size reflects the maximum path length.
2151 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
2152 /* Path name too long */
2153 g_snprintf(errmsg, errmsgl,
2154 "The capture session coud not be initiated "
2155 "due to error on socket connect: Path name too long");
2156 pcap_opts->cap_pipe_err = PIPERR;
2160 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
2162 g_snprintf(errmsg, errmsgl,
2163 "The capture session coud not be initiated "
2164 "due to error on socket connect: %s", g_strerror(errno));
2165 pcap_opts->cap_pipe_err = PIPERR;
2170 if (S_ISCHR(pipe_stat.st_mode)) {
2172 * Assume the user specified an interface on a system where
2173 * interfaces are in /dev. Pretend we haven't seen it.
2175 pcap_opts->cap_pipe_err = PIPNEXIST;
2177 g_snprintf(errmsg, errmsgl,
2178 "The capture session could not be initiated because\n"
2179 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
2180 pcap_opts->cap_pipe_err = PIPERR;
2185 #define PIPE_STR "\\pipe\\"
2186 /* Under Windows, named pipes _must_ have the form
2187 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
2189 pncopy = g_strdup(pipename);
2190 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
2191 pos = strchr(pncopy + 3, '\\');
2192 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
2199 g_snprintf(errmsg, errmsgl,
2200 "The capture session could not be initiated because\n"
2201 "\"%s\" is neither an interface nor a pipe", pipename);
2202 pcap_opts->cap_pipe_err = PIPNEXIST;
2206 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
2208 extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
2209 extcap_pipe = strstr(interface_opts.name, extcap_pipe_name) ? TRUE : FALSE;
2210 g_free(extcap_pipe_name);
2213 /* Wait for the pipe to appear */
2218 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
2221 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
2222 OPEN_EXISTING, 0, NULL);
2224 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
2227 if (GetLastError() != ERROR_PIPE_BUSY) {
2228 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2229 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2230 g_snprintf(errmsg, errmsgl,
2231 "The capture session on \"%s\" could not be started "
2232 "due to error on pipe open: %s (error %d)",
2233 pipename, utf_16to8(err_str), GetLastError());
2235 pcap_opts->cap_pipe_err = PIPERR;
2239 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
2240 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2241 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2242 g_snprintf(errmsg, errmsgl,
2243 "The capture session on \"%s\" timed out during "
2244 "pipe open: %s (error %d)",
2245 pipename, utf_16to8(err_str), GetLastError());
2247 pcap_opts->cap_pipe_err = PIPERR;
2254 pcap_opts->from_cap_pipe = TRUE;
2257 if (pcap_opts->from_cap_socket)
2260 /* read the pcap header */
2262 while (bytes_read < sizeof magic) {
2264 g_snprintf(errmsg, errmsgl, "Invalid file descriptor");
2268 sel_ret = cap_pipe_select(fd);
2270 g_snprintf(errmsg, errmsgl,
2271 "Unexpected error from select: %s", g_strerror(errno));
2273 } else if (sel_ret > 0) {
2274 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
2275 sizeof magic-bytes_read,
2276 pcap_opts->from_cap_socket);
2279 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2281 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2291 #if GLIB_CHECK_VERSION(2,31,0)
2292 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
2294 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
2297 pcap_opts->cap_pipe_buf = (char *) &magic;
2298 pcap_opts->cap_pipe_bytes_read = 0;
2299 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
2300 /* We don't have to worry about cap_pipe_read_mtx here */
2301 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2302 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2303 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2304 if (pcap_opts->cap_pipe_bytes_read == 0)
2305 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2307 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2316 case PCAP_NSEC_MAGIC:
2317 /* Host that wrote it has our byte order, and was running
2318 a program using either standard or ss990417 libpcap. */
2319 pcap_opts->cap_pipe_byte_swapped = FALSE;
2320 pcap_opts->cap_pipe_modified = FALSE;
2321 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
2323 case PCAP_MODIFIED_MAGIC:
2324 /* Host that wrote it has our byte order, but was running
2325 a program using either ss990915 or ss991029 libpcap. */
2326 pcap_opts->cap_pipe_byte_swapped = FALSE;
2327 pcap_opts->cap_pipe_modified = TRUE;
2329 case PCAP_SWAPPED_MAGIC:
2330 case PCAP_SWAPPED_NSEC_MAGIC:
2331 /* Host that wrote it has a byte order opposite to ours,
2332 and was running a program using either standard or
2333 ss990417 libpcap. */
2334 pcap_opts->cap_pipe_byte_swapped = TRUE;
2335 pcap_opts->cap_pipe_modified = FALSE;
2336 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2338 case PCAP_SWAPPED_MODIFIED_MAGIC:
2339 /* Host that wrote it out has a byte order opposite to
2340 ours, and was running a program using either ss990915
2341 or ss991029 libpcap. */
2342 pcap_opts->cap_pipe_byte_swapped = TRUE;
2343 pcap_opts->cap_pipe_modified = TRUE;
2346 /* Not a "libpcap" type we know about. */
2347 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2352 if (pcap_opts->from_cap_socket)
2355 /* Read the rest of the header */
2357 while (bytes_read < sizeof(struct pcap_hdr)) {
2358 sel_ret = cap_pipe_select(fd);
2360 g_snprintf(errmsg, errmsgl,
2361 "Unexpected error from select: %s", g_strerror(errno));
2363 } else if (sel_ret > 0) {
2364 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2365 sizeof(struct pcap_hdr) - bytes_read,
2366 pcap_opts->from_cap_socket);
2369 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2371 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
2381 pcap_opts->cap_pipe_buf = (char *) hdr;
2382 pcap_opts->cap_pipe_bytes_read = 0;
2383 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
2384 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2385 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2386 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2387 if (pcap_opts->cap_pipe_bytes_read == 0)
2388 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2390 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
2397 if (pcap_opts->cap_pipe_byte_swapped) {
2398 /* Byte-swap the header fields about which we care. */
2399 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
2400 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
2401 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
2402 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
2404 pcap_opts->linktype = hdr->network;
2406 if (hdr->version_major < 2) {
2407 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2411 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2412 pcap_opts->cap_pipe_err = PIPOK;
2413 pcap_opts->cap_pipe_fd = fd;
2417 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2418 pcap_opts->cap_pipe_err = PIPERR;
2419 cap_pipe_close(fd, pcap_opts->from_cap_socket);
2420 pcap_opts->cap_pipe_fd = -1;
2424 /* We read one record from the pipe, take care of byte order in the record
2425 * header, write the record to the capture file, and update capture statistics. */
2427 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2429 struct pcap_pkthdr phdr;
2430 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2433 #if !GLIB_CHECK_VERSION(2,31,18)
2441 #ifdef LOG_CAPTURE_VERBOSE
2442 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2445 switch (pcap_opts->cap_pipe_state) {
2447 case STATE_EXPECT_REC_HDR:
2449 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2452 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2453 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2454 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2455 pcap_opts->cap_pipe_bytes_read = 0;
2458 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2459 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2460 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2465 case STATE_READ_REC_HDR:
2467 if (pcap_opts->from_cap_socket)
2470 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2471 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
2474 result = PD_PIPE_EOF;
2476 result = PD_PIPE_ERR;
2479 pcap_opts->cap_pipe_bytes_read += b;
2483 #if GLIB_CHECK_VERSION(2,31,18)
2484 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2486 g_get_current_time(&wait_time);
2487 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2488 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2490 if (pcap_opts->cap_pipe_err == PIPEOF) {
2491 result = PD_PIPE_EOF;
2493 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2494 result = PD_PIPE_ERR;
2502 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2504 result = PD_REC_HDR_READ;
2507 case STATE_EXPECT_DATA:
2509 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2512 pcap_opts->cap_pipe_state = STATE_READ_DATA;
2513 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2514 pcap_opts->cap_pipe_bytes_read = 0;
2517 pcap_opts->cap_pipe_buf = (char *) data;
2518 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2519 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2524 case STATE_READ_DATA:
2526 if (pcap_opts->from_cap_socket)
2529 b = cap_pipe_read(pcap_opts->cap_pipe_fd,
2530 data+pcap_opts->cap_pipe_bytes_read,
2531 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
2532 pcap_opts->from_cap_socket);
2535 result = PD_PIPE_EOF;
2537 result = PD_PIPE_ERR;
2540 pcap_opts->cap_pipe_bytes_read += b;
2545 #if GLIB_CHECK_VERSION(2,31,18)
2546 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2548 g_get_current_time(&wait_time);
2549 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2550 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2551 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2552 if (pcap_opts->cap_pipe_err == PIPEOF) {
2553 result = PD_PIPE_EOF;
2555 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2556 result = PD_PIPE_ERR;
2564 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2566 result = PD_DATA_READ;
2570 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2573 } /* switch (pcap_opts->cap_pipe_state) */
2576 * We've now read as much data as we were expecting, so process it.
2580 case PD_REC_HDR_READ:
2581 /* We've read the header. Take care of byte order. */
2582 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2583 &pcap_opts->cap_pipe_rechdr.hdr);
2584 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2585 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2586 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2590 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2591 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2594 /* no data to read? fall through */
2597 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2598 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2599 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2600 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2601 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2604 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2606 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2608 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2612 pcap_opts->cap_pipe_err = PIPEOF;
2617 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2618 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2619 g_snprintf(errmsg, errmsgl,
2620 "Error reading from pipe: %s (error %d)",
2621 utf_16to8(err_str), GetLastError());
2624 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2632 pcap_opts->cap_pipe_err = PIPERR;
2633 /* Return here rather than inside the switch to prevent GCC warning */
2638 /** Open the capture input file (pcap or capture pipe).
2639 * Returns TRUE if it succeeds, FALSE otherwise. */
2641 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2642 char *errmsg, size_t errmsg_len,
2643 char *secondary_errmsg, size_t secondary_errmsg_len)
2645 gchar open_err_str[PCAP_ERRBUF_SIZE];
2646 gchar *sync_msg_str;
2647 interface_options interface_opts;
2648 pcap_options *pcap_opts;
2652 WORD wVersionRequested;
2656 /* XXX - opening Winsock on tshark? */
2658 /* Initialize Windows Socket if we are in a Win32 OS
2659 This needs to be done before querying the interface for network/netmask */
2661 /* XXX - do we really require 1.1 or earlier?
2662 Are there any versions that support only 2.0 or higher? */
2663 wVersionRequested = MAKEWORD(1, 1);
2664 err = WSAStartup(wVersionRequested, &wsaData);
2668 case WSASYSNOTREADY:
2669 g_snprintf(errmsg, (gulong) errmsg_len,
2670 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2673 case WSAVERNOTSUPPORTED:
2674 g_snprintf(errmsg, (gulong) errmsg_len,
2675 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2676 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2679 case WSAEINPROGRESS:
2680 g_snprintf(errmsg, (gulong) errmsg_len,
2681 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2685 g_snprintf(errmsg, (gulong) errmsg_len,
2686 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2690 g_snprintf(errmsg, (gulong) errmsg_len,
2691 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2695 g_snprintf(errmsg, (gulong) errmsg_len,
2696 "Couldn't initialize Windows Sockets: error %d", err);
2699 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2703 if ((use_threads == FALSE) &&
2704 (capture_opts->ifaces->len > 1)) {
2705 g_snprintf(errmsg, (gulong) errmsg_len,
2706 "Using threads is required for capturing on multiple interfaces.");
2710 for (i = 0; i < capture_opts->ifaces->len; i++) {
2711 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2712 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2713 if (pcap_opts == NULL) {
2714 g_snprintf(errmsg, (gulong) errmsg_len,
2715 "Could not allocate memory.");
2718 pcap_opts->received = 0;
2719 pcap_opts->dropped = 0;
2720 pcap_opts->flushed = 0;
2721 pcap_opts->pcap_h = NULL;
2722 #ifdef MUST_DO_SELECT
2723 pcap_opts->pcap_fd = -1;
2725 pcap_opts->pcap_err = FALSE;
2726 pcap_opts->interface_id = i;
2727 pcap_opts->tid = NULL;
2728 pcap_opts->snaplen = 0;
2729 pcap_opts->linktype = -1;
2730 pcap_opts->ts_nsec = FALSE;
2731 pcap_opts->from_cap_pipe = FALSE;
2732 pcap_opts->from_cap_socket = FALSE;
2733 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2734 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2736 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2738 pcap_opts->cap_pipe_fd = -1;
2739 pcap_opts->cap_pipe_modified = FALSE;
2740 pcap_opts->cap_pipe_byte_swapped = FALSE;
2742 pcap_opts->cap_pipe_buf = NULL;
2744 pcap_opts->cap_pipe_bytes_to_read = 0;
2745 pcap_opts->cap_pipe_bytes_read = 0;
2746 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2747 pcap_opts->cap_pipe_err = PIPOK;
2749 #if GLIB_CHECK_VERSION(2,31,0)
2750 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2751 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2753 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2755 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2756 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2758 g_array_append_val(ld->pcaps, pcap_opts);
2760 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2761 pcap_opts->pcap_h = open_capture_device(capture_opts, &interface_opts, &open_err_str);
2763 if (pcap_opts->pcap_h != NULL) {
2764 /* we've opened "iface" as a network device */
2766 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2767 /* Find out if we're getting nanosecond-precision time stamps */
2768 pcap_opts->ts_nsec = have_high_resolution_timestamp(pcap_opts->pcap_h);
2771 #if defined(HAVE_PCAP_SETSAMPLING)
2772 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2773 struct pcap_samp *samp;
2775 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2776 switch (interface_opts.sampling_method) {
2777 case CAPTURE_SAMP_BY_COUNT:
2778 samp->method = PCAP_SAMP_1_EVERY_N;
2781 case CAPTURE_SAMP_BY_TIMER:
2782 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2786 sync_msg_str = g_strdup_printf(
2787 "Unknown sampling method %d specified,\n"
2788 "continue without packet sampling",
2789 interface_opts.sampling_method);
2790 report_capture_error("Couldn't set the capture "
2791 "sampling", sync_msg_str);
2792 g_free(sync_msg_str);
2794 samp->value = interface_opts.sampling_param;
2796 report_capture_error("Couldn't set the capture sampling",
2797 "Cannot get packet sampling data structure");
2802 /* setting the data link type only works on real interfaces */
2803 if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2805 secondary_errmsg, secondary_errmsg_len)) {
2808 pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2810 /* We couldn't open "iface" as a network device. */
2811 /* Try to open it as a pipe */
2812 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2815 if (pcap_opts->cap_pipe_fd == -1) {
2817 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2819 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2820 /* Pipe doesn't exist, so output message for interface */
2821 get_capture_device_open_failure_messages(open_err_str,
2822 interface_opts.name,
2826 secondary_errmsg_len);
2829 * Else pipe (or file) does exist and cap_pipe_open_live() has
2834 /* cap_pipe_open_live() succeeded; don't want
2835 error message from pcap_open_live() */
2836 open_err_str[0] = '\0';
2840 /* XXX - will this work for tshark? */
2841 #ifdef MUST_DO_SELECT
2842 if (!pcap_opts->from_cap_pipe) {
2843 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2844 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2846 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2851 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2852 returned a warning; print it, but keep capturing. */
2853 if (open_err_str[0] != '\0') {
2854 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2855 report_capture_error(sync_msg_str, "");
2856 g_free(sync_msg_str);
2858 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2859 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2862 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2863 /* to remove any suid privileges. */
2864 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2865 /* (euid/egid have already previously been set to ruid/rgid. */
2866 /* (See comment in main() for details) */
2868 relinquish_special_privs_perm();
2870 relinquish_all_capabilities();
2875 /* close the capture input file (pcap or capture pipe) */
2876 static void capture_loop_close_input(loop_data *ld)
2879 pcap_options *pcap_opts;
2881 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2883 for (i = 0; i < ld->pcaps->len; i++) {
2884 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2885 /* if open, close the capture pipe "input file" */
2886 if (pcap_opts->cap_pipe_fd >= 0) {
2887 g_assert(pcap_opts->from_cap_pipe);
2888 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2889 pcap_opts->cap_pipe_fd = -1;
2892 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2893 CloseHandle(pcap_opts->cap_pipe_h);
2894 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2897 /* if open, close the pcap "input file" */
2898 if (pcap_opts->pcap_h != NULL) {
2899 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2900 pcap_close(pcap_opts->pcap_h);
2901 pcap_opts->pcap_h = NULL;
2908 /* Shut down windows sockets */
2914 /* init the capture filter */
2915 static initfilter_status_t
2916 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2917 const gchar * name, const gchar * cfilter)
2919 struct bpf_program fcode;
2921 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2923 /* capture filters only work on real interfaces */
2924 if (cfilter && !from_cap_pipe) {
2925 /* A capture filter was specified; set it up. */
2926 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2927 /* Treat this specially - our caller might try to compile this
2928 as a display filter and, if that succeeds, warn the user that
2929 the display and capture filter syntaxes are different. */
2930 return INITFILTER_BAD_FILTER;
2932 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2933 #ifdef HAVE_PCAP_FREECODE
2934 pcap_freecode(&fcode);
2936 return INITFILTER_OTHER_ERROR;
2938 #ifdef HAVE_PCAP_FREECODE
2939 pcap_freecode(&fcode);
2943 return INITFILTER_NO_ERROR;
2947 /* set up to write to the already-opened capture output file/files */
2949 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2953 pcap_options *pcap_opts;
2954 interface_options interface_opts;
2955 gboolean successful;
2957 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2959 if ((capture_opts->use_pcapng == FALSE) &&
2960 (capture_opts->ifaces->len > 1)) {
2961 g_snprintf(errmsg, errmsg_len,
2962 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
2966 /* Set up to write to the capture file. */
2967 if (capture_opts->multi_files_on) {
2968 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2970 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2971 if (ld->pdh == NULL) {
2976 if (capture_opts->use_pcapng) {
2978 GString *os_info_str;
2980 os_info_str = g_string_new("");
2981 get_os_version_info(os_info_str);
2983 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2984 successful = pcapng_write_session_header_block(ld->pdh,
2985 (const char *)capture_opts->capture_comment, /* Comment*/
2987 os_info_str->str, /* OS*/
2989 -1, /* section_length */
2994 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2995 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2996 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2997 if (pcap_opts->from_cap_pipe) {
2998 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
3000 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
3002 successful = pcapng_write_interface_description_block(global_ld.pdh,
3003 NULL, /* OPT_COMMENT 1 */
3004 interface_opts.name, /* IDB_NAME 2 */
3005 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3006 interface_opts.cfilter, /* IDB_FILTER 11 */
3007 os_info_str->str, /* IDB_OS 12 */
3008 pcap_opts->linktype,
3010 &(global_ld.bytes_written),
3011 0, /* IDB_IF_SPEED 8 */
3012 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3016 g_string_free(os_info_str, TRUE);
3019 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
3020 if (pcap_opts->from_cap_pipe) {
3021 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
3023 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
3025 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
3026 pcap_opts->ts_nsec, &ld->bytes_written, &err);
3034 if (ld->pdh == NULL) {
3035 /* We couldn't set up to write to the capture file. */
3036 /* XXX - use cf_open_error_message from tshark instead? */
3041 g_snprintf(errmsg, errmsg_len,
3042 "The file to which the capture would be"
3043 " saved (\"%s\") could not be opened: Error %d.",
3044 capture_opts->save_file, err);
3046 g_snprintf(errmsg, errmsg_len,
3047 "The file to which the capture would be"
3048 " saved (\"%s\") could not be opened: %s.",
3049 capture_opts->save_file, g_strerror(err));
3061 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
3065 pcap_options *pcap_opts;
3066 guint64 end_time = create_timestamp();
3068 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
3070 if (capture_opts->multi_files_on) {
3071 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
3073 if (capture_opts->use_pcapng) {
3074 for (i = 0; i < global_ld.pcaps->len; i++) {
3075 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3076 if (!pcap_opts->from_cap_pipe) {
3077 guint64 isb_ifrecv, isb_ifdrop;
3078 struct pcap_stat stats;
3080 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
3081 isb_ifrecv = pcap_opts->received;
3082 isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
3084 isb_ifrecv = G_MAXUINT64;
3085 isb_ifdrop = G_MAXUINT64;
3087 pcapng_write_interface_statistics_block(ld->pdh,
3090 "Counters provided by dumpcap",
3099 if (fclose(ld->pdh) == EOF) {
3100 if (err_close != NULL) {
3110 /* dispatch incoming packets (pcap or capture pipe)
3112 * Waits for incoming packets to be available, and calls pcap_dispatch()
3113 * to cause them to be processed.
3115 * Returns the number of packets which were processed.
3117 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3118 * packet-batching behaviour does not cause packets to get held back
3122 capture_loop_dispatch(loop_data *ld,
3123 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
3126 gint packet_count_before;
3127 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
3132 packet_count_before = ld->packet_count;
3133 if (pcap_opts->from_cap_pipe) {
3134 /* dispatch from capture pipe */
3135 #ifdef LOG_CAPTURE_VERBOSE
3136 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3139 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
3141 if (sel_ret < 0 && errno != EINTR) {
3142 g_snprintf(errmsg, errmsg_len,
3143 "Unexpected error from select: %s", g_strerror(errno));
3144 report_capture_error(errmsg, please_report);
3149 * "select()" says we can read from the pipe without blocking
3152 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
3162 /* dispatch from pcap */
3163 #ifdef MUST_DO_SELECT
3165 * If we have "pcap_get_selectable_fd()", we use it to get the
3166 * descriptor on which to select; if that's -1, it means there
3167 * is no descriptor on which you can do a "select()" (perhaps
3168 * because you're capturing on a special device, and that device's
3169 * driver unfortunately doesn't support "select()", in which case
3170 * we don't do the select - which means it might not be possible
3171 * to stop a capture until a packet arrives. If that's unacceptable,
3172 * plead with whoever supplies the software for that device to add
3173 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3174 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3175 * later, so it can use pcap_breakloop().
3177 #ifdef LOG_CAPTURE_VERBOSE
3178 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3180 if (pcap_opts->pcap_fd != -1) {
3181 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
3184 * "select()" says we can read from it without blocking; go for
3187 * We don't have pcap_breakloop(), so we only process one packet
3188 * per pcap_dispatch() call, to allow a signal to stop the
3189 * processing immediately, rather than processing all packets
3190 * in a batch before quitting.
3193 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3195 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3199 /* Error, rather than pcap_breakloop(). */
3200 pcap_opts->pcap_err = TRUE;
3202 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3205 if (sel_ret < 0 && errno != EINTR) {
3206 g_snprintf(errmsg, errmsg_len,
3207 "Unexpected error from select: %s", g_strerror(errno));
3208 report_capture_error(errmsg, please_report);
3214 #endif /* MUST_DO_SELECT */
3216 /* dispatch from pcap without select */
3218 #ifdef LOG_CAPTURE_VERBOSE
3219 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3223 * On Windows, we don't support asynchronously telling a process to
3224 * stop capturing; instead, we check for an indication on a pipe
3225 * after processing packets. We therefore process only one packet
3226 * at a time, so that we can check the pipe after every packet.
3229 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3231 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3235 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3237 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3242 /* Error, rather than pcap_breakloop(). */
3243 pcap_opts->pcap_err = TRUE;
3245 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3247 #else /* pcap_next_ex */
3248 #ifdef LOG_CAPTURE_VERBOSE
3249 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3251 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3254 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3255 * see https://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
3256 * This should be fixed in the WinPcap 4.0 alpha release.
3258 * For reference, an example remote interface:
3259 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3262 /* emulate dispatch from pcap */
3265 struct pcap_pkthdr *pkt_header;
3270 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
3272 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3274 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3279 pcap_opts->pcap_err = TRUE;
3283 #endif /* pcap_next_ex */
3287 #ifdef LOG_CAPTURE_VERBOSE
3288 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3291 return ld->packet_count - packet_count_before;
3295 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3296 * want to grab only the characters between the '{' and '}' delimiters.
3298 * Returns a GString that must be freed with g_string_free(). */
3300 isolate_uuid(const char *iface)
3305 ptr = strchr(iface, '{');
3307 return g_string_new(iface);
3308 gstr = g_string_new(ptr + 1);
3310 ptr = strchr(gstr->str, '}');
3314 gstr = g_string_truncate(gstr, ptr - gstr->str);
3319 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3320 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3322 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3323 char *errmsg, int errmsg_len)
3326 gchar *capfile_name;
3328 gboolean is_tempfile;
3330 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3331 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3333 if (capture_opts->save_file != NULL) {
3334 /* We return to the caller while the capture is in progress.
3335 * Therefore we need to take a copy of save_file in
3336 * case the caller destroys it after we return.
3338 capfile_name = g_strdup(capture_opts->save_file);
3340 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3341 if (capture_opts->multi_files_on) {
3342 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3343 g_snprintf(errmsg, errmsg_len,
3344 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3345 g_free(capfile_name);
3348 if (strcmp(capfile_name, "-") == 0) {
3349 /* write to stdout */
3352 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3353 _setmode(1, O_BINARY);
3356 } /* if (...output_to_pipe ... */
3359 if (capture_opts->multi_files_on) {
3360 /* ringbuffer is enabled */
3361 *save_file_fd = ringbuf_init(capfile_name,
3362 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3363 capture_opts->group_read_access);
3365 /* we need the ringbuf name */
3366 if (*save_file_fd != -1) {
3367 g_free(capfile_name);
3368 capfile_name = g_strdup(ringbuf_current_filename());
3371 /* Try to open/create the specified file for use as a capture buffer. */
3372 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
3373 (capture_opts->group_read_access) ? 0640 : 0600);
3376 is_tempfile = FALSE;
3378 /* Choose a random name for the temporary capture buffer */
3379 if (global_capture_opts.ifaces->len > 1) {
3380 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3383 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
3385 /* use the generic portion of the interface guid to form the basis of the filename */
3386 if (strncmp("NPF_{", basename, 5)==0)
3388 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3390 iface = isolate_uuid(basename);
3392 basename = g_strdup(iface->str);
3393 g_string_free(iface, TRUE);
3396 /* generate the temp file name prefix...
3397 * It would be nice if we could specify a pcapng/pcap filename suffix,
3398 * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
3399 if (capture_opts->use_pcapng) {
3400 prefix = g_strconcat("wireshark_pcapng_", basename, NULL);
3402 prefix = g_strconcat("wireshark_pcap_", basename, NULL);
3406 *save_file_fd = create_tempfile(&tmpname, prefix);
3408 capfile_name = g_strdup(tmpname);
3412 /* did we fail to open the output file? */
3413 if (*save_file_fd == -1) {
3415 g_snprintf(errmsg, errmsg_len,
3416 "The temporary file to which the capture would be saved (\"%s\") "
3417 "could not be opened: %s.", capfile_name, g_strerror(errno));
3419 if (capture_opts->multi_files_on) {
3420 ringbuf_error_cleanup();
3423 g_snprintf(errmsg, errmsg_len,
3424 "The file to which the capture would be saved (\"%s\") "
3425 "could not be opened: %s.", capfile_name,
3428 g_free(capfile_name);
3432 if (capture_opts->save_file != NULL) {
3433 g_free(capture_opts->save_file);
3435 capture_opts->save_file = capfile_name;
3436 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3437 "g_free(capfile_name)". */
3443 /* Do the work of handling either the file size or file duration capture
3444 conditions being reached, and switching files or stopping. */
3446 do_file_switch_or_stop(capture_options *capture_opts,
3447 condition *cnd_autostop_files,
3448 condition *cnd_autostop_size,
3449 condition *cnd_file_duration)
3452 pcap_options *pcap_opts;
3453 interface_options interface_opts;
3454 gboolean successful;
3456 if (capture_opts->multi_files_on) {
3457 if (cnd_autostop_files != NULL &&
3458 cnd_eval(cnd_autostop_files, (guint64)++global_ld.autostop_files)) {
3459 /* no files left: stop here */
3460 global_ld.go = FALSE;
3464 /* Switch to the next ringbuffer file */
3465 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3466 &global_ld.save_file_fd, &global_ld.err)) {
3468 /* File switch succeeded: reset the conditions */
3469 global_ld.bytes_written = 0;
3470 if (capture_opts->use_pcapng) {
3472 GString *os_info_str;
3474 os_info_str = g_string_new("");
3475 get_os_version_info(os_info_str);
3477 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
3478 successful = pcapng_write_session_header_block(global_ld.pdh,
3481 os_info_str->str, /* OS */
3483 -1, /* section_length */
3484 &(global_ld.bytes_written),
3488 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3489 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3490 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3491 successful = pcapng_write_interface_description_block(global_ld.pdh,
3492 NULL, /* OPT_COMMENT 1 */
3493 interface_opts.name, /* IDB_NAME 2 */
3494 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3495 interface_opts.cfilter, /* IDB_FILTER 11 */
3496 os_info_str->str, /* IDB_OS 12 */
3497 pcap_opts->linktype,
3499 &(global_ld.bytes_written),
3500 0, /* IDB_IF_SPEED 8 */
3501 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3505 g_string_free(os_info_str, TRUE);
3508 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3509 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3510 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3513 fclose(global_ld.pdh);
3514 global_ld.pdh = NULL;
3515 global_ld.go = FALSE;
3518 if (cnd_autostop_size)
3519 cnd_reset(cnd_autostop_size);
3520 if (cnd_file_duration)
3521 cnd_reset(cnd_file_duration);
3522 fflush(global_ld.pdh);
3524 report_packet_count(global_ld.inpkts_to_sync_pipe);
3525 global_ld.inpkts_to_sync_pipe = 0;
3526 report_new_capture_file(capture_opts->save_file);
3528 /* File switch failed: stop here */
3529 global_ld.go = FALSE;
3533 /* single file, stop now */
3534 global_ld.go = FALSE;
3541 pcap_read_handler(void* arg)
3543 pcap_options *pcap_opts;
3544 char errmsg[MSG_MAX_LENGTH+1];
3546 pcap_opts = (pcap_options *)arg;
3548 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3549 pcap_opts->interface_id);
3551 while (global_ld.go) {
3552 /* dispatch incoming packets */
3553 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3555 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3556 pcap_opts->interface_id);
3557 g_thread_exit(NULL);
3561 /* Do the low-level work of a capture.
3562 Returns TRUE if it succeeds, FALSE otherwise. */
3564 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3567 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3569 struct timeval upd_time, cur_time;
3573 condition *cnd_file_duration = NULL;
3574 condition *cnd_autostop_files = NULL;
3575 condition *cnd_autostop_size = NULL;
3576 condition *cnd_autostop_duration = NULL;
3579 gboolean cfilter_error = FALSE;
3580 char errmsg[MSG_MAX_LENGTH+1];
3581 char secondary_errmsg[MSG_MAX_LENGTH+1];
3582 pcap_options *pcap_opts;
3583 interface_options interface_opts;
3584 guint i, error_index = 0;
3587 *secondary_errmsg = '\0';
3589 /* init the loop data */
3590 global_ld.go = TRUE;
3591 global_ld.packet_count = 0;
3593 global_ld.report_packet_count = FALSE;
3595 if (capture_opts->has_autostop_packets)
3596 global_ld.packet_max = capture_opts->autostop_packets;
3598 global_ld.packet_max = 0; /* no limit */
3599 global_ld.inpkts_to_sync_pipe = 0;
3600 global_ld.err = 0; /* no error seen yet */
3601 global_ld.pdh = NULL;
3602 global_ld.autostop_files = 0;
3603 global_ld.save_file_fd = -1;
3605 /* We haven't yet gotten the capture statistics. */
3606 *stats_known = FALSE;
3608 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3609 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3611 /* open the "input file" from network interface or capture pipe */
3612 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3613 secondary_errmsg, sizeof(secondary_errmsg))) {
3616 for (i = 0; i < capture_opts->ifaces->len; i++) {
3617 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3618 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3619 /* init the input filter from the network interface (capture pipe will do nothing) */
3621 * When remote capturing WinPCap crashes when the capture filter
3622 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3625 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3626 interface_opts.name,
3627 interface_opts.cfilter?interface_opts.cfilter:"")) {
3629 case INITFILTER_NO_ERROR:
3632 case INITFILTER_BAD_FILTER:
3633 cfilter_error = TRUE;
3635 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3638 case INITFILTER_OTHER_ERROR:
3639 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3640 pcap_geterr(pcap_opts->pcap_h));
3641 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3646 /* If we're supposed to write to a capture file, open it for output
3647 (temporary/specified name/ringbuffer) */
3648 if (capture_opts->saving_to_file) {
3649 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3650 errmsg, sizeof(errmsg))) {
3654 /* set up to write to the already-opened capture output file/files */
3655 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3660 /* XXX - capture SIGTERM and close the capture, in case we're on a
3661 Linux 2.0[.x] system and you have to explicitly close the capture
3662 stream in order to turn promiscuous mode off? We need to do that
3663 in other places as well - and I don't think that works all the
3664 time in any case, due to libpcap bugs. */
3666 /* Well, we should be able to start capturing.
3668 Sync out the capture file, so the header makes it to the file system,
3669 and send a "capture started successfully and capture file created"
3670 message to our parent so that they'll open the capture file and
3671 update its windows to indicate that we have a live capture in
3673 fflush(global_ld.pdh);
3674 report_new_capture_file(capture_opts->save_file);
3677 /* initialize capture stop (and alike) conditions */
3678 init_capture_stop_conditions();
3679 /* create stop conditions */
3680 if (capture_opts->has_autostop_filesize) {
3681 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3682 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3685 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3687 if (capture_opts->has_autostop_duration)
3688 cnd_autostop_duration =
3689 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3691 if (capture_opts->multi_files_on) {
3692 if (capture_opts->has_file_duration)
3694 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3696 if (capture_opts->has_autostop_files)
3697 cnd_autostop_files =
3698 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_files);
3701 /* init the time values */
3703 upd_time = GetTickCount();
3705 gettimeofday(&upd_time, NULL);
3707 start_time = create_timestamp();
3708 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3710 /* WOW, everything is prepared! */
3711 /* please fasten your seat belts, we will enter now the actual capture loop */
3713 pcap_queue = g_async_queue_new();
3714 pcap_queue_bytes = 0;
3715 pcap_queue_packets = 0;
3716 for (i = 0; i < global_ld.pcaps->len; i++) {
3717 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3718 #if GLIB_CHECK_VERSION(2,31,0)
3719 /* XXX - Add an interface name here? */
3720 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3722 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3726 while (global_ld.go) {
3727 /* dispatch incoming packets */
3729 pcap_queue_element *queue_element;
3730 #if GLIB_CHECK_VERSION(2,31,18)
3732 g_async_queue_lock(pcap_queue);
3733 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3735 GTimeVal write_thread_time;
3737 g_get_current_time(&write_thread_time);
3738 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3739 g_async_queue_lock(pcap_queue);
3740 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3742 if (queue_element) {
3743 pcap_queue_bytes -= queue_element->phdr.caplen;
3744 pcap_queue_packets -= 1;
3746 g_async_queue_unlock(pcap_queue);
3747 if (queue_element) {
3748 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3749 "Dequeued a packet of length %d captured on interface %d.",
3750 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3752 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3753 &queue_element->phdr,
3755 g_free(queue_element->pd);
3756 g_free(queue_element);
3762 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3763 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3764 sizeof(errmsg), pcap_opts);
3767 /* Were we asked to print packet counts by the SIGINFO handler? */
3768 if (global_ld.report_packet_count) {
3769 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3770 plurality(global_ld.packet_count, "", "s"));
3771 global_ld.report_packet_count = FALSE;
3776 /* any news from our parent (signal pipe)? -> just stop the capture */
3777 if (!signal_pipe_check_running()) {
3778 global_ld.go = FALSE;
3783 global_ld.inpkts_to_sync_pipe += inpkts;
3785 /* check capture size condition */
3786 if (cnd_autostop_size != NULL &&
3787 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3788 /* Capture size limit reached, do we have another file? */
3789 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3790 cnd_autostop_size, cnd_file_duration))
3792 } /* cnd_autostop_size */
3793 if (capture_opts->output_to_pipe) {
3794 fflush(global_ld.pdh);
3798 /* Only update once every 500ms so as not to overload slow displays.
3799 * This also prevents too much context-switching between the dumpcap
3800 * and wireshark processes.
3802 #define DUMPCAP_UPD_TIME 500
3805 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3806 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3808 gettimeofday(&cur_time, NULL);
3809 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3810 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3813 upd_time = cur_time;
3816 if (pcap_stats(pch, stats) >= 0) {
3817 *stats_known = TRUE;
3820 /* Let the parent process know. */
3821 if (global_ld.inpkts_to_sync_pipe) {
3823 fflush(global_ld.pdh);
3825 /* Send our parent a message saying we've written out
3826 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3828 report_packet_count(global_ld.inpkts_to_sync_pipe);
3830 global_ld.inpkts_to_sync_pipe = 0;
3833 /* check capture duration condition */
3834 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3835 /* The maximum capture time has elapsed; stop the capture. */
3836 global_ld.go = FALSE;
3840 /* check capture file duration condition */
3841 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3842 /* duration limit reached, do we have another file? */
3843 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3844 cnd_autostop_size, cnd_file_duration))
3846 } /* cnd_file_duration */
3850 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3852 pcap_queue_element *queue_element;
3854 for (i = 0; i < global_ld.pcaps->len; i++) {
3855 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3856 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3857 pcap_opts->interface_id);
3858 g_thread_join(pcap_opts->tid);
3859 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3860 pcap_opts->interface_id);
3863 g_async_queue_lock(pcap_queue);
3864 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3865 if (queue_element) {
3866 pcap_queue_bytes -= queue_element->phdr.caplen;
3867 pcap_queue_packets -= 1;
3869 g_async_queue_unlock(pcap_queue);
3870 if (queue_element == NULL) {
3873 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3874 "Dequeued a packet of length %d captured on interface %d.",
3875 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3876 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3877 &queue_element->phdr,
3879 g_free(queue_element->pd);
3880 g_free(queue_element);
3881 global_ld.inpkts_to_sync_pipe += 1;
3882 if (capture_opts->output_to_pipe) {
3883 fflush(global_ld.pdh);
3889 /* delete stop conditions */
3890 if (cnd_file_duration != NULL)
3891 cnd_delete(cnd_file_duration);
3892 if (cnd_autostop_files != NULL)
3893 cnd_delete(cnd_autostop_files);
3894 if (cnd_autostop_size != NULL)
3895 cnd_delete(cnd_autostop_size);
3896 if (cnd_autostop_duration != NULL)
3897 cnd_delete(cnd_autostop_duration);
3899 /* did we have a pcap (input) error? */
3900 for (i = 0; i < capture_opts->ifaces->len; i++) {
3901 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3902 if (pcap_opts->pcap_err) {
3903 /* On Linux, if an interface goes down while you're capturing on it,
3904 you'll get a "recvfrom: Network is down" or
3905 "The interface went down" error (ENETDOWN).
3906 (At least you will if g_strerror() doesn't show a local translation
3909 On FreeBSD and OS X, if a network adapter disappears while
3910 you're capturing on it, you'll get a "read: Device not configured"
3911 error (ENXIO). (See previous parenthetical note.)
3913 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3915 These should *not* be reported to the Wireshark developers. */
3918 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3919 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3920 strcmp(cap_err_str, "The interface went down") == 0 ||
3921 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3922 strcmp(cap_err_str, "read: I/O error") == 0 ||
3923 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3924 report_capture_error("The network adapter on which the capture was being done "
3925 "is no longer running; the capture has stopped.",
3928 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3930 report_capture_error(errmsg, please_report);
3933 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3934 report_capture_error(errmsg, "");
3938 /* did we have an output error while capturing? */
3939 if (global_ld.err == 0) {
3942 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3943 global_ld.err, FALSE);
3944 report_capture_error(errmsg, please_report);
3948 if (capture_opts->saving_to_file) {
3949 /* close the output file */
3950 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3954 /* there might be packets not yet notified to the parent */
3955 /* (do this after closing the file, so all packets are already flushed) */
3956 if (global_ld.inpkts_to_sync_pipe) {
3958 report_packet_count(global_ld.inpkts_to_sync_pipe);
3959 global_ld.inpkts_to_sync_pipe = 0;
3962 /* If we've displayed a message about a write error, there's no point
3963 in displaying another message about an error on close. */
3964 if (!close_ok && write_ok) {
3965 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3967 report_capture_error(errmsg, "");
3971 * XXX We exhibit different behaviour between normal mode and sync mode
3972 * when the pipe is stdin and not already at EOF. If we're a child, the
3973 * parent's stdin isn't closed, so if the user starts another capture,
3974 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3975 * will say "Unrecognized libpcap format". On the other hand, in normal
3976 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3979 report_capture_count(TRUE);
3981 /* get packet drop statistics from pcap */
3982 for (i = 0; i < capture_opts->ifaces->len; i++) {
3984 guint32 pcap_dropped = 0;
3986 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3987 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3988 received = pcap_opts->received;
3989 if (pcap_opts->pcap_h != NULL) {
3990 g_assert(!pcap_opts->from_cap_pipe);
3991 /* Get the capture statistics, so we know how many packets were dropped. */
3993 * Older versions of libpcap didn't set ps_ifdrop on some
3994 * platforms; initialize it to 0 to handle that.
3996 stats->ps_ifdrop = 0;
3997 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3998 *stats_known = TRUE;
3999 /* Let the parent process know. */
4000 pcap_dropped += stats->ps_drop;
4002 g_snprintf(errmsg, sizeof(errmsg),
4003 "Can't get packet-drop statistics: %s",
4004 pcap_geterr(pcap_opts->pcap_h));
4005 report_capture_error(errmsg, please_report);
4008 report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
4011 /* close the input file (pcap or capture pipe) */
4012 capture_loop_close_input(&global_ld);
4014 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
4016 /* ok, if the write and the close were successful. */
4017 return write_ok && close_ok;
4020 if (capture_opts->multi_files_on) {
4021 /* cleanup ringbuffer */
4022 ringbuf_error_cleanup();
4024 /* We can't use the save file, and we have no FILE * for the stream
4025 to close in order to close it, so close the FD directly. */
4026 if (global_ld.save_file_fd != -1) {
4027 ws_close(global_ld.save_file_fd);
4030 /* We couldn't even start the capture, so get rid of the capture
4032 if (capture_opts->save_file != NULL) {
4033 ws_unlink(capture_opts->save_file);
4034 g_free(capture_opts->save_file);
4037 capture_opts->save_file = NULL;
4039 report_cfilter_error(capture_opts, error_index, errmsg);
4041 report_capture_error(errmsg, secondary_errmsg);
4043 /* close the input file (pcap or cap_pipe) */
4044 capture_loop_close_input(&global_ld);
4046 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
4053 capture_loop_stop(void)
4055 #ifdef HAVE_PCAP_BREAKLOOP
4057 pcap_options *pcap_opts;
4059 for (i = 0; i < global_ld.pcaps->len; i++) {
4060 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
4061 if (pcap_opts->pcap_h != NULL)
4062 pcap_breakloop(pcap_opts->pcap_h);
4065 global_ld.go = FALSE;
4070 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
4071 int err, gboolean is_close)
4076 g_snprintf(errmsg, errmsglen,
4077 "Not all the packets could be written to the file"
4078 " to which the capture was being saved\n"
4079 "(\"%s\") because there is no space left on the file system\n"
4080 "on which that file resides.",
4086 g_snprintf(errmsg, errmsglen,
4087 "Not all the packets could be written to the file"
4088 " to which the capture was being saved\n"
4089 "(\"%s\") because you are too close to, or over,"
4090 " your disk quota\n"
4091 "on the file system on which that file resides.",
4098 g_snprintf(errmsg, errmsglen,
4099 "The file to which the capture was being saved\n"
4100 "(\"%s\") could not be closed: %s.",
4101 fname, g_strerror(err));
4103 g_snprintf(errmsg, errmsglen,
4104 "An error occurred while writing to the file"
4105 " to which the capture was being saved\n"
4107 fname, g_strerror(err));
4114 /* one packet was captured, process it */
4116 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4119 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4121 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
4123 /* We may be called multiple times from pcap_dispatch(); if we've set
4124 the "stop capturing" flag, ignore this packet, as we're not
4125 supposed to be saving any more packets. */
4126 if (!global_ld.go) {
4127 pcap_opts->flushed++;
4131 if (global_ld.pdh) {
4132 gboolean successful;
4134 /* We're supposed to write the packet to a file; do so.
4135 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4136 "ld->err" to the error. */
4137 if (global_capture_opts.use_pcapng) {
4138 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4140 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4141 phdr->caplen, phdr->len,
4142 pcap_opts->interface_id,
4145 &global_ld.bytes_written, &err);
4147 successful = libpcap_write_packet(global_ld.pdh,
4148 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4149 phdr->caplen, phdr->len,
4151 &global_ld.bytes_written, &err);
4154 global_ld.go = FALSE;
4155 global_ld.err = err;
4156 pcap_opts->dropped++;
4158 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4159 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4160 "Wrote a packet of length %d captured on interface %u.",
4161 phdr->caplen, pcap_opts->interface_id);
4163 global_ld.packet_count++;
4164 pcap_opts->received++;
4165 /* if the user told us to stop after x packets, do we already have enough? */
4166 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4167 global_ld.go = FALSE;
4173 /* one packet was captured, queue it */
4175 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4178 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4179 pcap_queue_element *queue_element;
4180 gboolean limit_reached;
4182 /* We may be called multiple times from pcap_dispatch(); if we've set
4183 the "stop capturing" flag, ignore this packet, as we're not
4184 supposed to be saving any more packets. */
4185 if (!global_ld.go) {
4186 pcap_opts->flushed++;
4190 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4191 if (queue_element == NULL) {
4192 pcap_opts->dropped++;
4195 queue_element->pcap_opts = pcap_opts;
4196 queue_element->phdr = *phdr;
4197 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4198 if (queue_element->pd == NULL) {
4199 pcap_opts->dropped++;
4200 g_free(queue_element);
4203 memcpy(queue_element->pd, pd, phdr->caplen);
4204 g_async_queue_lock(pcap_queue);
4205 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4206 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4207 limit_reached = FALSE;
4208 g_async_queue_push_unlocked(pcap_queue, queue_element);
4209 pcap_queue_bytes += phdr->caplen;
4210 pcap_queue_packets += 1;
4212 limit_reached = TRUE;
4214 g_async_queue_unlock(pcap_queue);
4215 if (limit_reached) {
4216 pcap_opts->dropped++;
4217 g_free(queue_element->pd);
4218 g_free(queue_element);
4219 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4220 "Dropped a packet of length %d captured on interface %u.",
4221 phdr->caplen, pcap_opts->interface_id);
4223 pcap_opts->received++;
4224 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4225 "Queued a packet of length %d captured on interface %u.",
4226 phdr->caplen, pcap_opts->interface_id);
4228 /* I don't want to hold the mutex over the debug output. So the
4229 output may be wrong */
4230 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4231 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4232 pcap_queue_bytes, pcap_queue_packets);
4236 set_80211_channel(const char *iface, const char *opt)
4238 int freq = 0, type, ret;
4239 gchar **options = NULL;
4241 options = g_strsplit_set(opt, ",", 2);
4244 freq = atoi(options[0]);
4247 type = ws80211_str_to_chan_type(options[1]);
4256 ret = ws80211_init();
4258 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4262 ret = ws80211_set_freq(iface, freq, type);
4265 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4271 pipe_write_block(2, SP_SUCCESS, NULL);
4275 g_strfreev(options);
4280 get_dumpcap_compiled_info(GString *str)
4282 /* Capture libraries */
4283 g_string_append(str, ", ");
4284 get_compiled_caplibs_version(str);
4287 g_string_append(str, ", ");
4289 g_string_append(str, "with libz ");
4291 g_string_append(str, ZLIB_VERSION);
4292 #else /* ZLIB_VERSION */
4293 g_string_append(str, "(version unknown)");
4294 #endif /* ZLIB_VERSION */
4295 #else /* HAVE_LIBZ */
4296 g_string_append(str, "without libz");
4297 #endif /* HAVE_LIBZ */
4301 get_dumpcap_runtime_info(GString *str)
4303 /* Capture libraries */
4304 g_string_append(str, ", ");
4305 get_runtime_caplibs_version(str);
4308 #if defined(HAVE_LIBZ) && !defined(_WIN32)
4309 g_string_append_printf(str, ", with libz %s", zlibVersion());
4313 /* And now our feature presentation... [ fade to music ] */
4315 main(int argc, char *argv[])
4317 GString *comp_info_str;
4318 GString *runtime_info_str;
4320 static const struct option long_options[] = {
4321 {"help", no_argument, NULL, 'h'},
4322 {"version", no_argument, NULL, 'v'},
4323 LONGOPT_CAPTURE_COMMON
4327 gboolean arg_error = FALSE;
4332 struct sigaction action, oldaction;
4335 gboolean start_capture = TRUE;
4336 gboolean stats_known;
4337 struct pcap_stat stats;
4338 GLogLevelFlags log_flags;
4339 gboolean list_interfaces = FALSE;
4340 gboolean list_link_layer_types = FALSE;
4341 #ifdef HAVE_BPF_IMAGE
4342 gboolean print_bpf_code = FALSE;
4344 gboolean set_chan = FALSE;
4345 gchar *set_chan_arg = NULL;
4346 gboolean machine_readable = FALSE;
4347 gboolean print_statistics = FALSE;
4348 int status, run_once_args = 0;
4351 #if defined(__APPLE__) && defined(__LP64__)
4352 struct utsname osinfo;
4356 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
4358 /* Get the compile-time version information string */
4359 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4361 /* Get the run-time version information string */
4362 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4364 /* Add it to the information to be reported on a crash. */
4365 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
4370 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
4373 arg_list_utf_16to8(argc, argv);
4374 create_app_running_mutex();
4377 * Initialize our DLL search path. MUST be called before LoadLibrary
4380 ws_init_dll_search_path();
4383 #ifdef HAVE_BPF_IMAGE
4384 #define OPTSTRING_d "d"
4386 #define OPTSTRING_d ""
4389 #ifdef HAVE_PCAP_REMOTE
4390 #define OPTSTRING_r "r"
4391 #define OPTSTRING_u "u"
4393 #define OPTSTRING_r ""
4394 #define OPTSTRING_u ""
4397 #ifdef HAVE_PCAP_SETSAMPLING
4398 #define OPTSTRING_m "m:"
4400 #define OPTSTRING_m ""
4403 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
4405 #ifdef DEBUG_CHILD_DUMPCAP
4406 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4407 fprintf (stderr, "Unable to open debug log file .\n");
4412 #if defined(__APPLE__) && defined(__LP64__)
4414 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4415 * a bug workaround - timeouts less than 1 second don't work with libpcap
4416 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4417 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4418 * The problem is extremely unlikely to be reintroduced in a future
4421 if (uname(&osinfo) == 0) {
4423 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
4424 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4425 * number of 10.0.0, not 10.1.0 - go figure).
4427 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4428 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4429 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4430 need_timeout_workaround = TRUE;
4435 * Determine if dumpcap is being requested to run in a special
4436 * capture_child mode by going thru the command line args to see if
4437 * a -Z is present. (-Z is a hidden option).
4439 * The primary result of running in capture_child mode is that
4440 * all messages sent out on stderr are in a special type/len/string
4441 * format to allow message processing by type. These messages include
4442 * error messages if dumpcap fails to start the operation it was
4443 * requested to do, as well as various "status" messages which are sent
4444 * when an actual capture is in progress, and a "success" message sent
4445 * if dumpcap was requested to perform an operation other than a
4448 * Capture_child mode would normally be requested by a parent process
4449 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4450 * to which dumpcap stderr has been redirected. It might also have
4451 * another pipe to obtain dumpcap stdout output; for operations other
4452 * than a capture, that information is formatted specially for easier
4453 * parsing by the parent process.
4455 * Capture_child mode needs to be determined immediately upon
4456 * startup so that any messages generated by dumpcap in this mode
4457 * (eg: during initialization) will be formatted properly.
4460 for (i=1; i<argc; i++) {
4461 if (strcmp("-Z", argv[i]) == 0) {
4462 capture_child = TRUE;
4463 machine_readable = TRUE; /* request machine-readable output */
4465 /* set output pipe to binary mode, to avoid ugly text conversions */
4466 _setmode(2, O_BINARY);
4471 /* The default_log_handler will use stdout, which makes trouble in */
4472 /* capture child mode, as it uses stdout for its sync_pipe. */
4473 /* So: the filtering is done in the console_log_handler and not here.*/
4474 /* We set the log handlers right up front to make sure that any log */
4475 /* messages when running as child will be sent back to the parent */
4476 /* with the correct format. */
4481 G_LOG_LEVEL_CRITICAL|
4482 G_LOG_LEVEL_WARNING|
4483 G_LOG_LEVEL_MESSAGE|
4487 G_LOG_FLAG_RECURSION);
4489 g_log_set_handler(NULL,
4491 console_log_handler, NULL /* user_data */);
4492 g_log_set_handler(LOG_DOMAIN_MAIN,
4494 console_log_handler, NULL /* user_data */);
4495 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4497 console_log_handler, NULL /* user_data */);
4498 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4500 console_log_handler, NULL /* user_data */);
4502 /* Initialize the pcaps list */
4503 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
4505 #if !GLIB_CHECK_VERSION(2,31,0)
4506 /* Initialize the thread system */
4507 g_thread_init(NULL);
4511 /* Load wpcap if possible. Do this before collecting the run-time version information */
4514 /* ... and also load the packet.dll from wpcap */
4515 /* XXX - currently not required, may change later. */
4516 /*wpcap_packet_load();*/
4518 /* Start windows sockets */
4519 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4521 /* Set handler for Ctrl+C key */
4522 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4524 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4525 and exit. Do the same with SIGPIPE, in case, for example,
4526 we're writing to our standard output and it's a pipe.
4527 Do the same with SIGHUP if it's not being ignored (if we're
4528 being run under nohup, it might be ignored, in which case we
4529 should leave it ignored).
4531 XXX - apparently, Coverity complained that part of action
4532 wasn't initialized. Perhaps it's running on Linux, where
4533 struct sigaction has an ignored "sa_restorer" element and
4534 where "sa_handler" and "sa_sigaction" might not be two
4535 members of a union. */
4536 memset(&action, 0, sizeof(action));
4537 action.sa_handler = capture_cleanup_handler;
4539 * Arrange that system calls not get restarted, because when
4540 * our signal handler returns we don't want to restart
4541 * a call that was waiting for packets to arrive.
4543 action.sa_flags = 0;
4544 sigemptyset(&action.sa_mask);
4545 sigaction(SIGTERM, &action, NULL);
4546 sigaction(SIGINT, &action, NULL);
4547 sigaction(SIGPIPE, &action, NULL);
4548 sigaction(SIGHUP, NULL, &oldaction);
4549 if (oldaction.sa_handler == SIG_DFL)
4550 sigaction(SIGHUP, &action, NULL);
4553 /* Catch SIGINFO and, if we get it and we're capturing in
4554 quiet mode, report the number of packets we've captured. */
4555 action.sa_handler = report_counts_siginfo;
4556 action.sa_flags = SA_RESTART;
4557 sigemptyset(&action.sa_mask);
4558 sigaction(SIGINFO, &action, NULL);
4559 #endif /* SIGINFO */
4563 enable_kernel_bpf_jit_compiler();
4566 /* ----------------------------------------------------------------- */
4567 /* Privilege and capability handling */
4569 /* 1. Running not as root or suid root; no special capabilities. */
4572 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4575 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4577 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4578 /* capabilities; Drop all other capabilities; */
4579 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4580 /* else: after pcap_open_live() in capture_loop_open_input() */
4581 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4582 /* (Note: this means that the process, although logged in */
4583 /* as root, does not have various permissions such as the */
4584 /* ability to bypass file access permissions). */
4585 /* XXX: Should we just leave capabilities alone in this case */
4586 /* so that user gets expected effect that root can do */
4589 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4591 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4592 /* else: after pcap_open_live() in capture_loop_open_input() */
4593 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4594 /* pcap_open_live). */
4596 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4598 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4599 /* capabilities; Drop all other capabilities; */
4600 /* Drop suid privileges (euid=ruid); */
4601 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4602 /* else: after pcap_open_live() in capture_loop_open_input() */
4603 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4605 /* XXX: For some Linux versions/distros with capabilities */
4606 /* a 'normal' process with any capabilities cannot be */
4607 /* 'killed' (signaled) from another (same uid) non-privileged */
4609 /* For example: If (non-suid) Wireshark forks a */
4610 /* child suid dumpcap which acts as described here (case 5), */
4611 /* Wireshark will be unable to kill (signal) the child */
4612 /* dumpcap process until the capabilities have been dropped */
4613 /* (after pcap_open_live()). */
4614 /* This behaviour will apparently be changed in the kernel */
4615 /* to allow the kill (signal) in this case. */
4616 /* See the following for details: */
4617 /* https://www.mail-archive.com/ [wrapped] */
4618 /* linux-security-module@vger.kernel.org/msg02913.html */
4620 /* It is therefore conceivable that if dumpcap somehow hangs */
4621 /* in pcap_open_live or before that wireshark will not */
4622 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4623 /* In this case, exiting wireshark will kill the child */
4624 /* dumpcap process. */
4626 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4627 /* capabilities; Using libcap. Note: capset cmd (which see) */
4628 /* used to assign capabilities to file. */
4630 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4631 /* else: after pcap_open_live() in capture_loop_open_input() */
4632 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4634 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4635 /* longer required (similar to capture). */
4637 /* ----------------------------------------------------------------- */
4639 init_process_policies();
4642 /* If 'started with special privileges' (and using libcap) */
4643 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4644 /* Set euid/egid = ruid/rgid to remove suid privileges */
4645 relinquish_privs_except_capture();
4648 /* Set the initial values in the capture options. This might be overwritten
4649 by the command line parameters. */
4650 capture_opts_init(&global_capture_opts);
4651 /* We always save to a file - if no file was specified, we save to a
4653 global_capture_opts.saving_to_file = TRUE;
4654 global_capture_opts.has_ring_num_files = TRUE;
4656 /* Pass on capture_child mode for capture_opts */
4657 global_capture_opts.capture_child = capture_child;
4659 /* Now get our args */
4660 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4662 case 'h': /* Print help and exit */
4663 printf("Dumpcap (Wireshark) %s\n"
4664 "Capture network packets and dump them into a pcapng or pcap file.\n"
4665 "See https://www.wireshark.org for more information.\n",
4666 get_ws_vcs_version_info());
4667 print_usage(stdout);
4670 case 'v': /* Show version and exit */
4672 show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4673 g_string_free(comp_info_str, TRUE);
4674 g_string_free(runtime_info_str, TRUE);
4678 /*** capture option specific ***/
4679 case 'a': /* autostop criteria */
4680 case 'b': /* Ringbuffer option */
4681 case 'c': /* Capture x packets */
4682 case 'f': /* capture filter */
4683 case 'g': /* enable group read access on file(s) */
4684 case 'i': /* Use interface x */
4685 case 'n': /* Use pcapng format */
4686 case 'p': /* Don't capture in promiscuous mode */
4687 case 'P': /* Use pcap format */
4688 case 's': /* Set the snapshot (capture) length */
4689 case 'w': /* Write to capture file x */
4690 case 'y': /* Set the pcap data link type */
4691 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4692 #ifdef HAVE_PCAP_REMOTE
4693 case 'u': /* Use UDP for data transfer */
4694 case 'r': /* Capture own RPCAP traffic too */
4695 case 'A': /* Authentication */
4697 #ifdef HAVE_PCAP_SETSAMPLING
4698 case 'm': /* Sampling */
4700 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4701 case 'B': /* Buffer size */
4703 #ifdef HAVE_PCAP_CREATE
4704 case 'I': /* Monitor mode */
4706 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4711 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4713 capture_child = TRUE;
4715 /* set output pipe to binary mode, to avoid ugly text conversions */
4716 _setmode(2, O_BINARY);
4718 * optarg = the control ID, aka the PPID, currently used for the
4721 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4722 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4723 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4724 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4726 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4727 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4728 "Signal pipe: Unable to open %s. Dead parent?",
4736 case 'q': /* Quiet */
4742 /*** all non capture option specific ***/
4743 case 'D': /* Print a list of capture devices and exit */
4744 if (!list_interfaces) {
4745 list_interfaces = TRUE;
4749 case 'L': /* Print list of link-layer types and exit */
4750 if (!list_link_layer_types) {
4751 list_link_layer_types = TRUE;
4755 #ifdef HAVE_BPF_IMAGE
4756 case 'd': /* Print BPF code for capture filter and exit */
4757 if (!print_bpf_code) {
4758 print_bpf_code = TRUE;
4763 case 'S': /* Print interface statistics once a second */
4764 if (!print_statistics) {
4765 print_statistics = TRUE;
4769 case 'k': /* Set wireless channel */
4772 set_chan_arg = optarg;
4775 cmdarg_err("Only one -k flag may be specified");
4779 case 'M': /* For -D, -L, and -S, print machine-readable output */
4780 machine_readable = TRUE;
4783 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4786 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4789 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4791 case '?': /* Bad flag - print usage message */
4800 /* user specified file name as regular command-line argument */
4801 /* XXX - use it as the capture file name (or something else)? */
4807 * Extra command line arguments were specified; complain.
4808 * XXX - interpret as capture filter, as tcpdump and tshark do?
4810 cmdarg_err("Invalid argument: %s", argv[0]);
4815 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4818 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4819 /* Use some default if the user hasn't specified some */
4820 /* XXX: Are these defaults good enough? */
4821 pcap_queue_byte_limit = 1000 * 1000;
4822 pcap_queue_packet_limit = 1000;
4825 print_usage(stderr);
4829 if (run_once_args > 1) {
4830 #ifdef HAVE_BPF_IMAGE
4831 cmdarg_err("Only one of -D, -L, -d, -k, or -S may be supplied.");
4833 cmdarg_err("Only one of -D, -L, -k, or -S may be supplied.");
4836 } else if (run_once_args == 1) {
4837 /* We're supposed to print some information, rather than
4838 to capture traffic; did they specify a ring buffer option? */
4839 if (global_capture_opts.multi_files_on) {
4840 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4844 /* We're supposed to capture traffic; */
4846 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4847 if (global_capture_opts.ifaces->len > 1) {
4849 global_capture_opts.use_pcapng = TRUE;
4852 if (global_capture_opts.capture_comment &&
4853 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4854 /* XXX - for ringbuffer, should we apply the comment to each file? */
4855 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4859 /* Was the ring buffer option specified and, if so, does it make sense? */
4860 if (global_capture_opts.multi_files_on) {
4861 /* Ring buffer works only under certain conditions:
4862 a) ring buffer does not work with temporary files;
4863 b) it makes no sense to enable the ring buffer if the maximum
4864 file size is set to "infinite". */
4865 if (global_capture_opts.save_file == NULL) {
4866 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4867 global_capture_opts.multi_files_on = FALSE;
4869 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4870 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4872 /* XXX - this must be redesigned as the conditions changed */
4873 global_capture_opts.multi_files_on = FALSE;
4880 * "-D" requires no interface to be selected; it's supposed to list
4883 if (list_interfaces) {
4884 /* Get the list of interfaces */
4889 if_list = capture_interface_list(&err, &err_str,NULL);
4890 if (if_list == NULL) {
4893 * If we're being run by another program, just give them
4894 * an empty list of interfaces, don't report this as
4895 * an error; that lets them decide whether to report
4896 * this as an error or not.
4898 if (!machine_readable) {
4899 cmdarg_err("There are no interfaces on which a capture can be done");
4903 cmdarg_err("%s", err_str);
4909 if (machine_readable) /* tab-separated values to stdout */
4910 print_machine_readable_interfaces(if_list);
4912 capture_opts_print_interfaces(if_list);
4913 free_interface_list(if_list);
4918 * "-S" requires no interface to be selected; it gives statistics
4919 * for all interfaces.
4921 if (print_statistics) {
4922 status = print_statistics_loop(machine_readable);
4927 interface_options interface_opts;
4929 if (global_capture_opts.ifaces->len != 1) {
4930 cmdarg_err("Need one interface");
4934 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4935 status = set_80211_channel(interface_opts.name, set_chan_arg);
4940 * "-L", "-d", and capturing act on a particular interface, so we have to
4941 * have an interface; if none was specified, pick a default.
4943 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4945 /* cmdarg_err() already called .... */
4949 if (list_link_layer_types) {
4950 /* Get the list of link-layer types for the capture device. */
4951 if_capabilities_t *caps;
4955 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4956 interface_options interface_opts;
4958 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4960 caps = get_if_capabilities(&interface_opts, &err_str);
4962 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4963 "Please check to make sure you have sufficient permissions, and that\n"
4964 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4968 if (caps->data_link_types == NULL) {
4969 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4972 if (machine_readable) /* tab-separated values to stdout */
4973 /* XXX: We need to change the format and adopt consumers */
4974 print_machine_readable_if_capabilities(caps);
4976 /* XXX: We might want to print also the interface name */
4977 capture_opts_print_if_capabilities(caps, interface_opts.name,
4978 interface_opts.monitor_mode);
4979 free_if_capabilities(caps);
4984 /* We're supposed to do a capture, or print the BPF code for a filter. */
4986 /* Let the user know what interfaces were chosen. */
4987 if (capture_child) {
4988 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4989 interface_options interface_opts;
4991 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4992 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4993 interface_opts.name);
4996 str = g_string_new("");
4998 if (global_capture_opts.ifaces->len < 2)
5000 if (global_capture_opts.ifaces->len < 4)
5003 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5004 interface_options interface_opts;
5006 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
5008 if (global_capture_opts.ifaces->len > 2) {
5009 g_string_append_printf(str, ",");
5011 g_string_append_printf(str, " ");
5012 if (j == global_capture_opts.ifaces->len - 1) {
5013 g_string_append_printf(str, "and ");
5016 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
5019 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
5021 fprintf(stderr, "Capturing on %s\n", str->str);
5022 g_string_free(str, TRUE);
5025 /* Process the snapshot length, as that affects the generated BPF code. */
5026 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
5028 #ifdef HAVE_BPF_IMAGE
5029 if (print_bpf_code) {
5030 show_filter_code(&global_capture_opts);
5035 /* We're supposed to do a capture. Process the ring buffer arguments. */
5036 capture_opts_trim_ring_num_files(&global_capture_opts);
5038 /* flush stderr prior to starting the main capture loop */
5041 /* Now start the capture. */
5042 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
5046 /* capture failed */
5049 return 0; /* never here, make compiler happy */
5054 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
5055 const char *message, gpointer user_data _U_)
5062 /* ignore log message, if log_level isn't interesting */
5063 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5064 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
5069 /* create a "timestamp" */
5071 today = localtime(&curr);
5073 switch(log_level & G_LOG_LEVEL_MASK) {
5074 case G_LOG_LEVEL_ERROR:
5077 case G_LOG_LEVEL_CRITICAL:
5080 case G_LOG_LEVEL_WARNING:
5083 case G_LOG_LEVEL_MESSAGE:
5086 case G_LOG_LEVEL_INFO:
5089 case G_LOG_LEVEL_DEBUG:
5093 fprintf(stderr, "unknown log_level %d\n", log_level);
5095 g_assert_not_reached();
5098 /* Generate the output message */
5099 if (log_level & G_LOG_LEVEL_MESSAGE) {
5100 /* normal user messages without additional infos */
5101 msg = g_strdup_printf("%s\n", message);
5103 /* info/debug messages with additional infos */
5104 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
5105 today->tm_hour, today->tm_min, today->tm_sec,
5106 log_domain != NULL ? log_domain : "",
5110 /* DEBUG & INFO msgs (if we're debugging today) */
5111 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
5112 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5113 #ifdef DEBUG_DUMPCAP
5114 fprintf(stderr, "%s", msg);
5117 #ifdef DEBUG_CHILD_DUMPCAP
5118 fprintf(debug_log, "%s", msg);
5126 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
5127 /* to parent especially formatted if dumpcap running as child. */
5128 if (capture_child) {
5129 sync_pipe_errmsg_to_parent(2, msg, "");
5131 fprintf(stderr, "%s", msg);
5138 /****************************************************************************************************************/
5139 /* indication report routines */
5143 report_packet_count(unsigned int packet_count)
5145 char tmp[SP_DECISIZE+1+1];
5146 static unsigned int count = 0;
5148 if (capture_child) {
5149 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
5150 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
5151 pipe_write_block(2, SP_PACKET_COUNT, tmp);
5153 count += packet_count;
5154 fprintf(stderr, "\rPackets: %u ", count);
5155 /* stderr could be line buffered */
5161 report_new_capture_file(const char *filename)
5163 if (capture_child) {
5164 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
5165 pipe_write_block(2, SP_FILE, filename);
5169 * Prevent a SIGINFO handler from writing to the standard error
5170 * while we're doing so; instead, have it just set a flag telling
5171 * us to print that information when we're done.
5174 #endif /* SIGINFO */
5175 fprintf(stderr, "File: %s\n", filename);
5176 /* stderr could be line buffered */
5181 * Allow SIGINFO handlers to write.
5186 * If a SIGINFO handler asked us to write out capture counts, do so.
5189 report_counts_for_siginfo();
5190 #endif /* SIGINFO */
5195 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5197 interface_options interface_opts;
5198 char tmp[MSG_MAX_LENGTH+1+6];
5200 if (i < capture_opts->ifaces->len) {
5201 if (capture_child) {
5202 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5203 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5204 pipe_write_block(2, SP_BAD_FILTER, tmp);
5207 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5208 * the error message below.
5210 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
5212 "Invalid capture filter \"%s\" for interface '%s'.\n"
5214 "That string isn't a valid capture filter (%s).\n"
5215 "See the User's Guide for a description of the capture filter syntax.",
5216 interface_opts.cfilter, interface_opts.name, errmsg);
5222 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5224 if (capture_child) {
5225 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5226 "Primary Error: %s", error_msg);
5227 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5228 "Secondary Error: %s", secondary_error_msg);
5229 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5231 cmdarg_err("%s", error_msg);
5232 if (secondary_error_msg[0] != '\0')
5233 cmdarg_err_cont("%s", secondary_error_msg);
5238 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
5240 char tmp[SP_DECISIZE+1+1];
5241 guint32 total_drops = pcap_drops + drops + flushed;
5243 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5245 if (capture_child) {
5246 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5247 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5248 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
5249 /* XXX: Need to provide interface id, changes to consumers required. */
5250 pipe_write_block(2, SP_DROPS, tmp);
5253 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5254 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
5255 received ? 100.0 * received / (received + total_drops) : 0.0);
5256 /* stderr could be line buffered */
5262 /************************************************************************************************/
5263 /* signal_pipe handling */
5268 signal_pipe_check_running(void)
5270 /* any news from our parent? -> just stop the capture */
5274 /* if we are running standalone, no check required */
5275 if (!capture_child) {
5279 if (!sig_pipe_name || !sig_pipe_handle) {
5280 /* This shouldn't happen */
5281 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5282 "Signal pipe: No name or handle");
5287 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5288 * at this point. Should we check to see if the parent is still alive,
5289 * e.g. by using OpenProcess?
5292 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5294 if (!result || avail > 0) {
5295 /* peek failed or some bytes really available */
5296 /* (if not piping from stdin this would fail) */
5297 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5298 "Signal pipe: Stop capture: %s", sig_pipe_name);
5299 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5300 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
5301 sig_pipe_handle, result, avail);
5304 /* pipe ok and no bytes available */
5315 * Editor modelines - https://www.wireshark.org/tools/modelines.html
5320 * indent-tabs-mode: nil
5323 * vi: set shiftwidth=4 tabstop=8 expandtab:
5324 * :indentSize=4:tabSize=8:noTabs=true: