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() */
31 #ifdef HAVE_SYS_TYPES_H
32 # include <sys/types.h>
35 #ifdef HAVE_SYS_SOCKET_H
36 #include <sys/socket.h>
39 #ifdef HAVE_NETINET_IN_H
40 #include <netinet/in.h>
43 #ifdef HAVE_SYS_STAT_H
44 # include <sys/stat.h>
59 #ifdef HAVE_ARPA_INET_H
60 #include <arpa/inet.h>
63 #if defined(__APPLE__) && defined(__LP64__)
64 #include <sys/utsname.h>
71 #include <zlib.h> /* to get the libz version number */
74 #include <wsutil/cmdarg_err.h>
75 #include <wsutil/crash_info.h>
76 #include <wsutil/copyright_info.h>
77 #include <wsutil/ws_version_info.h>
80 #include "wsutil/wsgetopt.h"
88 # include <sys/prctl.h>
89 # include <sys/capability.h>
92 #include "ringbuffer.h"
93 #include "version_info.h"
95 #include "capture-pcap-util.h"
97 #include "capture-wpcap.h"
103 #include "capture-wpcap.h"
104 #include <wsutil/unicode-utils.h>
111 #ifdef NEED_INET_V6DEFS_H
112 # include "wsutil/inet_v6defs.h"
115 #include <wsutil/clopts_common.h>
116 #include <wsutil/privileges.h>
118 #include "sync_pipe.h"
120 #include "capture_opts.h"
121 #include <capchild/capture_session.h>
122 #include <capchild/capture_ifinfo.h>
123 #include <capchild/capture_sync.h>
125 #include "conditions.h"
126 #include "capture_stop_conditions.h"
128 #include "wsutil/tempfile.h"
130 #include "wsutil/file_util.h"
131 #include "wsutil/os_version_info.h"
133 #include "ws80211_utils.h"
136 * Get information about libpcap format from "wiretap/libpcap.h".
137 * XXX - can we just use pcap_open_offline() to read the pipe?
139 #include "wiretap/libpcap.h"
141 /**#define DEBUG_DUMPCAP**/
142 /**#define DEBUG_CHILD_DUMPCAP**/
146 #include <conio.h> /* _getch() */
150 #ifdef DEBUG_CHILD_DUMPCAP
151 FILE *debug_log; /* for logging debug messages to */
152 /* a file if DEBUG_CHILD_DUMPCAP */
156 static GAsyncQueue *pcap_queue;
157 static gint64 pcap_queue_bytes;
158 static gint64 pcap_queue_packets;
159 static gint64 pcap_queue_byte_limit = 0;
160 static gint64 pcap_queue_packet_limit = 0;
162 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
164 static gchar *sig_pipe_name = NULL;
165 static HANDLE sig_pipe_handle = NULL;
166 static gboolean signal_pipe_check_running(void);
170 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
171 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
174 /** Stop a low-level capture (stops the capture child). */
175 static void capture_loop_stop(void);
176 /** Close a pipe, or socket if \a from_socket is TRUE */
177 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
181 * Enable kernel BPF JIT compiler if available.
182 * If any calls fail, just drive on - the JIT compiler might not be
183 * enabled, but filtering will still work, and it's not clear what
184 * we could do if the calls fail; should we just report the error
185 * and not continue to capture, should we report it as a warning, or
189 enable_kernel_bpf_jit_compiler(void)
193 static const char file[] = "/proc/sys/net/core/bpf_jit_enable";
195 fd = open(file, O_WRONLY);
199 written = write(fd, "1", strlen("1"));
205 #if !defined (__linux__)
206 #ifndef HAVE_PCAP_BREAKLOOP
208 * We don't have pcap_breakloop(), which is the only way to ensure that
209 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
210 * won't, if the call to read the next packet or batch of packets is
211 * is interrupted by a signal on UN*X, just go back and try again to
214 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
215 * the signal handler, set a flag to stop capturing; however, without
216 * a guarantee of that sort, we can't guarantee that we'll stop capturing
217 * if the read will be retried and won't time out if no packets arrive.
219 * Therefore, on at least some platforms, we work around the lack of
220 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
221 * to wait for packets to arrive, so that we're probably going to be
222 * blocked in the select() when the signal arrives, and can just bail
223 * out of the loop at that point.
225 * However, we don't want to do that on BSD (because "select()" doesn't work
226 * correctly on BPF devices on at least some releases of some flavors of
227 * BSD), and we don't want to do it on Windows (because "select()" is
228 * something for sockets, not for arbitrary handles). (Note that "Windows"
229 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
230 * using WinPcap, not a UNIX libpcap.)
232 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
233 * on BSD times out even if no packets have arrived, so we'll eventually
234 * exit pcap_dispatch() with an indication that no packets have arrived,
235 * and will break out of the capture loop at that point.
237 * On Windows, we can't send a SIGINT to stop capturing, so none of this
238 * applies in any case.
240 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
241 * want to include it if it's not present on this platform, however.
243 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
244 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
246 # define MUST_DO_SELECT
247 # endif /* avoid select */
248 #endif /* HAVE_PCAP_BREAKLOOP */
250 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
251 * in pcap_dispatch(); on the other hand, select() works just fine there.
252 * Hence we use a select for that come what may.
254 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
255 * internally, and, with TPACKET_V3, once that's supported, it'll
256 * support timeouts, at least as I understand the way the code works.
258 #define MUST_DO_SELECT
261 /** init the capture filter */
264 INITFILTER_BAD_FILTER,
265 INITFILTER_OTHER_ERROR
266 } initfilter_status_t;
269 STATE_EXPECT_REC_HDR,
282 typedef struct _pcap_options {
287 #ifdef MUST_DO_SELECT
288 int pcap_fd; /**< pcap file descriptor */
295 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
296 /**< capture pipe (unix only "input file") */
297 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
298 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
299 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
300 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
302 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
304 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
305 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
306 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
308 char * cap_pipe_buf; /**< Pointer to the data buffer we read into */
309 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
310 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
312 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
313 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
315 cap_pipe_state_t cap_pipe_state;
316 cap_pipe_err_t cap_pipe_err;
319 GMutex *cap_pipe_read_mtx;
320 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
324 typedef struct _loop_data {
326 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
327 int err; /**< if non-zero, error seen while capturing */
328 gint packet_count; /**< Number of packets we have already captured */
329 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
330 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
332 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
338 guint64 bytes_written;
339 guint32 autostop_files;
342 typedef struct _pcap_queue_element {
343 pcap_options *pcap_opts;
344 struct pcap_pkthdr phdr;
346 } pcap_queue_element;
349 * Standard secondary message for unexpected errors.
351 static const char please_report[] =
352 "Please report this to the Wireshark developers.\n"
353 "http://bugs.wireshark.org/\n"
354 "(This is not a crash; please do not report it as such.)";
357 * This needs to be static, so that the SIGINT handler can clear the "go"
360 static loop_data global_ld;
364 * Timeout, in milliseconds, for reads from the stream of captured packets
365 * from a capture device.
367 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
368 * 64-bit applications, with sub-second timeouts not to work. The bug is
369 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
371 #if defined(__APPLE__) && defined(__LP64__)
372 static gboolean need_timeout_workaround;
374 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
376 #define CAP_READ_TIMEOUT 250
380 * Timeout, in microseconds, for reads from the stream of captured packets
381 * from a pipe. Pipes don't have the same problem that BPF devices do
382 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
383 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
384 * of the offending versions of Snow Leopard.
386 * On Windows this value is converted to milliseconds and passed to
387 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
388 * will return immediately.
391 #define PIPE_READ_TIMEOUT 100000
393 #define PIPE_READ_TIMEOUT 250000
396 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
399 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
400 const char *message, gpointer user_data _U_);
402 /* capture related options */
403 static capture_options global_capture_opts;
404 static gboolean quiet = FALSE;
405 static gboolean use_threads = FALSE;
406 static guint64 start_time;
408 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
410 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
412 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
413 int err, gboolean is_close);
415 static void WS_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
417 static void report_new_capture_file(const char *filename);
418 static void report_packet_count(unsigned int packet_count);
419 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
420 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
421 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
423 #define MSG_MAX_LENGTH 4096
425 /* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
427 create_timestamp(void) {
437 * Current time, represented as 100-nanosecond intervals since
438 * January 1, 1601, 00:00:00 UTC.
440 * I think DWORD might be signed, so cast both parts of "now"
441 * to guint32 so that the sign bit doesn't get treated specially.
443 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
444 * might want to use instead.
446 GetSystemTimeAsFileTime(&now);
447 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
448 (guint32)now.dwLowDateTime;
451 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
457 * Subtract difference, in microseconds, between January 1, 1601
458 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
460 timestamp -= G_GUINT64_CONSTANT(11644473600000000);
463 * Current time, represented as seconds and microseconds since
464 * January 1, 1970, 00:00:00 UTC.
466 gettimeofday(&now, NULL);
469 * Convert to delta in microseconds.
471 timestamp = (guint64)(now.tv_sec) * 1000000 +
472 (guint64)(now.tv_usec);
478 print_usage(FILE *output)
480 fprintf(output, "\nUsage: dumpcap [options] ...\n");
481 fprintf(output, "\n");
482 fprintf(output, "Capture interface:\n");
483 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
484 " or for remote capturing, use one of these formats:\n"
485 " rpcap://<host>/<interface>\n"
486 " TCP@<host>:<port>\n");
487 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
488 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
489 fprintf(output, " -p don't capture in promiscuous mode\n");
490 #ifdef HAVE_PCAP_CREATE
491 fprintf(output, " -I capture in monitor mode, if available\n");
493 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
494 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
496 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
497 fprintf(output, " -D print list of interfaces and exit\n");
498 fprintf(output, " -L print list of link-layer types of iface and exit\n");
499 #ifdef HAVE_BPF_IMAGE
500 fprintf(output, " -d print generated BPF code for capture filter\n");
502 fprintf(output, " -k set channel on wifi interface <freq>,[<type>]\n");
503 fprintf(output, " -S print statistics for each interface once per second\n");
504 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
505 fprintf(output, "\n");
506 #ifdef HAVE_PCAP_REMOTE
507 fprintf(output, "RPCAP options:\n");
508 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
509 fprintf(output, " -u use UDP for RPCAP data transfer\n");
510 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
511 #ifdef HAVE_PCAP_SETSAMPLING
512 fprintf(output, " -m <sampling type> use packet sampling\n");
513 fprintf(output, " count:NUM - capture one packet of every NUM\n");
514 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
517 fprintf(output, "Stop conditions:\n");
518 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
519 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
520 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
521 fprintf(output, " files:NUM - stop after NUM files\n");
522 /*fprintf(output, "\n");*/
523 fprintf(output, "Output (files):\n");
524 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
525 fprintf(output, " -g enable group read access on the output file(s)\n");
526 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
527 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
528 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
529 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
530 fprintf(output, " -P use libpcap format instead of pcapng\n");
531 fprintf(output, " --capture-comment <comment>\n");
532 fprintf(output, " add a capture comment to the output file\n");
533 fprintf(output, " (only for pcapng)\n");
534 fprintf(output, "\n");
535 fprintf(output, "Miscellaneous:\n");
536 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
537 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
538 fprintf(output, " within dumpcap\n");
539 fprintf(output, " -t use a separate thread per interface\n");
540 fprintf(output, " -q don't report packet capture counts\n");
541 fprintf(output, " -v print version information and exit\n");
542 fprintf(output, " -h display this help and exit\n");
543 fprintf(output, "\n");
545 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
546 fprintf(output, "You might want to reset it\n");
547 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
548 fprintf(output, "\n");
550 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
551 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
552 fprintf(output, "\n");
553 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
557 show_version(GString *comp_info_str, GString *runtime_info_str)
560 "Dumpcap (Wireshark) %s\n"
565 "See http://www.wireshark.org for more information.\n",
566 get_ws_vcs_version_info(), get_copyright_info(), comp_info_str->str, runtime_info_str->str);
570 * Report an error in command-line arguments.
571 * If we're a capture child, send a message back to the parent, otherwise
575 dumpcap_cmdarg_err(const char *fmt, va_list ap)
579 /* Generate a 'special format' message back to parent */
580 msg = g_strdup_vprintf(fmt, ap);
581 sync_pipe_errmsg_to_parent(2, msg, "");
584 fprintf(stderr, "dumpcap: ");
585 vfprintf(stderr, fmt, ap);
586 fprintf(stderr, "\n");
591 * Report additional information for an error in command-line arguments.
592 * If we're a capture child, send a message back to the parent, otherwise
596 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
600 msg = g_strdup_vprintf(fmt, ap);
601 sync_pipe_errmsg_to_parent(2, msg, "");
604 vfprintf(stderr, fmt, ap);
605 fprintf(stderr, "\n");
611 #if 0 /* Set to enable capability debugging */
612 /* see 'man cap_to_text()' for explanation of output */
613 /* '=' means 'all= ' ie: no capabilities */
614 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
616 print_caps(const char *pfx) {
617 cap_t caps = cap_get_proc();
618 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
619 "%s: EUID: %d Capabilities: %s", pfx,
620 geteuid(), cap_to_text(caps, NULL));
623 print_caps(const char *pfx _U_) {
628 relinquish_all_capabilities(void)
630 /* Drop any and all capabilities this process may have. */
631 /* Allowed whether or not process has any privileges. */
632 cap_t caps = cap_init(); /* all capabilities initialized to off */
633 print_caps("Pre-clear");
634 if (cap_set_proc(caps)) {
635 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
637 print_caps("Post-clear");
643 open_capture_device(interface_options *interface_opts,
644 char (*open_err_str)[PCAP_ERRBUF_SIZE])
647 #ifdef HAVE_PCAP_CREATE
650 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
651 struct pcap_rmtauth auth;
654 /* Open the network interface to capture from it.
655 Some versions of libpcap may put warnings into the error buffer
656 if they succeed; to tell if that's happened, we have to clear
657 the error buffer, and check if it's still a null string. */
658 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Entering open_capture_device().");
659 (*open_err_str)[0] = '\0';
660 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
662 * If we're opening a remote device, use pcap_open(); that's currently
663 * the only open routine that supports remote devices.
665 if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
666 auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
667 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
668 auth.username = interface_opts->auth_username;
669 auth.password = interface_opts->auth_password;
671 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
672 "Calling pcap_open() using name %s, snaplen %d, promisc_mode %d, datatx_udp %d, nocap_rpcap %d.",
673 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode,
674 interface_opts->datatx_udp, interface_opts->nocap_rpcap);
675 pcap_h = pcap_open(interface_opts->name, interface_opts->snaplen,
677 (interface_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
678 (interface_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
679 (interface_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
680 CAP_READ_TIMEOUT, &auth, *open_err_str);
681 if (pcap_h == NULL) {
682 /* Error - did pcap actually supply an error message? */
683 if ((*open_err_str)[0] == '\0') {
684 /* Work around known WinPcap bug wherein no error message is
685 filled in on a failure to open an rpcap: URL. */
686 g_strlcpy(*open_err_str,
687 "Unknown error (pcap bug; actual error cause not reported)",
688 sizeof *open_err_str);
691 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
692 "pcap_open() returned %p.", (void *)pcap_h);
697 * If we're not opening a remote device, use pcap_create() and
698 * pcap_activate() if we have them, so that we can set the buffer
699 * size, otherwise use pcap_open_live().
701 #ifdef HAVE_PCAP_CREATE
702 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
703 "Calling pcap_create() using %s.", interface_opts->name);
704 pcap_h = pcap_create(interface_opts->name, *open_err_str);
705 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
706 "pcap_create() returned %p.", (void *)pcap_h);
707 if (pcap_h != NULL) {
708 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
709 "Calling pcap_set_snaplen() with snaplen %d.", interface_opts->snaplen);
710 pcap_set_snaplen(pcap_h, interface_opts->snaplen);
711 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
712 "Calling pcap_set_promisc() with promisc_mode %d.", interface_opts->promisc_mode);
713 pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
714 pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
716 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
717 "buffersize %d.", interface_opts->buffer_size);
718 if (interface_opts->buffer_size != 0) {
719 pcap_set_buffer_size(pcap_h, interface_opts->buffer_size * 1024 * 1024);
721 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
722 "monitor_mode %d.", interface_opts->monitor_mode);
723 if (interface_opts->monitor_mode)
724 pcap_set_rfmon(pcap_h, 1);
725 err = pcap_activate(pcap_h);
726 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
727 "pcap_activate() returned %d.", err);
729 /* Failed to activate, set to NULL */
730 if (err == PCAP_ERROR)
731 g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
733 g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
739 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
740 "pcap_open_live() calling using name %s, snaplen %d, promisc_mode %d.",
741 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode);
742 pcap_h = pcap_open_live(interface_opts->name, interface_opts->snaplen,
743 interface_opts->promisc_mode, CAP_READ_TIMEOUT,
745 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
746 "pcap_open_live() returned %p.", (void *)pcap_h);
749 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_capture_device %s : %s", pcap_h ? "SUCCESS" : "FAILURE", interface_opts->name);
754 get_capture_device_open_failure_messages(const char *open_err_str,
756 char *errmsg, size_t errmsg_len,
757 char *secondary_errmsg,
758 size_t secondary_errmsg_len)
761 const char *libpcap_warn;
762 static const char ppamsg[] = "can't find PPA for ";
765 g_snprintf(errmsg, (gulong) errmsg_len,
766 "The capture session could not be initiated on interface '%s' (%s).",
767 iface, open_err_str);
770 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
772 "In order to capture packets, WinPcap must be installed; see\n"
774 " http://www.winpcap.org/\n"
778 " http://www.mirrors.wiretapped.net/security/packet-capture/winpcap/\n"
782 " http://winpcap.cs.pu.edu.tw/\n"
784 "for a downloadable version of WinPcap and for instructions on how to install\n"
787 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
789 "Please check that \"%s\" is the proper interface.\n"
792 "Help can be found at:\n"
794 " http://wiki.wireshark.org/WinPcap\n"
795 " http://wiki.wireshark.org/CaptureSetup\n",
799 /* If we got a "can't find PPA for X" message, warn the user (who
800 is running dumpcap on HP-UX) that they don't have a version of
801 libpcap that properly handles HP-UX (libpcap 0.6.x and later
802 versions, which properly handle HP-UX, say "can't find /dev/dlpi
803 PPA for X" rather than "can't find PPA for X"). */
804 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
807 "You are running (T)Wireshark with a version of the libpcap library\n"
808 "that doesn't handle HP-UX network devices well; this means that\n"
809 "(T)Wireshark may not be able to capture packets.\n"
811 "To fix this, you should install libpcap 0.6.2, or a later version\n"
812 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
813 "packaged binary form from the Software Porting And Archive Centre\n"
814 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
815 "at the URL lists a number of mirror sites.";
819 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
820 "Please check to make sure you have sufficient permissions, and that you have "
821 "the proper interface or pipe specified.%s", libpcap_warn);
825 /* Set the data link type on a pcap. */
827 set_pcap_linktype(pcap_t *pcap_h, int linktype, char *name,
828 char *errmsg, size_t errmsg_len,
829 char *secondary_errmsg, size_t secondary_errmsg_len)
831 char *set_linktype_err_str;
834 return TRUE; /* just use the default */
835 #ifdef HAVE_PCAP_SET_DATALINK
836 if (pcap_set_datalink(pcap_h, linktype) == 0)
837 return TRUE; /* no error */
838 set_linktype_err_str = pcap_geterr(pcap_h);
840 /* Let them set it to the type it is; reject any other request. */
841 if (get_pcap_linktype(pcap_h, name) == linktype)
842 return TRUE; /* no error */
843 set_linktype_err_str =
844 "That DLT isn't one of the DLTs supported by this device";
846 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type on interface '%s' (%s).",
847 name, set_linktype_err_str);
849 * If the error isn't "XXX is not one of the DLTs supported by this device",
850 * tell the user to tell the Wireshark developers about it.
852 if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
853 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
855 secondary_errmsg[0] = '\0';
860 compile_capture_filter(const char *iface, pcap_t *pcap_h,
861 struct bpf_program *fcode, const char *cfilter)
863 bpf_u_int32 netnum, netmask;
864 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
866 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
868 * Well, we can't get the netmask for this interface; it's used
869 * only for filters that check for broadcast IP addresses, so
870 * we just punt and use 0. It might be nice to warn the user,
871 * but that's a pain in a GUI application, as it'd involve popping
872 * up a message box, and it's not clear how often this would make
873 * a difference (only filters that check for IP broadcast addresses
877 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
882 * Sigh. Older versions of libpcap don't properly declare the
883 * third argument to pcap_compile() as a const pointer. Cast
886 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
891 #ifdef HAVE_BPF_IMAGE
893 show_filter_code(capture_options *capture_opts)
895 interface_options interface_opts;
897 gchar open_err_str[PCAP_ERRBUF_SIZE];
898 char errmsg[MSG_MAX_LENGTH+1];
899 char secondary_errmsg[MSG_MAX_LENGTH+1];
900 struct bpf_program fcode;
901 struct bpf_insn *insn;
905 for (j = 0; j < capture_opts->ifaces->len; j++) {
906 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
907 pcap_h = open_capture_device(&interface_opts, &open_err_str);
908 if (pcap_h == NULL) {
909 /* Open failed; get messages */
910 get_capture_device_open_failure_messages(open_err_str,
912 errmsg, sizeof errmsg,
914 sizeof secondary_errmsg);
915 /* And report them */
916 report_capture_error(errmsg, secondary_errmsg);
920 /* Set the link-layer type. */
921 if (!set_pcap_linktype(pcap_h, interface_opts.linktype, interface_opts.name,
922 errmsg, sizeof errmsg,
923 secondary_errmsg, sizeof secondary_errmsg)) {
925 report_capture_error(errmsg, secondary_errmsg);
929 /* OK, try to compile the capture filter. */
930 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
931 interface_opts.cfilter)) {
933 report_cfilter_error(capture_opts, j, errmsg);
938 /* Now print the filter code. */
939 insn = fcode.bf_insns;
941 for (i = 0; i < fcode.bf_len; insn++, i++)
942 printf("%s\n", bpf_image(insn, i));
944 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
945 /* to remove any suid privileges. */
946 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
947 /* (euid/egid have already previously been set to ruid/rgid. */
948 /* (See comment in main() for details) */
950 relinquish_special_privs_perm();
952 relinquish_all_capabilities();
955 /* Let our parent know we succeeded. */
956 pipe_write_block(2, SP_SUCCESS, NULL);
963 * capture_interface_list() is expected to do the right thing to get
964 * a list of interfaces.
966 * In most of the programs in the Wireshark suite, "the right thing"
967 * is to run dumpcap and ask it for the list, because dumpcap may
968 * be the only program in the suite with enough privileges to get
971 * In dumpcap itself, however, we obviously can't run dumpcap to
972 * ask for the list. Therefore, our capture_interface_list() should
973 * just call get_interface_list().
976 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
978 return get_interface_list(err, err_str);
982 * Get the data-link type for a libpcap device.
983 * This works around AIX 5.x's non-standard and incompatible-with-the-
984 * rest-of-the-universe libpcap.
987 get_pcap_linktype(pcap_t *pch, const char *devicename
995 const char *ifacename;
998 linktype = pcap_datalink(pch);
1002 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
1003 * rather than DLT_ values for link-layer types; the ifType values
1004 * for LAN devices are:
1011 * and the ifType value for a loopback device is 24.
1013 * The AIX names for LAN devices begin with:
1020 * and the AIX names for loopback devices begin with "lo".
1022 * (The difference between "Ethernet" and "802.3" is presumably
1023 * whether packets have an Ethernet header, with a packet type,
1024 * or an 802.3 header, with a packet length, followed by an 802.2
1025 * header and possibly a SNAP header.)
1027 * If the device name matches "linktype" interpreted as an ifType
1028 * value, rather than as a DLT_ value, we will assume this is AIX's
1029 * non-standard, incompatible libpcap, rather than a standard libpcap,
1030 * and will map the link-layer type to the standard DLT_ value for
1031 * that link-layer type, as that's what the rest of Wireshark expects.
1033 * (This means the capture files won't be readable by a tcpdump
1034 * linked with AIX's non-standard libpcap, but so it goes. They
1035 * *will* be readable by standard versions of tcpdump, Wireshark,
1038 * XXX - if we conclude we're using AIX libpcap, should we also
1039 * set a flag to cause us to assume the time stamps are in
1040 * seconds-and-nanoseconds form, and to convert them to
1041 * seconds-and-microseconds form before processing them and
1046 * Find the last component of the device name, which is the
1049 ifacename = strchr(devicename, '/');
1050 if (ifacename == NULL)
1051 ifacename = devicename;
1053 /* See if it matches any of the LAN device names. */
1054 if (strncmp(ifacename, "en", 2) == 0) {
1055 if (linktype == 6) {
1057 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
1061 } else if (strncmp(ifacename, "et", 2) == 0) {
1062 if (linktype == 7) {
1064 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
1065 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
1070 } else if (strncmp(ifacename, "tr", 2) == 0) {
1071 if (linktype == 9) {
1073 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
1074 * DLT_IEEE802, which is what's used for Token Ring.
1078 } else if (strncmp(ifacename, "fi", 2) == 0) {
1079 if (linktype == 15) {
1081 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
1085 } else if (strncmp(ifacename, "lo", 2) == 0) {
1086 if (linktype == 24) {
1088 * That's the RFC 1573 value for "software loopback" devices; map it
1089 * to DLT_NULL, which is what's used for loopback devices on BSD.
1099 static data_link_info_t *
1100 create_data_link_info(int dlt)
1102 data_link_info_t *data_link_info;
1105 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
1106 data_link_info->dlt = dlt;
1107 text = pcap_datalink_val_to_name(dlt);
1109 data_link_info->name = g_strdup(text);
1111 data_link_info->name = g_strdup_printf("DLT %d", dlt);
1112 text = pcap_datalink_val_to_description(dlt);
1114 data_link_info->description = g_strdup(text);
1116 data_link_info->description = NULL;
1117 return data_link_info;
1121 * Get the capabilities of a network device.
1123 static if_capabilities_t *
1124 get_if_capabilities(const char *devicename, gboolean monitor_mode
1125 #ifndef HAVE_PCAP_CREATE
1130 if_capabilities_t *caps;
1131 char errbuf[PCAP_ERRBUF_SIZE];
1133 #ifdef HAVE_PCAP_CREATE
1137 #ifdef HAVE_PCAP_LIST_DATALINKS
1141 data_link_info_t *data_link_info;
1144 * Allocate the interface capabilities structure.
1146 caps = (if_capabilities_t *)g_malloc(sizeof *caps);
1149 * WinPcap 4.1.2, and possibly earlier versions, have a bug
1150 * wherein, when an open with an rpcap: URL fails, the error
1151 * message for the error is not copied to errbuf and whatever
1152 * on-the-stack junk is in errbuf is treated as the error
1155 * To work around that (and any other bugs of that sort, we
1156 * initialize errbuf to an empty string. If we get an error
1157 * and the string is empty, we report it as an unknown error.
1158 * (If we *don't* get an error, and the string is *non*-empty,
1159 * that could be a warning returned, such as "can't turn
1160 * promiscuous mode on"; we currently don't do so.)
1163 #ifdef HAVE_PCAP_OPEN
1164 pch = pcap_open(devicename, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1165 caps->can_set_rfmon = FALSE;
1167 if (err_str != NULL)
1168 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1172 #elif defined(HAVE_PCAP_CREATE)
1173 pch = pcap_create(devicename, errbuf);
1175 if (err_str != NULL)
1176 *err_str = g_strdup(errbuf);
1180 status = pcap_can_set_rfmon(pch);
1183 if (status == PCAP_ERROR)
1184 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1187 *err_str = g_strdup(pcap_statustostr(status));
1193 caps->can_set_rfmon = FALSE;
1194 else if (status == 1) {
1195 caps->can_set_rfmon = TRUE;
1197 pcap_set_rfmon(pch, 1);
1199 if (err_str != NULL) {
1200 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1208 status = pcap_activate(pch);
1210 /* Error. We ignore warnings (status > 0). */
1211 if (err_str != NULL) {
1212 if (status == PCAP_ERROR)
1213 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1216 *err_str = g_strdup(pcap_statustostr(status));
1223 pch = pcap_open_live(devicename, MIN_PACKET_SIZE, 0, 0, errbuf);
1224 caps->can_set_rfmon = FALSE;
1226 if (err_str != NULL)
1227 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1232 deflt = get_pcap_linktype(pch, devicename);
1233 #ifdef HAVE_PCAP_LIST_DATALINKS
1234 nlt = pcap_list_datalinks(pch, &linktypes);
1235 if (nlt == 0 || linktypes == NULL) {
1237 if (err_str != NULL)
1238 *err_str = NULL; /* an empty list doesn't mean an error */
1242 caps->data_link_types = NULL;
1243 for (i = 0; i < nlt; i++) {
1244 data_link_info = create_data_link_info(linktypes[i]);
1247 * XXX - for 802.11, make the most detailed 802.11
1248 * version the default, rather than the one the
1249 * device has as the default?
1251 if (linktypes[i] == deflt)
1252 caps->data_link_types = g_list_prepend(caps->data_link_types,
1255 caps->data_link_types = g_list_append(caps->data_link_types,
1258 #ifdef HAVE_PCAP_FREE_DATALINKS
1259 pcap_free_datalinks(linktypes);
1262 * In Windows, there's no guarantee that if you have a library
1263 * built with one version of the MSVC++ run-time library, and
1264 * it returns a pointer to allocated data, you can free that
1265 * data from a program linked with another version of the
1266 * MSVC++ run-time library.
1268 * This is not an issue on UN*X.
1270 * See the mail threads starting at
1272 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1276 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1279 #define xx_free free /* hack so checkAPIs doesn't complain */
1282 #endif /* HAVE_PCAP_FREE_DATALINKS */
1283 #else /* HAVE_PCAP_LIST_DATALINKS */
1285 data_link_info = create_data_link_info(deflt);
1286 caps->data_link_types = g_list_append(caps->data_link_types,
1288 #endif /* HAVE_PCAP_LIST_DATALINKS */
1292 if (err_str != NULL)
1297 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1299 * Output a machine readable list of the interfaces
1300 * This list is retrieved by the sync_interface_list_open() function
1301 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
1304 print_machine_readable_interfaces(GList *if_list)
1311 char addr_str[ADDRSTRLEN];
1313 if (capture_child) {
1314 /* Let our parent know we succeeded. */
1315 pipe_write_block(2, SP_SUCCESS, NULL);
1318 i = 1; /* Interface id number */
1319 for (if_entry = g_list_first(if_list); if_entry != NULL;
1320 if_entry = g_list_next(if_entry)) {
1321 if_info = (if_info_t *)if_entry->data;
1322 printf("%d. %s\t", i++, if_info->name);
1325 * Print the contents of the if_entry struct in a parseable format.
1326 * Each if_entry element is tab-separated. Addresses are comma-
1329 /* XXX - Make sure our description doesn't contain a tab */
1330 if (if_info->vendor_description != NULL)
1331 printf("%s\t", if_info->vendor_description);
1335 /* XXX - Make sure our friendly name doesn't contain a tab */
1336 if (if_info->friendly_name != NULL)
1337 printf("%s\t", if_info->friendly_name);
1341 printf("%i\t", if_info->type);
1343 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1344 addr = g_slist_next(addr)) {
1345 if (addr != g_slist_nth(if_info->addrs, 0))
1348 if_addr = (if_addr_t *)addr->data;
1349 switch(if_addr->ifat_type) {
1351 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1353 printf("%s", addr_str);
1355 printf("<unknown IPv4>");
1359 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1360 addr_str, ADDRSTRLEN)) {
1361 printf("%s", addr_str);
1363 printf("<unknown IPv6>");
1367 printf("<type unknown %i>", if_addr->ifat_type);
1371 if (if_info->loopback)
1372 printf("\tloopback");
1374 printf("\tnetwork");
1381 * If you change the machine-readable output format of this function,
1382 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1385 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1388 data_link_info_t *data_link_info;
1389 const gchar *desc_str;
1391 if (capture_child) {
1392 /* Let our parent know we succeeded. */
1393 pipe_write_block(2, SP_SUCCESS, NULL);
1396 if (caps->can_set_rfmon)
1400 for (lt_entry = caps->data_link_types; lt_entry != NULL;
1401 lt_entry = g_list_next(lt_entry)) {
1402 data_link_info = (data_link_info_t *)lt_entry->data;
1403 if (data_link_info->description != NULL)
1404 desc_str = data_link_info->description;
1406 desc_str = "(not supported)";
1407 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1417 /* Print the number of packets captured for each interface until we're killed. */
1419 print_statistics_loop(gboolean machine_readable)
1421 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1427 char errbuf[PCAP_ERRBUF_SIZE];
1428 struct pcap_stat ps;
1430 if_list = get_interface_list(&err, &err_str);
1431 if (if_list == NULL) {
1433 case CANT_GET_INTERFACE_LIST:
1434 case DONT_HAVE_PCAP:
1435 cmdarg_err("%s", err_str);
1439 case NO_INTERFACES_FOUND:
1440 cmdarg_err("There are no interfaces on which a capture can be done");
1446 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1447 if_info = (if_info_t *)if_entry->data;
1448 #ifdef HAVE_PCAP_OPEN
1449 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1451 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1455 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1456 if_stat->name = g_strdup(if_info->name);
1458 stat_list = g_list_append(stat_list, if_stat);
1463 cmdarg_err("There are no interfaces on which a capture can be done");
1467 if (capture_child) {
1468 /* Let our parent know we succeeded. */
1469 pipe_write_block(2, SP_SUCCESS, NULL);
1472 if (!machine_readable) {
1473 printf("%-15s %10s %10s\n", "Interface", "Received",
1477 global_ld.go = TRUE;
1478 while (global_ld.go) {
1479 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1480 if_stat = (if_stat_t *)stat_entry->data;
1481 pcap_stats(if_stat->pch, &ps);
1483 if (!machine_readable) {
1484 printf("%-15s %10u %10u\n", if_stat->name,
1485 ps.ps_recv, ps.ps_drop);
1487 printf("%s\t%u\t%u\n", if_stat->name,
1488 ps.ps_recv, ps.ps_drop);
1493 /* If we have a dummy signal pipe check it */
1494 if (!signal_pipe_check_running()) {
1495 global_ld.go = FALSE;
1503 /* XXX - Not reached. Should we look for 'q' in stdin? */
1504 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1505 if_stat = (if_stat_t *)stat_entry->data;
1506 pcap_close(if_stat->pch);
1507 g_free(if_stat->name);
1510 g_list_free(stat_list);
1511 free_interface_list(if_list);
1519 capture_cleanup_handler(DWORD dwCtrlType)
1521 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1522 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1523 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1524 like SIGTERM at least when the machine's shutting down.
1526 For now, if we're running as a command rather than a capture child,
1527 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1528 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1529 in that way on UN*X.
1531 If we're not running as a capture child, we might be running as
1532 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1533 user logs out. (XXX - can we explicitly check whether we're
1534 running as a service?) */
1536 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1537 "Console: Control signal");
1538 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1539 "Console: Control signal, CtrlType: %u", dwCtrlType);
1541 /* Keep capture running if we're a service and a user logs off */
1542 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1543 capture_loop_stop();
1551 capture_cleanup_handler(int signum _U_)
1553 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1554 SIGTERM. We assume that if the user wanted it to keep running
1555 after they logged out, they'd have nohupped it. */
1557 /* Note: don't call g_log() in the signal handler: if we happened to be in
1558 * g_log() in process context when the signal came in, g_log will detect
1559 * the "recursion" and abort.
1562 capture_loop_stop();
1568 report_capture_count(gboolean reportit)
1570 /* Don't print this if we're a capture child. */
1571 if (!capture_child && reportit) {
1572 fprintf(stderr, "\rPackets captured: %u\n", global_ld.packet_count);
1573 /* stderr could be line buffered */
1581 report_counts_for_siginfo(void)
1583 report_capture_count(quiet);
1584 infoprint = FALSE; /* we just reported it */
1588 report_counts_siginfo(int signum _U_)
1590 int sav_errno = errno;
1592 /* If we've been told to delay printing, just set a flag asking
1593 that we print counts (if we're supposed to), otherwise print
1594 the count of packets captured (if we're supposed to). */
1598 report_counts_for_siginfo();
1601 #endif /* SIGINFO */
1604 exit_main(int status)
1607 /* Shutdown windows sockets */
1610 /* can be helpful for debugging */
1611 #ifdef DEBUG_DUMPCAP
1612 printf("Press any key\n");
1623 * If we were linked with libcap (not related to libpcap), make sure we have
1624 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1625 * (See comment in main() for details)
1628 relinquish_privs_except_capture(void)
1630 /* If 'started_with_special_privs' (ie: suid) then enable for
1631 * ourself the NET_ADMIN and NET_RAW capabilities and then
1632 * drop our suid privileges.
1634 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1635 * stuff we don't need (and shouldn't have).
1636 * CAP_NET_RAW: Packet capture (raw sockets).
1639 if (started_with_special_privs()) {
1640 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1641 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1643 cap_t caps = cap_init(); /* all capabilities initialized to off */
1645 print_caps("Pre drop, pre set");
1647 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1648 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1651 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1652 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1654 if (cap_set_proc(caps)) {
1655 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1657 print_caps("Pre drop, post set");
1659 relinquish_special_privs_perm();
1661 print_caps("Post drop, pre set");
1662 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1663 if (cap_set_proc(caps)) {
1664 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1666 print_caps("Post drop, post set");
1672 #endif /* HAVE_LIBCAP */
1674 /* Take care of byte order in the libpcap headers read from pipes.
1675 * (function taken from wiretap/libpcap.c) */
1677 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1680 /* Byte-swap the record header fields. */
1681 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1682 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1683 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1684 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1687 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1688 swapped, in order to match the BPF header layout.
1690 Unfortunately, some files were, according to a comment in the "libpcap"
1691 source, written with version 2.3 in their headers but without the
1692 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1693 would make no sense - we assume that we need to swap them. */
1694 if (hdr->version_major == 2 &&
1695 (hdr->version_minor < 3 ||
1696 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1699 temp = rechdr->orig_len;
1700 rechdr->orig_len = rechdr->incl_len;
1701 rechdr->incl_len = temp;
1705 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1709 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1713 return recv(pipe_fd, buf, (int)sz, 0);
1718 return ws_read(pipe_fd, buf, sz);
1724 * Thread function that reads from a pipe and pushes the data
1725 * to the main application thread.
1728 * XXX Right now we use async queues for basic signaling. The main thread
1729 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1730 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1731 * Iff the read is successful cap_pipe_read pushes an item onto
1732 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1733 * the queues themselves (yet).
1735 * We might want to move some of the cap_pipe_dispatch logic here so that
1736 * we can let cap_thread_read run independently, queuing up multiple reads
1737 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1739 static void *cap_thread_read(void *arg)
1741 pcap_options *pcap_opts;
1744 DWORD b, last_err, bytes_read;
1750 pcap_opts = (pcap_options *)arg;
1751 while (pcap_opts->cap_pipe_err == PIPOK) {
1752 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1753 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1755 while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1756 if ((pcap_opts->from_cap_socket)
1762 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1763 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1766 pcap_opts->cap_pipe_err = PIPEOF;
1770 pcap_opts->cap_pipe_err = PIPERR;
1781 /* If we try to use read() on a named pipe on Windows with partial
1782 * data it appears to return EOF.
1784 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1785 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1790 last_err = GetLastError();
1791 if (last_err == ERROR_MORE_DATA) {
1793 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1794 pcap_opts->cap_pipe_err = PIPEOF;
1798 pcap_opts->cap_pipe_err = PIPERR;
1801 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1802 pcap_opts->cap_pipe_err = PIPEOF;
1809 pcap_opts->cap_pipe_bytes_read = bytes_read;
1810 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1811 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1813 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1819 /* Provide select() functionality for a single file descriptor
1820 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1822 * Returns the same values as select.
1825 cap_pipe_select(int pipe_fd)
1828 struct timeval timeout;
1831 FD_SET(pipe_fd, &rfds);
1833 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1834 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1836 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1839 #define DEF_TCP_PORT 19000
1842 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1844 char *sockname = pipename + 4;
1845 struct sockaddr_in sa;
1852 memset(&sa, 0, sizeof(sa));
1854 p = strchr(sockname, ':');
1856 len = strlen(sockname);
1857 port = DEF_TCP_PORT;
1861 port = strtoul(p + 1, &p, 10);
1862 if (*p || port > 65535) {
1871 strncpy(buf, sockname, len);
1873 if (inet_pton(AF_INET, buf, &sa.sin_addr) <= 0) {
1877 sa.sin_family = AF_INET;
1878 sa.sin_port = htons((u_short)port);
1880 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1881 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1883 LPTSTR errorText = NULL;
1886 lastError = WSAGetLastError();
1887 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1888 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1889 FORMAT_MESSAGE_IGNORE_INSERTS,
1890 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1891 (LPTSTR)&errorText, 0, NULL);
1893 g_snprintf(errmsg, errmsgl,
1894 "The capture session could not be initiated due to the socket error: \n"
1896 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1898 LocalFree(errorText);
1900 " %d: %s", errno, strerror(errno));
1902 pcap_opts->cap_pipe_err = PIPERR;
1905 cap_pipe_close(fd, TRUE);
1909 pcap_opts->from_cap_socket = TRUE;
1913 g_snprintf(errmsg, errmsgl,
1914 "The capture session could not be initiated because\n"
1915 "\"%s\" is not a valid socket specification", pipename);
1916 pcap_opts->cap_pipe_err = PIPERR;
1920 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1924 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1928 closesocket(pipe_fd);
1935 /* Mimic pcap_open_live() for pipe captures
1937 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1938 * open it, and read the header.
1940 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1941 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1943 cap_pipe_open_live(char *pipename,
1944 pcap_options *pcap_opts,
1945 struct pcap_hdr *hdr,
1946 char *errmsg, int errmsgl)
1949 ws_statb64 pipe_stat;
1950 struct sockaddr_un sa;
1956 int fd = -1, sel_ret;
1960 pcap_opts->cap_pipe_fd = -1;
1962 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1964 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1967 * XXX - this blocks until a pcap per-file header has been written to
1968 * the pipe, so it could block indefinitely.
1970 if (strcmp(pipename, "-") == 0) {
1972 fd = 0; /* read from stdin */
1974 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1976 } else if (!strncmp(pipename, "TCP@", 4)) {
1977 if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
1982 if (ws_stat64(pipename, &pipe_stat) < 0) {
1983 if (errno == ENOENT || errno == ENOTDIR)
1984 pcap_opts->cap_pipe_err = PIPNEXIST;
1986 g_snprintf(errmsg, errmsgl,
1987 "The capture session could not be initiated "
1988 "due to error getting information on pipe/socket: %s", g_strerror(errno));
1989 pcap_opts->cap_pipe_err = PIPERR;
1993 if (S_ISFIFO(pipe_stat.st_mode)) {
1994 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1996 g_snprintf(errmsg, errmsgl,
1997 "The capture session could not be initiated "
1998 "due to error on pipe open: %s", g_strerror(errno));
1999 pcap_opts->cap_pipe_err = PIPERR;
2002 } else if (S_ISSOCK(pipe_stat.st_mode)) {
2003 fd = socket(AF_UNIX, SOCK_STREAM, 0);
2005 g_snprintf(errmsg, errmsgl,
2006 "The capture session could not be initiated "
2007 "due to error on socket create: %s", g_strerror(errno));
2008 pcap_opts->cap_pipe_err = PIPERR;
2011 sa.sun_family = AF_UNIX;
2013 * The Single UNIX Specification says:
2015 * The size of sun_path has intentionally been left undefined.
2016 * This is because different implementations use different sizes.
2017 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
2018 * of 104. Since most implementations originate from BSD versions,
2019 * the size is typically in the range 92 to 108.
2021 * Applications should not assume a particular length for sun_path
2022 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
2026 * The <sys/un.h> header shall define the sockaddr_un structure,
2027 * which shall include at least the following members:
2029 * sa_family_t sun_family Address family.
2030 * char sun_path[] Socket pathname.
2032 * so we assume that it's an array, with a specified size,
2033 * and that the size reflects the maximum path length.
2035 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
2036 /* Path name too long */
2037 g_snprintf(errmsg, errmsgl,
2038 "The capture session coud not be initiated "
2039 "due to error on socket connect: Path name too long");
2040 pcap_opts->cap_pipe_err = PIPERR;
2044 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
2046 g_snprintf(errmsg, errmsgl,
2047 "The capture session coud not be initiated "
2048 "due to error on socket connect: %s", g_strerror(errno));
2049 pcap_opts->cap_pipe_err = PIPERR;
2054 if (S_ISCHR(pipe_stat.st_mode)) {
2056 * Assume the user specified an interface on a system where
2057 * interfaces are in /dev. Pretend we haven't seen it.
2059 pcap_opts->cap_pipe_err = PIPNEXIST;
2061 g_snprintf(errmsg, errmsgl,
2062 "The capture session could not be initiated because\n"
2063 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
2064 pcap_opts->cap_pipe_err = PIPERR;
2069 #define PIPE_STR "\\pipe\\"
2070 /* Under Windows, named pipes _must_ have the form
2071 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
2073 pncopy = g_strdup(pipename);
2074 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
2075 pos = strchr(pncopy + 3, '\\');
2076 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
2083 g_snprintf(errmsg, errmsgl,
2084 "The capture session could not be initiated because\n"
2085 "\"%s\" is neither an interface nor a pipe", pipename);
2086 pcap_opts->cap_pipe_err = PIPNEXIST;
2090 /* Wait for the pipe to appear */
2092 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
2093 OPEN_EXISTING, 0, NULL);
2095 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
2098 if (GetLastError() != ERROR_PIPE_BUSY) {
2099 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2100 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2101 g_snprintf(errmsg, errmsgl,
2102 "The capture session on \"%s\" could not be started "
2103 "due to error on pipe open: %s (error %d)",
2104 pipename, utf_16to8(err_str), GetLastError());
2106 pcap_opts->cap_pipe_err = PIPERR;
2110 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
2111 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2112 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2113 g_snprintf(errmsg, errmsgl,
2114 "The capture session on \"%s\" timed out during "
2115 "pipe open: %s (error %d)",
2116 pipename, utf_16to8(err_str), GetLastError());
2118 pcap_opts->cap_pipe_err = PIPERR;
2125 pcap_opts->from_cap_pipe = TRUE;
2128 if (pcap_opts->from_cap_socket)
2131 /* read the pcap header */
2133 while (bytes_read < sizeof magic) {
2135 g_snprintf(errmsg, errmsgl, "Invalid file descriptor");
2139 sel_ret = cap_pipe_select(fd);
2141 g_snprintf(errmsg, errmsgl,
2142 "Unexpected error from select: %s", g_strerror(errno));
2144 } else if (sel_ret > 0) {
2145 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
2146 sizeof magic-bytes_read,
2147 pcap_opts->from_cap_socket);
2150 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2152 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2162 #if GLIB_CHECK_VERSION(2,31,0)
2163 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
2165 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
2168 pcap_opts->cap_pipe_buf = (char *) &magic;
2169 pcap_opts->cap_pipe_bytes_read = 0;
2170 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
2171 /* We don't have to worry about cap_pipe_read_mtx here */
2172 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2173 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2174 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2175 if (pcap_opts->cap_pipe_bytes_read == 0)
2176 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2178 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2187 case PCAP_NSEC_MAGIC:
2188 /* Host that wrote it has our byte order, and was running
2189 a program using either standard or ss990417 libpcap. */
2190 pcap_opts->cap_pipe_byte_swapped = FALSE;
2191 pcap_opts->cap_pipe_modified = FALSE;
2192 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
2194 case PCAP_MODIFIED_MAGIC:
2195 /* Host that wrote it has our byte order, but was running
2196 a program using either ss990915 or ss991029 libpcap. */
2197 pcap_opts->cap_pipe_byte_swapped = FALSE;
2198 pcap_opts->cap_pipe_modified = TRUE;
2200 case PCAP_SWAPPED_MAGIC:
2201 case PCAP_SWAPPED_NSEC_MAGIC:
2202 /* Host that wrote it has a byte order opposite to ours,
2203 and was running a program using either standard or
2204 ss990417 libpcap. */
2205 pcap_opts->cap_pipe_byte_swapped = TRUE;
2206 pcap_opts->cap_pipe_modified = FALSE;
2207 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2209 case PCAP_SWAPPED_MODIFIED_MAGIC:
2210 /* Host that wrote it out has a byte order opposite to
2211 ours, and was running a program using either ss990915
2212 or ss991029 libpcap. */
2213 pcap_opts->cap_pipe_byte_swapped = TRUE;
2214 pcap_opts->cap_pipe_modified = TRUE;
2217 /* Not a "libpcap" type we know about. */
2218 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2223 if (pcap_opts->from_cap_socket)
2226 /* Read the rest of the header */
2228 while (bytes_read < sizeof(struct pcap_hdr)) {
2229 sel_ret = cap_pipe_select(fd);
2231 g_snprintf(errmsg, errmsgl,
2232 "Unexpected error from select: %s", g_strerror(errno));
2234 } else if (sel_ret > 0) {
2235 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2236 sizeof(struct pcap_hdr) - bytes_read,
2237 pcap_opts->from_cap_socket);
2240 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2242 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
2252 pcap_opts->cap_pipe_buf = (char *) hdr;
2253 pcap_opts->cap_pipe_bytes_read = 0;
2254 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
2255 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2256 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2257 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2258 if (pcap_opts->cap_pipe_bytes_read == 0)
2259 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2261 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
2268 if (pcap_opts->cap_pipe_byte_swapped) {
2269 /* Byte-swap the header fields about which we care. */
2270 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
2271 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
2272 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
2273 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
2275 pcap_opts->linktype = hdr->network;
2277 if (hdr->version_major < 2) {
2278 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2282 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2283 pcap_opts->cap_pipe_err = PIPOK;
2284 pcap_opts->cap_pipe_fd = fd;
2288 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2289 pcap_opts->cap_pipe_err = PIPERR;
2290 cap_pipe_close(fd, pcap_opts->from_cap_socket);
2291 pcap_opts->cap_pipe_fd = -1;
2295 /* We read one record from the pipe, take care of byte order in the record
2296 * header, write the record to the capture file, and update capture statistics. */
2298 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2300 struct pcap_pkthdr phdr;
2301 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2304 #if !GLIB_CHECK_VERSION(2,31,18)
2312 #ifdef LOG_CAPTURE_VERBOSE
2313 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2316 switch (pcap_opts->cap_pipe_state) {
2318 case STATE_EXPECT_REC_HDR:
2320 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2323 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2324 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2325 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2326 pcap_opts->cap_pipe_bytes_read = 0;
2329 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2330 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2331 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2336 case STATE_READ_REC_HDR:
2338 if (pcap_opts->from_cap_socket)
2341 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2342 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
2345 result = PD_PIPE_EOF;
2347 result = PD_PIPE_ERR;
2350 pcap_opts->cap_pipe_bytes_read += b;
2354 #if GLIB_CHECK_VERSION(2,31,18)
2355 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2357 g_get_current_time(&wait_time);
2358 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2359 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2361 if (pcap_opts->cap_pipe_err == PIPEOF) {
2362 result = PD_PIPE_EOF;
2364 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2365 result = PD_PIPE_ERR;
2373 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2375 result = PD_REC_HDR_READ;
2378 case STATE_EXPECT_DATA:
2380 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2383 pcap_opts->cap_pipe_state = STATE_READ_DATA;
2384 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2385 pcap_opts->cap_pipe_bytes_read = 0;
2388 pcap_opts->cap_pipe_buf = (char *) data;
2389 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2390 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2395 case STATE_READ_DATA:
2397 if (pcap_opts->from_cap_socket)
2400 b = cap_pipe_read(pcap_opts->cap_pipe_fd,
2401 data+pcap_opts->cap_pipe_bytes_read,
2402 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
2403 pcap_opts->from_cap_socket);
2406 result = PD_PIPE_EOF;
2408 result = PD_PIPE_ERR;
2411 pcap_opts->cap_pipe_bytes_read += b;
2416 #if GLIB_CHECK_VERSION(2,31,18)
2417 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2419 g_get_current_time(&wait_time);
2420 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2421 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2422 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2423 if (pcap_opts->cap_pipe_err == PIPEOF) {
2424 result = PD_PIPE_EOF;
2426 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2427 result = PD_PIPE_ERR;
2435 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2437 result = PD_DATA_READ;
2441 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2444 } /* switch (pcap_opts->cap_pipe_state) */
2447 * We've now read as much data as we were expecting, so process it.
2451 case PD_REC_HDR_READ:
2452 /* We've read the header. Take care of byte order. */
2453 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2454 &pcap_opts->cap_pipe_rechdr.hdr);
2455 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2456 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2457 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2461 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2462 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2465 /* no data to read? fall through */
2468 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2469 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2470 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2471 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2472 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2475 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2477 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2479 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2483 pcap_opts->cap_pipe_err = PIPEOF;
2488 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2489 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2490 g_snprintf(errmsg, errmsgl,
2491 "Error reading from pipe: %s (error %d)",
2492 utf_16to8(err_str), GetLastError());
2495 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2503 pcap_opts->cap_pipe_err = PIPERR;
2504 /* Return here rather than inside the switch to prevent GCC warning */
2509 /** Open the capture input file (pcap or capture pipe).
2510 * Returns TRUE if it succeeds, FALSE otherwise. */
2512 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2513 char *errmsg, size_t errmsg_len,
2514 char *secondary_errmsg, size_t secondary_errmsg_len)
2516 gchar open_err_str[PCAP_ERRBUF_SIZE];
2517 gchar *sync_msg_str;
2518 interface_options interface_opts;
2519 pcap_options *pcap_opts;
2523 gchar *sync_secondary_msg_str;
2524 WORD wVersionRequested;
2528 /* XXX - opening Winsock on tshark? */
2530 /* Initialize Windows Socket if we are in a WIN32 OS
2531 This needs to be done before querying the interface for network/netmask */
2533 /* XXX - do we really require 1.1 or earlier?
2534 Are there any versions that support only 2.0 or higher? */
2535 wVersionRequested = MAKEWORD(1, 1);
2536 err = WSAStartup(wVersionRequested, &wsaData);
2540 case WSASYSNOTREADY:
2541 g_snprintf(errmsg, (gulong) errmsg_len,
2542 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2545 case WSAVERNOTSUPPORTED:
2546 g_snprintf(errmsg, (gulong) errmsg_len,
2547 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2548 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2551 case WSAEINPROGRESS:
2552 g_snprintf(errmsg, (gulong) errmsg_len,
2553 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2557 g_snprintf(errmsg, (gulong) errmsg_len,
2558 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2562 g_snprintf(errmsg, (gulong) errmsg_len,
2563 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2567 g_snprintf(errmsg, (gulong) errmsg_len,
2568 "Couldn't initialize Windows Sockets: error %d", err);
2571 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2575 if ((use_threads == FALSE) &&
2576 (capture_opts->ifaces->len > 1)) {
2577 g_snprintf(errmsg, (gulong) errmsg_len,
2578 "Using threads is required for capturing on multiple interfaces!");
2582 for (i = 0; i < capture_opts->ifaces->len; i++) {
2583 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2584 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2585 if (pcap_opts == NULL) {
2586 g_snprintf(errmsg, (gulong) errmsg_len,
2587 "Could not allocate memory.");
2590 pcap_opts->received = 0;
2591 pcap_opts->dropped = 0;
2592 pcap_opts->flushed = 0;
2593 pcap_opts->pcap_h = NULL;
2594 #ifdef MUST_DO_SELECT
2595 pcap_opts->pcap_fd = -1;
2597 pcap_opts->pcap_err = FALSE;
2598 pcap_opts->interface_id = i;
2599 pcap_opts->tid = NULL;
2600 pcap_opts->snaplen = 0;
2601 pcap_opts->linktype = -1;
2602 pcap_opts->ts_nsec = FALSE;
2603 pcap_opts->from_cap_pipe = FALSE;
2604 pcap_opts->from_cap_socket = FALSE;
2605 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2606 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2608 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2610 pcap_opts->cap_pipe_fd = -1;
2611 pcap_opts->cap_pipe_modified = FALSE;
2612 pcap_opts->cap_pipe_byte_swapped = FALSE;
2614 pcap_opts->cap_pipe_buf = NULL;
2616 pcap_opts->cap_pipe_bytes_to_read = 0;
2617 pcap_opts->cap_pipe_bytes_read = 0;
2618 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2619 pcap_opts->cap_pipe_err = PIPOK;
2621 #if GLIB_CHECK_VERSION(2,31,0)
2622 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2623 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2625 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2627 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2628 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2630 g_array_append_val(ld->pcaps, pcap_opts);
2632 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2633 pcap_opts->pcap_h = open_capture_device(&interface_opts, &open_err_str);
2635 if (pcap_opts->pcap_h != NULL) {
2636 /* we've opened "iface" as a network device */
2638 /* try to set the capture buffer size */
2639 if (interface_opts.buffer_size > 1 &&
2640 pcap_setbuff(pcap_opts->pcap_h, interface_opts.buffer_size * 1024 * 1024) != 0) {
2641 sync_secondary_msg_str = g_strdup_printf(
2642 "The capture buffer size of %d MiB seems to be too high for your machine,\n"
2643 "the default of %d MiB will be used.\n"
2645 "Nonetheless, the capture is started.\n",
2646 interface_opts.buffer_size, DEFAULT_CAPTURE_BUFFER_SIZE);
2647 report_capture_error("Couldn't set the capture buffer size!",
2648 sync_secondary_msg_str);
2649 g_free(sync_secondary_msg_str);
2653 #if defined(HAVE_PCAP_SETSAMPLING)
2654 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2655 struct pcap_samp *samp;
2657 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2658 switch (interface_opts.sampling_method) {
2659 case CAPTURE_SAMP_BY_COUNT:
2660 samp->method = PCAP_SAMP_1_EVERY_N;
2663 case CAPTURE_SAMP_BY_TIMER:
2664 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2668 sync_msg_str = g_strdup_printf(
2669 "Unknown sampling method %d specified,\n"
2670 "continue without packet sampling",
2671 interface_opts.sampling_method);
2672 report_capture_error("Couldn't set the capture "
2673 "sampling", sync_msg_str);
2674 g_free(sync_msg_str);
2676 samp->value = interface_opts.sampling_param;
2678 report_capture_error("Couldn't set the capture sampling",
2679 "Cannot get packet sampling data structure");
2684 /* setting the data link type only works on real interfaces */
2685 if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2687 secondary_errmsg, secondary_errmsg_len)) {
2690 pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2692 /* We couldn't open "iface" as a network device. */
2693 /* Try to open it as a pipe */
2694 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2697 if (pcap_opts->cap_pipe_fd == -1) {
2699 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2701 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2702 /* Pipe doesn't exist, so output message for interface */
2703 get_capture_device_open_failure_messages(open_err_str,
2704 interface_opts.name,
2708 secondary_errmsg_len);
2711 * Else pipe (or file) does exist and cap_pipe_open_live() has
2716 /* cap_pipe_open_live() succeeded; don't want
2717 error message from pcap_open_live() */
2718 open_err_str[0] = '\0';
2722 /* XXX - will this work for tshark? */
2723 #ifdef MUST_DO_SELECT
2724 if (!pcap_opts->from_cap_pipe) {
2725 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2726 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2728 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2733 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2734 returned a warning; print it, but keep capturing. */
2735 if (open_err_str[0] != '\0') {
2736 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2737 report_capture_error(sync_msg_str, "");
2738 g_free(sync_msg_str);
2740 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2741 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2744 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2745 /* to remove any suid privileges. */
2746 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2747 /* (euid/egid have already previously been set to ruid/rgid. */
2748 /* (See comment in main() for details) */
2750 relinquish_special_privs_perm();
2752 relinquish_all_capabilities();
2757 /* close the capture input file (pcap or capture pipe) */
2758 static void capture_loop_close_input(loop_data *ld)
2761 pcap_options *pcap_opts;
2763 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2765 for (i = 0; i < ld->pcaps->len; i++) {
2766 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2767 /* if open, close the capture pipe "input file" */
2768 if (pcap_opts->cap_pipe_fd >= 0) {
2769 g_assert(pcap_opts->from_cap_pipe);
2770 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2771 pcap_opts->cap_pipe_fd = -1;
2774 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2775 CloseHandle(pcap_opts->cap_pipe_h);
2776 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2779 /* if open, close the pcap "input file" */
2780 if (pcap_opts->pcap_h != NULL) {
2781 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2782 pcap_close(pcap_opts->pcap_h);
2783 pcap_opts->pcap_h = NULL;
2790 /* Shut down windows sockets */
2796 /* init the capture filter */
2797 static initfilter_status_t
2798 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2799 const gchar * name, const gchar * cfilter)
2801 struct bpf_program fcode;
2803 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2805 /* capture filters only work on real interfaces */
2806 if (cfilter && !from_cap_pipe) {
2807 /* A capture filter was specified; set it up. */
2808 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2809 /* Treat this specially - our caller might try to compile this
2810 as a display filter and, if that succeeds, warn the user that
2811 the display and capture filter syntaxes are different. */
2812 return INITFILTER_BAD_FILTER;
2814 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2815 #ifdef HAVE_PCAP_FREECODE
2816 pcap_freecode(&fcode);
2818 return INITFILTER_OTHER_ERROR;
2820 #ifdef HAVE_PCAP_FREECODE
2821 pcap_freecode(&fcode);
2825 return INITFILTER_NO_ERROR;
2829 /* set up to write to the already-opened capture output file/files */
2831 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2835 pcap_options *pcap_opts;
2836 interface_options interface_opts;
2837 gboolean successful;
2839 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2841 if ((capture_opts->use_pcapng == FALSE) &&
2842 (capture_opts->ifaces->len > 1)) {
2843 g_snprintf(errmsg, errmsg_len,
2844 "Using PCAPNG is required for capturing on multiple interfaces! Use the -n option.");
2848 /* Set up to write to the capture file. */
2849 if (capture_opts->multi_files_on) {
2850 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2852 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2853 if (ld->pdh == NULL) {
2858 if (capture_opts->use_pcapng) {
2860 GString *os_info_str;
2862 os_info_str = g_string_new("");
2863 get_os_version_info(os_info_str);
2865 g_snprintf(appname, sizeof(appname), "Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2866 successful = pcapng_write_session_header_block(ld->pdh,
2867 (const char *)capture_opts->capture_comment, /* Comment*/
2869 os_info_str->str, /* OS*/
2871 -1, /* section_length */
2875 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2876 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2877 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2878 if (pcap_opts->from_cap_pipe) {
2879 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2881 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2883 successful = pcapng_write_interface_description_block(global_ld.pdh,
2884 NULL, /* OPT_COMMENT 1 */
2885 interface_opts.name, /* IDB_NAME 2 */
2886 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2887 interface_opts.cfilter, /* IDB_FILTER 11 */
2888 os_info_str->str, /* IDB_OS 12 */
2889 pcap_opts->linktype,
2891 &(global_ld.bytes_written),
2892 0, /* IDB_IF_SPEED 8 */
2893 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2897 g_string_free(os_info_str, TRUE);
2900 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2901 if (pcap_opts->from_cap_pipe) {
2902 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2904 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2906 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2907 pcap_opts->ts_nsec, &ld->bytes_written, &err);
2915 if (ld->pdh == NULL) {
2916 /* We couldn't set up to write to the capture file. */
2917 /* XXX - use cf_open_error_message from tshark instead? */
2922 g_snprintf(errmsg, errmsg_len,
2923 "The file to which the capture would be"
2924 " saved (\"%s\") could not be opened: Error %d.",
2925 capture_opts->save_file, err);
2927 g_snprintf(errmsg, errmsg_len,
2928 "The file to which the capture would be"
2929 " saved (\"%s\") could not be opened: %s.",
2930 capture_opts->save_file, g_strerror(err));
2942 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2946 pcap_options *pcap_opts;
2947 guint64 end_time = create_timestamp();
2949 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2951 if (capture_opts->multi_files_on) {
2952 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2954 if (capture_opts->use_pcapng) {
2955 for (i = 0; i < global_ld.pcaps->len; i++) {
2956 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2957 if (!pcap_opts->from_cap_pipe) {
2958 guint64 isb_ifrecv, isb_ifdrop;
2959 struct pcap_stat stats;
2961 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
2962 isb_ifrecv = pcap_opts->received;
2963 isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
2965 isb_ifrecv = G_MAXUINT64;
2966 isb_ifdrop = G_MAXUINT64;
2968 pcapng_write_interface_statistics_block(ld->pdh,
2971 "Counters provided by dumpcap",
2980 if (fclose(ld->pdh) == EOF) {
2981 if (err_close != NULL) {
2991 /* dispatch incoming packets (pcap or capture pipe)
2993 * Waits for incoming packets to be available, and calls pcap_dispatch()
2994 * to cause them to be processed.
2996 * Returns the number of packets which were processed.
2998 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2999 * packet-batching behaviour does not cause packets to get held back
3003 capture_loop_dispatch(loop_data *ld,
3004 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
3007 gint packet_count_before;
3008 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
3013 packet_count_before = ld->packet_count;
3014 if (pcap_opts->from_cap_pipe) {
3015 /* dispatch from capture pipe */
3016 #ifdef LOG_CAPTURE_VERBOSE
3017 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3020 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
3022 if (sel_ret < 0 && errno != EINTR) {
3023 g_snprintf(errmsg, errmsg_len,
3024 "Unexpected error from select: %s", g_strerror(errno));
3025 report_capture_error(errmsg, please_report);
3030 * "select()" says we can read from the pipe without blocking
3033 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
3043 /* dispatch from pcap */
3044 #ifdef MUST_DO_SELECT
3046 * If we have "pcap_get_selectable_fd()", we use it to get the
3047 * descriptor on which to select; if that's -1, it means there
3048 * is no descriptor on which you can do a "select()" (perhaps
3049 * because you're capturing on a special device, and that device's
3050 * driver unfortunately doesn't support "select()", in which case
3051 * we don't do the select - which means it might not be possible
3052 * to stop a capture until a packet arrives. If that's unacceptable,
3053 * plead with whoever supplies the software for that device to add
3054 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3055 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3056 * later, so it can use pcap_breakloop().
3058 #ifdef LOG_CAPTURE_VERBOSE
3059 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3061 if (pcap_opts->pcap_fd != -1) {
3062 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
3065 * "select()" says we can read from it without blocking; go for
3068 * We don't have pcap_breakloop(), so we only process one packet
3069 * per pcap_dispatch() call, to allow a signal to stop the
3070 * processing immediately, rather than processing all packets
3071 * in a batch before quitting.
3074 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3076 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3080 /* Error, rather than pcap_breakloop(). */
3081 pcap_opts->pcap_err = TRUE;
3083 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3086 if (sel_ret < 0 && errno != EINTR) {
3087 g_snprintf(errmsg, errmsg_len,
3088 "Unexpected error from select: %s", g_strerror(errno));
3089 report_capture_error(errmsg, please_report);
3095 #endif /* MUST_DO_SELECT */
3097 /* dispatch from pcap without select */
3099 #ifdef LOG_CAPTURE_VERBOSE
3100 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3104 * On Windows, we don't support asynchronously telling a process to
3105 * stop capturing; instead, we check for an indication on a pipe
3106 * after processing packets. We therefore process only one packet
3107 * at a time, so that we can check the pipe after every packet.
3110 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3112 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3116 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3118 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3123 /* Error, rather than pcap_breakloop(). */
3124 pcap_opts->pcap_err = TRUE;
3126 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3128 #else /* pcap_next_ex */
3129 #ifdef LOG_CAPTURE_VERBOSE
3130 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3132 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3135 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3136 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
3137 * This should be fixed in the WinPcap 4.0 alpha release.
3139 * For reference, an example remote interface:
3140 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3143 /* emulate dispatch from pcap */
3146 struct pcap_pkthdr *pkt_header;
3151 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
3153 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3155 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3160 pcap_opts->pcap_err = TRUE;
3164 #endif /* pcap_next_ex */
3168 #ifdef LOG_CAPTURE_VERBOSE
3169 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3172 return ld->packet_count - packet_count_before;
3176 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3177 * want to grab only the characters between the '{' and '}' delimiters.
3179 * Returns a GString that must be freed with g_string_free(). */
3181 isolate_uuid(const char *iface)
3186 ptr = strchr(iface, '{');
3188 return g_string_new(iface);
3189 gstr = g_string_new(ptr + 1);
3191 ptr = strchr(gstr->str, '}');
3195 gstr = g_string_truncate(gstr, ptr - gstr->str);
3200 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3201 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3203 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3204 char *errmsg, int errmsg_len)
3207 gchar *capfile_name;
3209 gboolean is_tempfile;
3211 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3212 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3214 if (capture_opts->save_file != NULL) {
3215 /* We return to the caller while the capture is in progress.
3216 * Therefore we need to take a copy of save_file in
3217 * case the caller destroys it after we return.
3219 capfile_name = g_strdup(capture_opts->save_file);
3221 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3222 if (capture_opts->multi_files_on) {
3223 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3224 g_snprintf(errmsg, errmsg_len,
3225 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3226 g_free(capfile_name);
3229 if (strcmp(capfile_name, "-") == 0) {
3230 /* write to stdout */
3233 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3234 _setmode(1, O_BINARY);
3237 } /* if (...output_to_pipe ... */
3240 if (capture_opts->multi_files_on) {
3241 /* ringbuffer is enabled */
3242 *save_file_fd = ringbuf_init(capfile_name,
3243 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3244 capture_opts->group_read_access);
3246 /* we need the ringbuf name */
3247 if (*save_file_fd != -1) {
3248 g_free(capfile_name);
3249 capfile_name = g_strdup(ringbuf_current_filename());
3252 /* Try to open/create the specified file for use as a capture buffer. */
3253 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
3254 (capture_opts->group_read_access) ? 0640 : 0600);
3257 is_tempfile = FALSE;
3259 /* Choose a random name for the temporary capture buffer */
3260 if (global_capture_opts.ifaces->len > 1) {
3261 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3264 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
3266 /* use the generic portion of the interface guid to form the basis of the filename */
3267 if (strncmp("NPF_{", basename, 5)==0)
3269 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3271 iface = isolate_uuid(basename);
3273 basename = g_strdup(iface->str);
3274 g_string_free(iface, TRUE);
3277 /* generate the temp file name prefix...
3278 * It would be nice if we could specify a pcapng/pcap filename suffix,
3279 * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
3280 if (capture_opts->use_pcapng) {
3281 prefix = g_strconcat("wireshark_pcapng_", basename, NULL);
3283 prefix = g_strconcat("wireshark_pcap_", basename, NULL);
3287 *save_file_fd = create_tempfile(&tmpname, prefix);
3289 capfile_name = g_strdup(tmpname);
3293 /* did we fail to open the output file? */
3294 if (*save_file_fd == -1) {
3296 g_snprintf(errmsg, errmsg_len,
3297 "The temporary file to which the capture would be saved (\"%s\") "
3298 "could not be opened: %s.", capfile_name, g_strerror(errno));
3300 if (capture_opts->multi_files_on) {
3301 ringbuf_error_cleanup();
3304 g_snprintf(errmsg, errmsg_len,
3305 "The file to which the capture would be saved (\"%s\") "
3306 "could not be opened: %s.", capfile_name,
3309 g_free(capfile_name);
3313 if (capture_opts->save_file != NULL) {
3314 g_free(capture_opts->save_file);
3316 capture_opts->save_file = capfile_name;
3317 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3318 "g_free(capfile_name)". */
3324 /* Do the work of handling either the file size or file duration capture
3325 conditions being reached, and switching files or stopping. */
3327 do_file_switch_or_stop(capture_options *capture_opts,
3328 condition *cnd_autostop_files,
3329 condition *cnd_autostop_size,
3330 condition *cnd_file_duration)
3333 pcap_options *pcap_opts;
3334 interface_options interface_opts;
3335 gboolean successful;
3337 if (capture_opts->multi_files_on) {
3338 if (cnd_autostop_files != NULL &&
3339 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
3340 /* no files left: stop here */
3341 global_ld.go = FALSE;
3345 /* Switch to the next ringbuffer file */
3346 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3347 &global_ld.save_file_fd, &global_ld.err)) {
3349 /* File switch succeeded: reset the conditions */
3350 global_ld.bytes_written = 0;
3351 if (capture_opts->use_pcapng) {
3353 GString *os_info_str;
3355 os_info_str = g_string_new("");
3356 get_os_version_info(os_info_str);
3358 g_snprintf(appname, sizeof(appname), "Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
3359 successful = pcapng_write_session_header_block(global_ld.pdh,
3362 os_info_str->str, /* OS */
3364 -1, /* section_length */
3365 &(global_ld.bytes_written),
3368 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3369 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3370 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3371 successful = pcapng_write_interface_description_block(global_ld.pdh,
3372 NULL, /* OPT_COMMENT 1 */
3373 interface_opts.name, /* IDB_NAME 2 */
3374 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3375 interface_opts.cfilter, /* IDB_FILTER 11 */
3376 os_info_str->str, /* IDB_OS 12 */
3377 pcap_opts->linktype,
3379 &(global_ld.bytes_written),
3380 0, /* IDB_IF_SPEED 8 */
3381 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3385 g_string_free(os_info_str, TRUE);
3388 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3389 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3390 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3393 fclose(global_ld.pdh);
3394 global_ld.pdh = NULL;
3395 global_ld.go = FALSE;
3398 if (cnd_autostop_size)
3399 cnd_reset(cnd_autostop_size);
3400 if (cnd_file_duration)
3401 cnd_reset(cnd_file_duration);
3402 fflush(global_ld.pdh);
3404 report_packet_count(global_ld.inpkts_to_sync_pipe);
3405 global_ld.inpkts_to_sync_pipe = 0;
3406 report_new_capture_file(capture_opts->save_file);
3408 /* File switch failed: stop here */
3409 global_ld.go = FALSE;
3413 /* single file, stop now */
3414 global_ld.go = FALSE;
3421 pcap_read_handler(void* arg)
3423 pcap_options *pcap_opts;
3424 char errmsg[MSG_MAX_LENGTH+1];
3426 pcap_opts = (pcap_options *)arg;
3428 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3429 pcap_opts->interface_id);
3431 while (global_ld.go) {
3432 /* dispatch incoming packets */
3433 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3435 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3436 pcap_opts->interface_id);
3437 g_thread_exit(NULL);
3441 /* Do the low-level work of a capture.
3442 Returns TRUE if it succeeds, FALSE otherwise. */
3444 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3447 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3449 struct timeval upd_time, cur_time;
3453 condition *cnd_file_duration = NULL;
3454 condition *cnd_autostop_files = NULL;
3455 condition *cnd_autostop_size = NULL;
3456 condition *cnd_autostop_duration = NULL;
3459 gboolean cfilter_error = FALSE;
3460 char errmsg[MSG_MAX_LENGTH+1];
3461 char secondary_errmsg[MSG_MAX_LENGTH+1];
3462 pcap_options *pcap_opts;
3463 interface_options interface_opts;
3464 guint i, error_index = 0;
3467 *secondary_errmsg = '\0';
3469 /* init the loop data */
3470 global_ld.go = TRUE;
3471 global_ld.packet_count = 0;
3473 global_ld.report_packet_count = FALSE;
3475 if (capture_opts->has_autostop_packets)
3476 global_ld.packet_max = capture_opts->autostop_packets;
3478 global_ld.packet_max = 0; /* no limit */
3479 global_ld.inpkts_to_sync_pipe = 0;
3480 global_ld.err = 0; /* no error seen yet */
3481 global_ld.pdh = NULL;
3482 global_ld.autostop_files = 0;
3483 global_ld.save_file_fd = -1;
3485 /* We haven't yet gotten the capture statistics. */
3486 *stats_known = FALSE;
3488 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3489 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3491 /* open the "input file" from network interface or capture pipe */
3492 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3493 secondary_errmsg, sizeof(secondary_errmsg))) {
3496 for (i = 0; i < capture_opts->ifaces->len; i++) {
3497 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3498 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3499 /* init the input filter from the network interface (capture pipe will do nothing) */
3501 * When remote capturing WinPCap crashes when the capture filter
3502 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3505 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3506 interface_opts.name,
3507 interface_opts.cfilter?interface_opts.cfilter:"")) {
3509 case INITFILTER_NO_ERROR:
3512 case INITFILTER_BAD_FILTER:
3513 cfilter_error = TRUE;
3515 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3518 case INITFILTER_OTHER_ERROR:
3519 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3520 pcap_geterr(pcap_opts->pcap_h));
3521 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3526 /* If we're supposed to write to a capture file, open it for output
3527 (temporary/specified name/ringbuffer) */
3528 if (capture_opts->saving_to_file) {
3529 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3530 errmsg, sizeof(errmsg))) {
3534 /* set up to write to the already-opened capture output file/files */
3535 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3540 /* XXX - capture SIGTERM and close the capture, in case we're on a
3541 Linux 2.0[.x] system and you have to explicitly close the capture
3542 stream in order to turn promiscuous mode off? We need to do that
3543 in other places as well - and I don't think that works all the
3544 time in any case, due to libpcap bugs. */
3546 /* Well, we should be able to start capturing.
3548 Sync out the capture file, so the header makes it to the file system,
3549 and send a "capture started successfully and capture file created"
3550 message to our parent so that they'll open the capture file and
3551 update its windows to indicate that we have a live capture in
3553 fflush(global_ld.pdh);
3554 report_new_capture_file(capture_opts->save_file);
3557 /* initialize capture stop (and alike) conditions */
3558 init_capture_stop_conditions();
3559 /* create stop conditions */
3560 if (capture_opts->has_autostop_filesize) {
3561 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3562 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3565 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3567 if (capture_opts->has_autostop_duration)
3568 cnd_autostop_duration =
3569 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3571 if (capture_opts->multi_files_on) {
3572 if (capture_opts->has_file_duration)
3574 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3576 if (capture_opts->has_autostop_files)
3577 cnd_autostop_files =
3578 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3581 /* init the time values */
3583 upd_time = GetTickCount();
3585 gettimeofday(&upd_time, NULL);
3587 start_time = create_timestamp();
3588 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
3590 /* WOW, everything is prepared! */
3591 /* please fasten your seat belts, we will enter now the actual capture loop */
3593 pcap_queue = g_async_queue_new();
3594 pcap_queue_bytes = 0;
3595 pcap_queue_packets = 0;
3596 for (i = 0; i < global_ld.pcaps->len; i++) {
3597 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3598 #if GLIB_CHECK_VERSION(2,31,0)
3599 /* XXX - Add an interface name here? */
3600 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3602 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3606 while (global_ld.go) {
3607 /* dispatch incoming packets */
3609 pcap_queue_element *queue_element;
3610 #if GLIB_CHECK_VERSION(2,31,18)
3612 g_async_queue_lock(pcap_queue);
3613 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3615 GTimeVal write_thread_time;
3617 g_get_current_time(&write_thread_time);
3618 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3619 g_async_queue_lock(pcap_queue);
3620 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3622 if (queue_element) {
3623 pcap_queue_bytes -= queue_element->phdr.caplen;
3624 pcap_queue_packets -= 1;
3626 g_async_queue_unlock(pcap_queue);
3627 if (queue_element) {
3628 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3629 "Dequeued a packet of length %d captured on interface %d.",
3630 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3632 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3633 &queue_element->phdr,
3635 g_free(queue_element->pd);
3636 g_free(queue_element);
3642 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3643 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3644 sizeof(errmsg), pcap_opts);
3647 /* Were we asked to print packet counts by the SIGINFO handler? */
3648 if (global_ld.report_packet_count) {
3649 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3650 plurality(global_ld.packet_count, "", "s"));
3651 global_ld.report_packet_count = FALSE;
3656 /* any news from our parent (signal pipe)? -> just stop the capture */
3657 if (!signal_pipe_check_running()) {
3658 global_ld.go = FALSE;
3663 global_ld.inpkts_to_sync_pipe += inpkts;
3665 /* check capture size condition */
3666 if (cnd_autostop_size != NULL &&
3667 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3668 /* Capture size limit reached, do we have another file? */
3669 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3670 cnd_autostop_size, cnd_file_duration))
3672 } /* cnd_autostop_size */
3673 if (capture_opts->output_to_pipe) {
3674 fflush(global_ld.pdh);
3678 /* Only update once every 500ms so as not to overload slow displays.
3679 * This also prevents too much context-switching between the dumpcap
3680 * and wireshark processes.
3682 #define DUMPCAP_UPD_TIME 500
3685 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3686 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3688 gettimeofday(&cur_time, NULL);
3689 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3690 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3693 upd_time = cur_time;
3696 if (pcap_stats(pch, stats) >= 0) {
3697 *stats_known = TRUE;
3700 /* Let the parent process know. */
3701 if (global_ld.inpkts_to_sync_pipe) {
3703 fflush(global_ld.pdh);
3705 /* Send our parent a message saying we've written out
3706 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3708 report_packet_count(global_ld.inpkts_to_sync_pipe);
3710 global_ld.inpkts_to_sync_pipe = 0;
3713 /* check capture duration condition */
3714 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3715 /* The maximum capture time has elapsed; stop the capture. */
3716 global_ld.go = FALSE;
3720 /* check capture file duration condition */
3721 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3722 /* duration limit reached, do we have another file? */
3723 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3724 cnd_autostop_size, cnd_file_duration))
3726 } /* cnd_file_duration */
3730 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3732 pcap_queue_element *queue_element;
3734 for (i = 0; i < global_ld.pcaps->len; i++) {
3735 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3736 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3737 pcap_opts->interface_id);
3738 g_thread_join(pcap_opts->tid);
3739 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3740 pcap_opts->interface_id);
3743 g_async_queue_lock(pcap_queue);
3744 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3745 if (queue_element) {
3746 pcap_queue_bytes -= queue_element->phdr.caplen;
3747 pcap_queue_packets -= 1;
3749 g_async_queue_unlock(pcap_queue);
3750 if (queue_element == NULL) {
3753 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3754 "Dequeued a packet of length %d captured on interface %d.",
3755 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3756 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3757 &queue_element->phdr,
3759 g_free(queue_element->pd);
3760 g_free(queue_element);
3761 global_ld.inpkts_to_sync_pipe += 1;
3762 if (capture_opts->output_to_pipe) {
3763 fflush(global_ld.pdh);
3769 /* delete stop conditions */
3770 if (cnd_file_duration != NULL)
3771 cnd_delete(cnd_file_duration);
3772 if (cnd_autostop_files != NULL)
3773 cnd_delete(cnd_autostop_files);
3774 if (cnd_autostop_size != NULL)
3775 cnd_delete(cnd_autostop_size);
3776 if (cnd_autostop_duration != NULL)
3777 cnd_delete(cnd_autostop_duration);
3779 /* did we have a pcap (input) error? */
3780 for (i = 0; i < capture_opts->ifaces->len; i++) {
3781 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3782 if (pcap_opts->pcap_err) {
3783 /* On Linux, if an interface goes down while you're capturing on it,
3784 you'll get a "recvfrom: Network is down" or
3785 "The interface went down" error (ENETDOWN).
3786 (At least you will if g_strerror() doesn't show a local translation
3789 On FreeBSD and OS X, if a network adapter disappears while
3790 you're capturing on it, you'll get a "read: Device not configured"
3791 error (ENXIO). (See previous parenthetical note.)
3793 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3795 These should *not* be reported to the Wireshark developers. */
3798 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3799 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3800 strcmp(cap_err_str, "The interface went down") == 0 ||
3801 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3802 strcmp(cap_err_str, "read: I/O error") == 0 ||
3803 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3804 report_capture_error("The network adapter on which the capture was being done "
3805 "is no longer running; the capture has stopped.",
3808 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3810 report_capture_error(errmsg, please_report);
3813 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3814 report_capture_error(errmsg, "");
3818 /* did we have an output error while capturing? */
3819 if (global_ld.err == 0) {
3822 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3823 global_ld.err, FALSE);
3824 report_capture_error(errmsg, please_report);
3828 if (capture_opts->saving_to_file) {
3829 /* close the output file */
3830 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3834 /* there might be packets not yet notified to the parent */
3835 /* (do this after closing the file, so all packets are already flushed) */
3836 if (global_ld.inpkts_to_sync_pipe) {
3838 report_packet_count(global_ld.inpkts_to_sync_pipe);
3839 global_ld.inpkts_to_sync_pipe = 0;
3842 /* If we've displayed a message about a write error, there's no point
3843 in displaying another message about an error on close. */
3844 if (!close_ok && write_ok) {
3845 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3847 report_capture_error(errmsg, "");
3851 * XXX We exhibit different behaviour between normal mode and sync mode
3852 * when the pipe is stdin and not already at EOF. If we're a child, the
3853 * parent's stdin isn't closed, so if the user starts another capture,
3854 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3855 * will say "Unrecognized libpcap format". On the other hand, in normal
3856 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3859 report_capture_count(TRUE);
3861 /* get packet drop statistics from pcap */
3862 for (i = 0; i < capture_opts->ifaces->len; i++) {
3864 guint32 pcap_dropped = 0;
3866 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3867 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3868 received = pcap_opts->received;
3869 if (pcap_opts->pcap_h != NULL) {
3870 g_assert(!pcap_opts->from_cap_pipe);
3871 /* Get the capture statistics, so we know how many packets were dropped. */
3873 * Older versions of libpcap didn't set ps_ifdrop on some
3874 * platforms; initialize it to 0 to handle that.
3876 stats->ps_ifdrop = 0;
3877 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3878 *stats_known = TRUE;
3879 /* Let the parent process know. */
3880 pcap_dropped += stats->ps_drop;
3882 g_snprintf(errmsg, sizeof(errmsg),
3883 "Can't get packet-drop statistics: %s",
3884 pcap_geterr(pcap_opts->pcap_h));
3885 report_capture_error(errmsg, please_report);
3888 report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
3891 /* close the input file (pcap or capture pipe) */
3892 capture_loop_close_input(&global_ld);
3894 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3896 /* ok, if the write and the close were successful. */
3897 return write_ok && close_ok;
3900 if (capture_opts->multi_files_on) {
3901 /* cleanup ringbuffer */
3902 ringbuf_error_cleanup();
3904 /* We can't use the save file, and we have no FILE * for the stream
3905 to close in order to close it, so close the FD directly. */
3906 if (global_ld.save_file_fd != -1) {
3907 ws_close(global_ld.save_file_fd);
3910 /* We couldn't even start the capture, so get rid of the capture
3912 if (capture_opts->save_file != NULL) {
3913 ws_unlink(capture_opts->save_file);
3914 g_free(capture_opts->save_file);
3917 capture_opts->save_file = NULL;
3919 report_cfilter_error(capture_opts, error_index, errmsg);
3921 report_capture_error(errmsg, secondary_errmsg);
3923 /* close the input file (pcap or cap_pipe) */
3924 capture_loop_close_input(&global_ld);
3926 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3933 capture_loop_stop(void)
3935 #ifdef HAVE_PCAP_BREAKLOOP
3937 pcap_options *pcap_opts;
3939 for (i = 0; i < global_ld.pcaps->len; i++) {
3940 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3941 if (pcap_opts->pcap_h != NULL)
3942 pcap_breakloop(pcap_opts->pcap_h);
3945 global_ld.go = FALSE;
3950 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3951 int err, gboolean is_close)
3956 g_snprintf(errmsg, errmsglen,
3957 "Not all the packets could be written to the file"
3958 " to which the capture was being saved\n"
3959 "(\"%s\") because there is no space left on the file system\n"
3960 "on which that file resides.",
3966 g_snprintf(errmsg, errmsglen,
3967 "Not all the packets could be written to the file"
3968 " to which the capture was being saved\n"
3969 "(\"%s\") because you are too close to, or over,"
3970 " your disk quota\n"
3971 "on the file system on which that file resides.",
3978 g_snprintf(errmsg, errmsglen,
3979 "The file to which the capture was being saved\n"
3980 "(\"%s\") could not be closed: %s.",
3981 fname, g_strerror(err));
3983 g_snprintf(errmsg, errmsglen,
3984 "An error occurred while writing to the file"
3985 " to which the capture was being saved\n"
3987 fname, g_strerror(err));
3994 /* one packet was captured, process it */
3996 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3999 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4001 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
4003 /* We may be called multiple times from pcap_dispatch(); if we've set
4004 the "stop capturing" flag, ignore this packet, as we're not
4005 supposed to be saving any more packets. */
4006 if (!global_ld.go) {
4007 pcap_opts->flushed++;
4011 if (global_ld.pdh) {
4012 gboolean successful;
4014 /* We're supposed to write the packet to a file; do so.
4015 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4016 "ld->err" to the error. */
4017 if (global_capture_opts.use_pcapng) {
4018 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4020 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4021 phdr->caplen, phdr->len,
4022 pcap_opts->interface_id,
4025 &global_ld.bytes_written, &err);
4027 successful = libpcap_write_packet(global_ld.pdh,
4028 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4029 phdr->caplen, phdr->len,
4031 &global_ld.bytes_written, &err);
4034 global_ld.go = FALSE;
4035 global_ld.err = err;
4036 pcap_opts->dropped++;
4038 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4039 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4040 "Wrote a packet of length %d captured on interface %u.",
4041 phdr->caplen, pcap_opts->interface_id);
4043 global_ld.packet_count++;
4044 pcap_opts->received++;
4045 /* if the user told us to stop after x packets, do we already have enough? */
4046 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4047 global_ld.go = FALSE;
4053 /* one packet was captured, queue it */
4055 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4058 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4059 pcap_queue_element *queue_element;
4060 gboolean limit_reached;
4062 /* We may be called multiple times from pcap_dispatch(); if we've set
4063 the "stop capturing" flag, ignore this packet, as we're not
4064 supposed to be saving any more packets. */
4065 if (!global_ld.go) {
4066 pcap_opts->flushed++;
4070 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4071 if (queue_element == NULL) {
4072 pcap_opts->dropped++;
4075 queue_element->pcap_opts = pcap_opts;
4076 queue_element->phdr = *phdr;
4077 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4078 if (queue_element->pd == NULL) {
4079 pcap_opts->dropped++;
4080 g_free(queue_element);
4083 memcpy(queue_element->pd, pd, phdr->caplen);
4084 g_async_queue_lock(pcap_queue);
4085 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4086 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4087 limit_reached = FALSE;
4088 g_async_queue_push_unlocked(pcap_queue, queue_element);
4089 pcap_queue_bytes += phdr->caplen;
4090 pcap_queue_packets += 1;
4092 limit_reached = TRUE;
4094 g_async_queue_unlock(pcap_queue);
4095 if (limit_reached) {
4096 pcap_opts->dropped++;
4097 g_free(queue_element->pd);
4098 g_free(queue_element);
4099 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4100 "Dropped a packet of length %d captured on interface %u.",
4101 phdr->caplen, pcap_opts->interface_id);
4103 pcap_opts->received++;
4104 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4105 "Queued a packet of length %d captured on interface %u.",
4106 phdr->caplen, pcap_opts->interface_id);
4108 /* I don't want to hold the mutex over the debug output. So the
4109 output may be wrong */
4110 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4111 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4112 pcap_queue_bytes, pcap_queue_packets);
4116 set_80211_channel(const char *iface, const char *opt)
4118 int freq = 0, type, ret;
4119 gchar **options = NULL;
4121 options = g_strsplit_set(opt, ",", 2);
4124 freq = atoi(options[0]);
4127 type = ws80211_str_to_chan_type(options[1]);
4136 ret = ws80211_init();
4138 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4142 ret = ws80211_set_freq(iface, freq, type);
4145 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4151 pipe_write_block(2, SP_SUCCESS, NULL);
4155 g_strfreev(options);
4160 get_dumpcap_runtime_info(GString *str)
4163 g_string_append(str, ", ");
4164 get_runtime_pcap_version(str);
4167 #if defined(HAVE_LIBZ) && !defined(_WIN32)
4168 g_string_append_printf(str, ", with libz %s", zlibVersion());
4172 /* And now our feature presentation... [ fade to music ] */
4174 main(int argc, char *argv[])
4176 GString *comp_info_str;
4177 GString *runtime_info_str;
4179 static const struct option long_options[] = {
4180 {(char *)"help", no_argument, NULL, 'h'},
4181 {(char *)"version", no_argument, NULL, 'v'},
4182 LONGOPT_CAPTURE_COMMON
4186 gboolean arg_error = FALSE;
4191 struct sigaction action, oldaction;
4194 gboolean start_capture = TRUE;
4195 gboolean stats_known;
4196 struct pcap_stat stats;
4197 GLogLevelFlags log_flags;
4198 gboolean list_interfaces = FALSE;
4199 gboolean list_link_layer_types = FALSE;
4200 #ifdef HAVE_BPF_IMAGE
4201 gboolean print_bpf_code = FALSE;
4203 gboolean set_chan = FALSE;
4204 gchar *set_chan_arg = NULL;
4205 gboolean machine_readable = FALSE;
4206 gboolean print_statistics = FALSE;
4207 int status, run_once_args = 0;
4210 #if defined(__APPLE__) && defined(__LP64__)
4211 struct utsname osinfo;
4215 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
4217 /* Assemble the compile-time version information string */
4218 comp_info_str = g_string_new("Compiled ");
4219 get_compiled_version_info(comp_info_str, NULL, NULL);
4221 /* Assemble the run-time version information string */
4222 runtime_info_str = g_string_new("Running ");
4223 get_runtime_version_info(runtime_info_str, get_dumpcap_runtime_info);
4225 /* Add it to the information to be reported on a crash. */
4226 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
4231 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
4234 arg_list_utf_16to8(argc, argv);
4235 create_app_running_mutex();
4238 * Initialize our DLL search path. MUST be called before LoadLibrary
4241 ws_init_dll_search_path();
4244 #ifdef HAVE_BPF_IMAGE
4245 #define OPTSTRING_d "d"
4247 #define OPTSTRING_d ""
4250 #ifdef HAVE_PCAP_REMOTE
4251 #define OPTSTRING_r "r"
4252 #define OPTSTRING_u "u"
4254 #define OPTSTRING_r ""
4255 #define OPTSTRING_u ""
4258 #ifdef HAVE_PCAP_SETSAMPLING
4259 #define OPTSTRING_m "m:"
4261 #define OPTSTRING_m ""
4264 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
4266 #ifdef DEBUG_CHILD_DUMPCAP
4267 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4268 fprintf (stderr, "Unable to open debug log file !\n");
4273 #if defined(__APPLE__) && defined(__LP64__)
4275 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4276 * a bug workaround - timeouts less than 1 second don't work with libpcap
4277 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4278 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4279 * The problem is extremely unlikely to be reintroduced in a future
4282 if (uname(&osinfo) == 0) {
4284 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
4285 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4286 * number of 10.0.0, not 10.1.0 - go figure).
4288 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4289 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4290 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4291 need_timeout_workaround = TRUE;
4296 * Determine if dumpcap is being requested to run in a special
4297 * capture_child mode by going thru the command line args to see if
4298 * a -Z is present. (-Z is a hidden option).
4300 * The primary result of running in capture_child mode is that
4301 * all messages sent out on stderr are in a special type/len/string
4302 * format to allow message processing by type. These messages include
4303 * error messages if dumpcap fails to start the operation it was
4304 * requested to do, as well as various "status" messages which are sent
4305 * when an actual capture is in progress, and a "success" message sent
4306 * if dumpcap was requested to perform an operation other than a
4309 * Capture_child mode would normally be requested by a parent process
4310 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4311 * to which dumpcap stderr has been redirected. It might also have
4312 * another pipe to obtain dumpcap stdout output; for operations other
4313 * than a capture, that information is formatted specially for easier
4314 * parsing by the parent process.
4316 * Capture_child mode needs to be determined immediately upon
4317 * startup so that any messages generated by dumpcap in this mode
4318 * (eg: during initialization) will be formatted properly.
4321 for (i=1; i<argc; i++) {
4322 if (strcmp("-Z", argv[i]) == 0) {
4323 capture_child = TRUE;
4324 machine_readable = TRUE; /* request machine-readable output */
4326 /* set output pipe to binary mode, to avoid ugly text conversions */
4327 _setmode(2, O_BINARY);
4332 /* The default_log_handler will use stdout, which makes trouble in */
4333 /* capture child mode, as it uses stdout for its sync_pipe. */
4334 /* So: the filtering is done in the console_log_handler and not here.*/
4335 /* We set the log handlers right up front to make sure that any log */
4336 /* messages when running as child will be sent back to the parent */
4337 /* with the correct format. */
4342 G_LOG_LEVEL_CRITICAL|
4343 G_LOG_LEVEL_WARNING|
4344 G_LOG_LEVEL_MESSAGE|
4348 G_LOG_FLAG_RECURSION);
4350 g_log_set_handler(NULL,
4352 console_log_handler, NULL /* user_data */);
4353 g_log_set_handler(LOG_DOMAIN_MAIN,
4355 console_log_handler, NULL /* user_data */);
4356 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4358 console_log_handler, NULL /* user_data */);
4359 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4361 console_log_handler, NULL /* user_data */);
4363 /* Initialize the pcaps list */
4364 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
4366 #if !GLIB_CHECK_VERSION(2,31,0)
4367 /* Initialize the thread system */
4368 g_thread_init(NULL);
4372 /* Load wpcap if possible. Do this before collecting the run-time version information */
4375 /* ... and also load the packet.dll from wpcap */
4376 /* XXX - currently not required, may change later. */
4377 /*wpcap_packet_load();*/
4379 /* Start windows sockets */
4380 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4382 /* Set handler for Ctrl+C key */
4383 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4385 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4386 and exit. Do the same with SIGPIPE, in case, for example,
4387 we're writing to our standard output and it's a pipe.
4388 Do the same with SIGHUP if it's not being ignored (if we're
4389 being run under nohup, it might be ignored, in which case we
4390 should leave it ignored).
4392 XXX - apparently, Coverity complained that part of action
4393 wasn't initialized. Perhaps it's running on Linux, where
4394 struct sigaction has an ignored "sa_restorer" element and
4395 where "sa_handler" and "sa_sigaction" might not be two
4396 members of a union. */
4397 memset(&action, 0, sizeof(action));
4398 action.sa_handler = capture_cleanup_handler;
4400 * Arrange that system calls not get restarted, because when
4401 * our signal handler returns we don't want to restart
4402 * a call that was waiting for packets to arrive.
4404 action.sa_flags = 0;
4405 sigemptyset(&action.sa_mask);
4406 sigaction(SIGTERM, &action, NULL);
4407 sigaction(SIGINT, &action, NULL);
4408 sigaction(SIGPIPE, &action, NULL);
4409 sigaction(SIGHUP, NULL, &oldaction);
4410 if (oldaction.sa_handler == SIG_DFL)
4411 sigaction(SIGHUP, &action, NULL);
4414 /* Catch SIGINFO and, if we get it and we're capturing in
4415 quiet mode, report the number of packets we've captured. */
4416 action.sa_handler = report_counts_siginfo;
4417 action.sa_flags = SA_RESTART;
4418 sigemptyset(&action.sa_mask);
4419 sigaction(SIGINFO, &action, NULL);
4420 #endif /* SIGINFO */
4424 enable_kernel_bpf_jit_compiler();
4427 /* ----------------------------------------------------------------- */
4428 /* Privilege and capability handling */
4430 /* 1. Running not as root or suid root; no special capabilities. */
4433 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4436 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4438 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4439 /* capabilities; Drop all other capabilities; */
4440 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4441 /* else: after pcap_open_live() in capture_loop_open_input() */
4442 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4443 /* (Note: this means that the process, although logged in */
4444 /* as root, does not have various permissions such as the */
4445 /* ability to bypass file access permissions). */
4446 /* XXX: Should we just leave capabilities alone in this case */
4447 /* so that user gets expected effect that root can do */
4450 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4452 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4453 /* else: after pcap_open_live() in capture_loop_open_input() */
4454 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4455 /* pcap_open_live). */
4457 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4459 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4460 /* capabilities; Drop all other capabilities; */
4461 /* Drop suid privileges (euid=ruid); */
4462 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4463 /* else: after pcap_open_live() in capture_loop_open_input() */
4464 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4466 /* XXX: For some Linux versions/distros with capabilities */
4467 /* a 'normal' process with any capabilities cannot be */
4468 /* 'killed' (signaled) from another (same uid) non-privileged */
4470 /* For example: If (non-suid) Wireshark forks a */
4471 /* child suid dumpcap which acts as described here (case 5), */
4472 /* Wireshark will be unable to kill (signal) the child */
4473 /* dumpcap process until the capabilities have been dropped */
4474 /* (after pcap_open_live()). */
4475 /* This behaviour will apparently be changed in the kernel */
4476 /* to allow the kill (signal) in this case. */
4477 /* See the following for details: */
4478 /* http://www.mail-archive.com/ [wrapped] */
4479 /* linux-security-module@vger.kernel.org/msg02913.html */
4481 /* It is therefore conceivable that if dumpcap somehow hangs */
4482 /* in pcap_open_live or before that wireshark will not */
4483 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4484 /* In this case, exiting wireshark will kill the child */
4485 /* dumpcap process. */
4487 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4488 /* capabilities; Using libcap. Note: capset cmd (which see) */
4489 /* used to assign capabilities to file. */
4491 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4492 /* else: after pcap_open_live() in capture_loop_open_input() */
4493 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4495 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4496 /* longer required (similar to capture). */
4498 /* ----------------------------------------------------------------- */
4500 init_process_policies();
4503 /* If 'started with special privileges' (and using libcap) */
4504 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4505 /* Set euid/egid = ruid/rgid to remove suid privileges */
4506 relinquish_privs_except_capture();
4509 /* Set the initial values in the capture options. This might be overwritten
4510 by the command line parameters. */
4511 capture_opts_init(&global_capture_opts);
4513 /* We always save to a file - if no file was specified, we save to a
4515 global_capture_opts.saving_to_file = TRUE;
4516 global_capture_opts.has_ring_num_files = TRUE;
4518 /* Pass on capture_child mode for capture_opts */
4519 global_capture_opts.capture_child = capture_child;
4521 /* Now get our args */
4522 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4524 case 'h': /* Print help and exit */
4525 printf("Dumpcap (Wireshark) %s\n"
4526 "Capture network packets and dump them into a pcapng or pcap file.\n"
4527 "See http://www.wireshark.org for more information.\n",
4528 get_ws_vcs_version_info());
4529 print_usage(stdout);
4532 case 'v': /* Show version and exit */
4534 show_version(comp_info_str, runtime_info_str);
4535 g_string_free(comp_info_str, TRUE);
4536 g_string_free(runtime_info_str, TRUE);
4540 /*** capture option specific ***/
4541 case 'a': /* autostop criteria */
4542 case 'b': /* Ringbuffer option */
4543 case 'c': /* Capture x packets */
4544 case 'f': /* capture filter */
4545 case 'g': /* enable group read access on file(s) */
4546 case 'i': /* Use interface x */
4547 case 'n': /* Use pcapng format */
4548 case 'p': /* Don't capture in promiscuous mode */
4549 case 'P': /* Use pcap format */
4550 case 's': /* Set the snapshot (capture) length */
4551 case 'w': /* Write to capture file x */
4552 case 'y': /* Set the pcap data link type */
4553 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4554 #ifdef HAVE_PCAP_REMOTE
4555 case 'u': /* Use UDP for data transfer */
4556 case 'r': /* Capture own RPCAP traffic too */
4557 case 'A': /* Authentication */
4559 #ifdef HAVE_PCAP_SETSAMPLING
4560 case 'm': /* Sampling */
4562 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4563 case 'B': /* Buffer size */
4564 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4565 #ifdef HAVE_PCAP_CREATE
4566 case 'I': /* Monitor mode */
4568 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4573 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4575 capture_child = TRUE;
4577 /* set output pipe to binary mode, to avoid ugly text conversions */
4578 _setmode(2, O_BINARY);
4580 * optarg = the control ID, aka the PPID, currently used for the
4583 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4584 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4585 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4586 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4588 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4589 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4590 "Signal pipe: Unable to open %s. Dead parent?",
4598 case 'q': /* Quiet */
4604 /*** all non capture option specific ***/
4605 case 'D': /* Print a list of capture devices and exit */
4606 list_interfaces = TRUE;
4609 case 'L': /* Print list of link-layer types and exit */
4610 list_link_layer_types = TRUE;
4613 #ifdef HAVE_BPF_IMAGE
4614 case 'd': /* Print BPF code for capture filter and exit */
4615 print_bpf_code = TRUE;
4619 case 'S': /* Print interface statistics once a second */
4620 print_statistics = TRUE;
4623 case 'k': /* Set wireless channel */
4625 set_chan_arg = optarg;
4628 case 'M': /* For -D, -L, and -S, print machine-readable output */
4629 machine_readable = TRUE;
4632 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4635 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4638 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4640 case '?': /* Bad flag - print usage message */
4649 /* user specified file name as regular command-line argument */
4650 /* XXX - use it as the capture file name (or something else)? */
4656 * Extra command line arguments were specified; complain.
4657 * XXX - interpret as capture filter, as tcpdump and tshark do?
4659 cmdarg_err("Invalid argument: %s", argv[0]);
4664 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4667 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4668 /* Use some default if the user hasn't specified some */
4669 /* XXX: Are these defaults good enough? */
4670 pcap_queue_byte_limit = 1000 * 1000;
4671 pcap_queue_packet_limit = 1000;
4674 print_usage(stderr);
4678 if (run_once_args > 1) {
4679 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4681 } else if (run_once_args == 1) {
4682 /* We're supposed to print some information, rather than
4683 to capture traffic; did they specify a ring buffer option? */
4684 if (global_capture_opts.multi_files_on) {
4685 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4689 /* We're supposed to capture traffic; */
4691 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4692 if (global_capture_opts.ifaces->len > 1) {
4694 global_capture_opts.use_pcapng = TRUE;
4697 if (global_capture_opts.capture_comment &&
4698 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4699 /* XXX - for ringbuffer, should we apply the comment to each file? */
4700 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4704 /* Was the ring buffer option specified and, if so, does it make sense? */
4705 if (global_capture_opts.multi_files_on) {
4706 /* Ring buffer works only under certain conditions:
4707 a) ring buffer does not work with temporary files;
4708 b) it makes no sense to enable the ring buffer if the maximum
4709 file size is set to "infinite". */
4710 if (global_capture_opts.save_file == NULL) {
4711 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4712 global_capture_opts.multi_files_on = FALSE;
4714 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4715 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4717 /* XXX - this must be redesigned as the conditions changed */
4718 global_capture_opts.multi_files_on = FALSE;
4725 * "-D" requires no interface to be selected; it's supposed to list
4728 if (list_interfaces) {
4729 /* Get the list of interfaces */
4734 if_list = capture_interface_list(&err, &err_str,NULL);
4735 if (if_list == NULL) {
4737 case CANT_GET_INTERFACE_LIST:
4738 case DONT_HAVE_PCAP:
4739 cmdarg_err("%s", err_str);
4744 case NO_INTERFACES_FOUND:
4746 * If we're being run by another program, just give them
4747 * an empty list of interfaces, don't report this as
4748 * an error; that lets them decide whether to report
4749 * this as an error or not.
4751 if (!machine_readable) {
4752 cmdarg_err("There are no interfaces on which a capture can be done");
4759 if (machine_readable) /* tab-separated values to stdout */
4760 print_machine_readable_interfaces(if_list);
4762 capture_opts_print_interfaces(if_list);
4763 free_interface_list(if_list);
4768 * "-S" requires no interface to be selected; it gives statistics
4769 * for all interfaces.
4771 if (print_statistics) {
4772 status = print_statistics_loop(machine_readable);
4777 interface_options interface_opts;
4779 if (global_capture_opts.ifaces->len != 1) {
4780 cmdarg_err("Need one interface");
4784 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4785 status = set_80211_channel(interface_opts.name, set_chan_arg);
4790 * "-L", "-d", and capturing act on a particular interface, so we have to
4791 * have an interface; if none was specified, pick a default.
4793 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4795 /* cmdarg_err() already called .... */
4799 /* Let the user know what interfaces were chosen. */
4800 if (capture_child) {
4801 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4802 interface_options interface_opts;
4804 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4805 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4806 interface_opts.name);
4809 str = g_string_new("");
4811 if (global_capture_opts.ifaces->len < 2)
4813 if (global_capture_opts.ifaces->len < 4)
4816 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4817 interface_options interface_opts;
4819 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4821 if (global_capture_opts.ifaces->len > 2) {
4822 g_string_append_printf(str, ",");
4824 g_string_append_printf(str, " ");
4825 if (j == global_capture_opts.ifaces->len - 1) {
4826 g_string_append_printf(str, "and ");
4829 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4832 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4834 fprintf(stderr, "Capturing on %s\n", str->str);
4835 g_string_free(str, TRUE);
4838 if (list_link_layer_types) {
4839 /* Get the list of link-layer types for the capture device. */
4840 if_capabilities_t *caps;
4844 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4845 interface_options interface_opts;
4847 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4848 caps = get_if_capabilities(interface_opts.name,
4849 interface_opts.monitor_mode, &err_str);
4851 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4852 "Please check to make sure you have sufficient permissions, and that\n"
4853 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4857 if (caps->data_link_types == NULL) {
4858 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4861 if (machine_readable) /* tab-separated values to stdout */
4862 /* XXX: We need to change the format and adopt consumers */
4863 print_machine_readable_if_capabilities(caps);
4865 /* XXX: We might want to print also the interface name */
4866 capture_opts_print_if_capabilities(caps, interface_opts.name,
4867 interface_opts.monitor_mode);
4868 free_if_capabilities(caps);
4873 /* We're supposed to do a capture, or print the BPF code for a filter.
4874 Process the snapshot length, as that affects the generated BPF code. */
4875 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4877 #ifdef HAVE_BPF_IMAGE
4878 if (print_bpf_code) {
4879 show_filter_code(&global_capture_opts);
4884 /* We're supposed to do a capture. Process the ring buffer arguments. */
4885 capture_opts_trim_ring_num_files(&global_capture_opts);
4887 /* flush stderr prior to starting the main capture loop */
4890 /* Now start the capture. */
4892 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4896 /* capture failed */
4899 return 0; /* never here, make compiler happy */
4904 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4905 const char *message, gpointer user_data _U_)
4912 /* ignore log message, if log_level isn't interesting */
4913 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4914 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4919 /* create a "timestamp" */
4921 today = localtime(&curr);
4923 switch(log_level & G_LOG_LEVEL_MASK) {
4924 case G_LOG_LEVEL_ERROR:
4927 case G_LOG_LEVEL_CRITICAL:
4930 case G_LOG_LEVEL_WARNING:
4933 case G_LOG_LEVEL_MESSAGE:
4936 case G_LOG_LEVEL_INFO:
4939 case G_LOG_LEVEL_DEBUG:
4943 fprintf(stderr, "unknown log_level %u\n", log_level);
4945 g_assert_not_reached();
4948 /* Generate the output message */
4949 if (log_level & G_LOG_LEVEL_MESSAGE) {
4950 /* normal user messages without additional infos */
4951 msg = g_strdup_printf("%s\n", message);
4953 /* info/debug messages with additional infos */
4954 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4955 today->tm_hour, today->tm_min, today->tm_sec,
4956 log_domain != NULL ? log_domain : "",
4960 /* DEBUG & INFO msgs (if we're debugging today) */
4961 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4962 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4963 #ifdef DEBUG_DUMPCAP
4964 fprintf(stderr, "%s", msg);
4967 #ifdef DEBUG_CHILD_DUMPCAP
4968 fprintf(debug_log, "%s", msg);
4976 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4977 /* to parent especially formatted if dumpcap running as child. */
4978 if (capture_child) {
4979 sync_pipe_errmsg_to_parent(2, msg, "");
4981 fprintf(stderr, "%s", msg);
4988 /****************************************************************************************************************/
4989 /* indication report routines */
4993 report_packet_count(unsigned int packet_count)
4995 char tmp[SP_DECISIZE+1+1];
4996 static unsigned int count = 0;
4998 if (capture_child) {
4999 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
5000 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
5001 pipe_write_block(2, SP_PACKET_COUNT, tmp);
5003 count += packet_count;
5004 fprintf(stderr, "\rPackets: %u ", count);
5005 /* stderr could be line buffered */
5011 report_new_capture_file(const char *filename)
5013 if (capture_child) {
5014 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
5015 pipe_write_block(2, SP_FILE, filename);
5019 * Prevent a SIGINFO handler from writing to the standard error
5020 * while we're doing so; instead, have it just set a flag telling
5021 * us to print that information when we're done.
5024 #endif /* SIGINFO */
5025 fprintf(stderr, "File: %s\n", filename);
5026 /* stderr could be line buffered */
5031 * Allow SIGINFO handlers to write.
5036 * If a SIGINFO handler asked us to write out capture counts, do so.
5039 report_counts_for_siginfo();
5040 #endif /* SIGINFO */
5045 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5047 interface_options interface_opts;
5048 char tmp[MSG_MAX_LENGTH+1+6];
5050 if (i < capture_opts->ifaces->len) {
5051 if (capture_child) {
5052 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5053 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5054 pipe_write_block(2, SP_BAD_FILTER, tmp);
5057 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5058 * the error message below.
5060 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
5062 "Invalid capture filter \"%s\" for interface '%s'!\n"
5064 "That string isn't a valid capture filter (%s).\n"
5065 "See the User's Guide for a description of the capture filter syntax.",
5066 interface_opts.cfilter, interface_opts.name, errmsg);
5072 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5074 if (capture_child) {
5075 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5076 "Primary Error: %s", error_msg);
5077 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5078 "Secondary Error: %s", secondary_error_msg);
5079 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5081 cmdarg_err("%s", error_msg);
5082 if (secondary_error_msg[0] != '\0')
5083 cmdarg_err_cont("%s", secondary_error_msg);
5088 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
5090 char tmp[SP_DECISIZE+1+1];
5091 guint32 total_drops = pcap_drops + drops + flushed;
5093 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5095 if (capture_child) {
5096 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5097 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5098 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
5099 /* XXX: Need to provide interface id, changes to consumers required. */
5100 pipe_write_block(2, SP_DROPS, tmp);
5103 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5104 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
5105 received ? 100.0 * received / (received + total_drops) : 0.0);
5106 /* stderr could be line buffered */
5112 /************************************************************************************************/
5113 /* signal_pipe handling */
5118 signal_pipe_check_running(void)
5120 /* any news from our parent? -> just stop the capture */
5124 /* if we are running standalone, no check required */
5125 if (!capture_child) {
5129 if (!sig_pipe_name || !sig_pipe_handle) {
5130 /* This shouldn't happen */
5131 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5132 "Signal pipe: No name or handle");
5137 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5138 * at this point. Should we check to see if the parent is still alive,
5139 * e.g. by using OpenProcess?
5142 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5144 if (!result || avail > 0) {
5145 /* peek failed or some bytes really available */
5146 /* (if not piping from stdin this would fail) */
5147 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5148 "Signal pipe: Stop capture: %s", sig_pipe_name);
5149 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5150 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
5151 sig_pipe_handle, result, avail);
5154 /* pipe ok and no bytes available */
5165 * Editor modelines - http://www.wireshark.org/tools/modelines.html
5170 * indent-tabs-mode: nil
5173 * vi: set shiftwidth=4 tabstop=8 expandtab:
5174 * :indentSize=4:tabSize=8:noTabs=true: