5 * Wireshark - Network traffic analyzer
6 * By Gerald Combs <gerald@wireshark.org>
7 * Copyright 1998 Gerald Combs
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 #include <stdlib.h> /* for exit() */
33 #ifdef HAVE_SYS_TYPES_H
34 # include <sys/types.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
41 #ifdef HAVE_NETINET_IN_H
42 #include <netinet/in.h>
45 #ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
61 #ifdef HAVE_ARPA_INET_H
62 #include <arpa/inet.h>
65 #if defined(__APPLE__) && defined(__LP64__)
66 #include <sys/utsname.h>
72 #include <wsutil/crash_info.h>
75 #include "wsutil/wsgetopt.h"
83 # include <sys/prctl.h>
84 # include <sys/capability.h>
87 #include "ringbuffer.h"
88 #include "clopts_common.h"
89 #include "cmdarg_err.h"
90 #include "version_info.h"
92 #include "capture-pcap-util.h"
94 #include "capture-wpcap.h"
100 #include "capture-wpcap.h"
101 #include <wsutil/unicode-utils.h>
108 #ifdef NEED_INET_V6DEFS_H
109 # include "wsutil/inet_v6defs.h"
112 #include <wsutil/privileges.h>
114 #include "sync_pipe.h"
116 #include "capture_opts.h"
117 #include "capture_session.h"
118 #include "capture_ifinfo.h"
119 #include "capture_sync.h"
121 #include "conditions.h"
122 #include "capture_stop_conditions.h"
124 #include "wsutil/tempfile.h"
126 #include "wsutil/file_util.h"
128 #include "ws80211_utils.h"
131 * Get information about libpcap format from "wiretap/libpcap.h".
132 * XXX - can we just use pcap_open_offline() to read the pipe?
134 #include "wiretap/libpcap.h"
136 /**#define DEBUG_DUMPCAP**/
137 /**#define DEBUG_CHILD_DUMPCAP**/
141 #include <conio.h> /* _getch() */
145 #ifdef DEBUG_CHILD_DUMPCAP
146 FILE *debug_log; /* for logging debug messages to */
147 /* a file if DEBUG_CHILD_DUMPCAP */
151 static GAsyncQueue *pcap_queue;
152 static gint64 pcap_queue_bytes;
153 static gint64 pcap_queue_packets;
154 static gint64 pcap_queue_byte_limit = 0;
155 static gint64 pcap_queue_packet_limit = 0;
157 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
159 static gchar *sig_pipe_name = NULL;
160 static HANDLE sig_pipe_handle = NULL;
161 static gboolean signal_pipe_check_running(void);
165 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
166 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
169 /** Stop a low-level capture (stops the capture child). */
170 static void capture_loop_stop(void);
171 /** Close a pipe, or socket if \a from_socket is TRUE */
172 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
176 * Enable kernel BPF JIT compiler if available.
177 * If any calls fail, just drive on - the JIT compiler might not be
178 * enabled, but filtering will still work, and it's not clear what
179 * we could do if the calls fail; should we just report the error
180 * and not continue to capture, should we report it as a warning, or
184 enable_kernel_bpf_jit_compiler(void)
188 static const char file[] = "/proc/sys/net/core/bpf_jit_enable";
190 fd = open(file, O_WRONLY);
194 written = write(fd, "1", strlen("1"));
200 #if !defined (__linux__)
201 #ifndef HAVE_PCAP_BREAKLOOP
203 * We don't have pcap_breakloop(), which is the only way to ensure that
204 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
205 * won't, if the call to read the next packet or batch of packets is
206 * is interrupted by a signal on UN*X, just go back and try again to
209 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
210 * the signal handler, set a flag to stop capturing; however, without
211 * a guarantee of that sort, we can't guarantee that we'll stop capturing
212 * if the read will be retried and won't time out if no packets arrive.
214 * Therefore, on at least some platforms, we work around the lack of
215 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
216 * to wait for packets to arrive, so that we're probably going to be
217 * blocked in the select() when the signal arrives, and can just bail
218 * out of the loop at that point.
220 * However, we don't want to do that on BSD (because "select()" doesn't work
221 * correctly on BPF devices on at least some releases of some flavors of
222 * BSD), and we don't want to do it on Windows (because "select()" is
223 * something for sockets, not for arbitrary handles). (Note that "Windows"
224 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
225 * using WinPcap, not a UNIX libpcap.)
227 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
228 * on BSD times out even if no packets have arrived, so we'll eventually
229 * exit pcap_dispatch() with an indication that no packets have arrived,
230 * and will break out of the capture loop at that point.
232 * On Windows, we can't send a SIGINT to stop capturing, so none of this
233 * applies in any case.
235 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
236 * want to include it if it's not present on this platform, however.
238 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
239 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
241 # define MUST_DO_SELECT
242 # endif /* avoid select */
243 #endif /* HAVE_PCAP_BREAKLOOP */
245 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
246 * in pcap_dispatch(); on the other hand, select() works just fine there.
247 * Hence we use a select for that come what may.
249 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
250 * internally, and, with TPACKET_V3, once that's supported, it'll
251 * support timeouts, at least as I understand the way the code works.
253 #define MUST_DO_SELECT
256 /** init the capture filter */
259 INITFILTER_BAD_FILTER,
260 INITFILTER_OTHER_ERROR
261 } initfilter_status_t;
264 STATE_EXPECT_REC_HDR,
277 typedef struct _pcap_options {
282 #ifdef MUST_DO_SELECT
283 int pcap_fd; /**< pcap file descriptor */
290 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
291 /**< capture pipe (unix only "input file") */
292 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
293 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
294 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
295 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
297 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
299 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
300 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
301 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
303 char * cap_pipe_buf; /**< Pointer to the data buffer we read into */
304 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
305 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
307 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
308 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
310 cap_pipe_state_t cap_pipe_state;
311 cap_pipe_err_t cap_pipe_err;
314 GMutex *cap_pipe_read_mtx;
315 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
319 typedef struct _loop_data {
321 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
322 int err; /**< if non-zero, error seen while capturing */
323 gint packet_count; /**< Number of packets we have already captured */
324 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
325 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
327 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
333 guint64 bytes_written;
334 guint32 autostop_files;
337 typedef struct _pcap_queue_element {
338 pcap_options *pcap_opts;
339 struct pcap_pkthdr phdr;
341 } pcap_queue_element;
344 * Standard secondary message for unexpected errors.
346 static const char please_report[] =
347 "Please report this to the Wireshark developers.\n"
348 "http://bugs.wireshark.org/\n"
349 "(This is not a crash; please do not report it as such.)";
352 * This needs to be static, so that the SIGINT handler can clear the "go"
355 static loop_data global_ld;
359 * Timeout, in milliseconds, for reads from the stream of captured packets
360 * from a capture device.
362 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
363 * 64-bit applications, with sub-second timeouts not to work. The bug is
364 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
366 #if defined(__APPLE__) && defined(__LP64__)
367 static gboolean need_timeout_workaround;
369 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
371 #define CAP_READ_TIMEOUT 250
375 * Timeout, in microseconds, for reads from the stream of captured packets
376 * from a pipe. Pipes don't have the same problem that BPF devices do
377 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
378 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
379 * of the offending versions of Snow Leopard.
381 * On Windows this value is converted to milliseconds and passed to
382 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
383 * will return immediately.
386 #define PIPE_READ_TIMEOUT 100000
388 #define PIPE_READ_TIMEOUT 250000
391 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
394 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
395 const char *message, gpointer user_data _U_);
397 /* capture related options */
398 static capture_options global_capture_opts;
399 static gboolean quiet = FALSE;
400 static gboolean use_threads = FALSE;
401 static guint64 start_time;
403 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
405 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
407 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
408 int err, gboolean is_close);
410 static void WS_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
412 static void report_new_capture_file(const char *filename);
413 static void report_packet_count(unsigned int packet_count);
414 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
415 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
416 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
418 #define MSG_MAX_LENGTH 4096
420 /* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
422 create_timestamp(void) {
432 * Current time, represented as 100-nanosecond intervals since
433 * January 1, 1601, 00:00:00 UTC.
435 * I think DWORD might be signed, so cast both parts of "now"
436 * to guint32 so that the sign bit doesn't get treated specially.
438 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
439 * might want to use instead.
441 GetSystemTimeAsFileTime(&now);
442 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
443 (guint32)now.dwLowDateTime;
446 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
452 * Subtract difference, in microseconds, between January 1, 1601
453 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
455 timestamp -= G_GUINT64_CONSTANT(11644473600000000);
458 * Current time, represented as seconds and microseconds since
459 * January 1, 1970, 00:00:00 UTC.
461 gettimeofday(&now, NULL);
464 * Convert to delta in microseconds.
466 timestamp = (guint64)(now.tv_sec) * 1000000 +
467 (guint64)(now.tv_usec);
473 print_usage(gboolean print_ver)
480 "Dumpcap " VERSION "%s\n"
481 "Capture network packets and dump them into a pcapng file.\n"
482 "See http://www.wireshark.org for more information.\n",
483 wireshark_gitversion);
487 fprintf(output, "\nUsage: dumpcap [options] ...\n");
488 fprintf(output, "\n");
489 fprintf(output, "Capture interface:\n");
490 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
491 " or for remote capturing, use one of these formats:\n"
492 " rpcap://<host>/<interface>\n"
493 " TCP@<host>:<port>\n");
494 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
495 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
496 fprintf(output, " -p don't capture in promiscuous mode\n");
497 #ifdef HAVE_PCAP_CREATE
498 fprintf(output, " -I capture in monitor mode, if available\n");
500 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
501 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
503 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
504 fprintf(output, " -D print list of interfaces and exit\n");
505 fprintf(output, " -L print list of link-layer types of iface and exit\n");
506 #ifdef HAVE_BPF_IMAGE
507 fprintf(output, " -d print generated BPF code for capture filter\n");
509 fprintf(output, " -k set channel on wifi interface <freq>,[<type>]\n");
510 fprintf(output, " -S print statistics for each interface once per second\n");
511 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
512 fprintf(output, "\n");
513 #ifdef HAVE_PCAP_REMOTE
514 fprintf(output, "RPCAP options:\n");
515 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
516 fprintf(output, " -u use UDP for RPCAP data transfer\n");
517 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
518 #ifdef HAVE_PCAP_SETSAMPLING
519 fprintf(output, " -m <sampling type> use packet sampling\n");
520 fprintf(output, " count:NUM - capture one packet of every NUM\n");
521 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
524 fprintf(output, "Stop conditions:\n");
525 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
526 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
527 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
528 fprintf(output, " files:NUM - stop after NUM files\n");
529 /*fprintf(output, "\n");*/
530 fprintf(output, "Output (files):\n");
531 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
532 fprintf(output, " -g enable group read access on the output file(s)\n");
533 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
534 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
535 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
536 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
537 fprintf(output, " -P use libpcap format instead of pcapng\n");
538 fprintf(output, " --capture-comment <comment>\n");
539 fprintf(output, " add a capture comment to the output file\n");
540 fprintf(output, " (only for pcapng)\n");
541 fprintf(output, "\n");
542 fprintf(output, "Miscellaneous:\n");
543 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
544 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
545 fprintf(output, " within dumpcap\n");
546 fprintf(output, " -t use a separate thread per interface\n");
547 fprintf(output, " -q don't report packet capture counts\n");
548 fprintf(output, " -v print version information and exit\n");
549 fprintf(output, " -h display this help and exit\n");
550 fprintf(output, "\n");
552 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
553 fprintf(output, "You might want to reset it\n");
554 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
555 fprintf(output, "\n");
557 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
558 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
559 fprintf(output, "\n");
560 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
564 show_version(GString *comp_info_str, GString *runtime_info_str)
567 "Dumpcap " VERSION "%s\n"
572 "See http://www.wireshark.org for more information.\n",
573 wireshark_gitversion, get_copyright_info(), comp_info_str->str, runtime_info_str->str);
577 * Report an error in command-line arguments.
580 cmdarg_err(const char *fmt, ...)
586 /* Generate a 'special format' message back to parent */
588 msg = g_strdup_vprintf(fmt, ap);
589 sync_pipe_errmsg_to_parent(2, msg, "");
594 fprintf(stderr, "dumpcap: ");
595 vfprintf(stderr, fmt, ap);
596 fprintf(stderr, "\n");
602 * Report additional information for an error in command-line arguments.
605 cmdarg_err_cont(const char *fmt, ...)
612 msg = g_strdup_vprintf(fmt, ap);
613 sync_pipe_errmsg_to_parent(2, msg, "");
618 vfprintf(stderr, fmt, ap);
619 fprintf(stderr, "\n");
626 #if 0 /* Set to enable capability debugging */
627 /* see 'man cap_to_text()' for explanation of output */
628 /* '=' means 'all= ' ie: no capabilities */
629 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
631 print_caps(const char *pfx) {
632 cap_t caps = cap_get_proc();
633 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
634 "%s: EUID: %d Capabilities: %s", pfx,
635 geteuid(), cap_to_text(caps, NULL));
638 print_caps(const char *pfx _U_) {
643 relinquish_all_capabilities(void)
645 /* Drop any and all capabilities this process may have. */
646 /* Allowed whether or not process has any privileges. */
647 cap_t caps = cap_init(); /* all capabilities initialized to off */
648 print_caps("Pre-clear");
649 if (cap_set_proc(caps)) {
650 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
652 print_caps("Post-clear");
658 open_capture_device(interface_options *interface_opts,
659 char (*open_err_str)[PCAP_ERRBUF_SIZE])
662 #ifdef HAVE_PCAP_CREATE
665 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
666 struct pcap_rmtauth auth;
669 /* Open the network interface to capture from it.
670 Some versions of libpcap may put warnings into the error buffer
671 if they succeed; to tell if that's happened, we have to clear
672 the error buffer, and check if it's still a null string. */
673 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Entering open_capture_device().");
674 (*open_err_str)[0] = '\0';
675 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
677 * If we're opening a remote device, use pcap_open(); that's currently
678 * the only open routine that supports remote devices.
680 if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
681 auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
682 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
683 auth.username = interface_opts->auth_username;
684 auth.password = interface_opts->auth_password;
686 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
687 "Calling pcap_open() using name %s, snaplen %d, promisc_mode %d, datatx_udp %d, nocap_rpcap %d.",
688 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode,
689 interface_opts->datatx_udp, interface_opts->nocap_rpcap);
690 pcap_h = pcap_open(interface_opts->name, interface_opts->snaplen,
692 (interface_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
693 (interface_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
694 (interface_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
695 CAP_READ_TIMEOUT, &auth, *open_err_str);
696 if (pcap_h == NULL) {
697 /* Error - did pcap actually supply an error message? */
698 if ((*open_err_str)[0] == '\0') {
699 /* Work around known WinPcap bug wherein no error message is
700 filled in on a failure to open an rpcap: URL. */
701 g_strlcpy(*open_err_str,
702 "Unknown error (pcap bug; actual error cause not reported)",
703 sizeof *open_err_str);
706 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
707 "pcap_open() returned %p.", (void *)pcap_h);
712 * If we're not opening a remote device, use pcap_create() and
713 * pcap_activate() if we have them, so that we can set the buffer
714 * size, otherwise use pcap_open_live().
716 #ifdef HAVE_PCAP_CREATE
717 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
718 "Calling pcap_create() using %s.", interface_opts->name);
719 pcap_h = pcap_create(interface_opts->name, *open_err_str);
720 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
721 "pcap_create() returned %p.", (void *)pcap_h);
722 if (pcap_h != NULL) {
723 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
724 "Calling pcap_set_snaplen() with snaplen %d.", interface_opts->snaplen);
725 pcap_set_snaplen(pcap_h, interface_opts->snaplen);
726 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
727 "Calling pcap_set_promisc() with promisc_mode %d.", interface_opts->promisc_mode);
728 pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
729 pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
731 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
732 "buffersize %d.", interface_opts->buffer_size);
733 if (interface_opts->buffer_size != 0) {
734 pcap_set_buffer_size(pcap_h, interface_opts->buffer_size * 1024 * 1024);
736 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
737 "monitor_mode %d.", interface_opts->monitor_mode);
738 if (interface_opts->monitor_mode)
739 pcap_set_rfmon(pcap_h, 1);
740 err = pcap_activate(pcap_h);
741 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
742 "pcap_activate() returned %d.", err);
744 /* Failed to activate, set to NULL */
745 if (err == PCAP_ERROR)
746 g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
748 g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
754 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
755 "pcap_open_live() calling using name %s, snaplen %d, promisc_mode %d.",
756 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode);
757 pcap_h = pcap_open_live(interface_opts->name, interface_opts->snaplen,
758 interface_opts->promisc_mode, CAP_READ_TIMEOUT,
760 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
761 "pcap_open_live() returned %p.", (void *)pcap_h);
764 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_capture_device %s : %s", pcap_h ? "SUCCESS" : "FAILURE", interface_opts->name);
769 get_capture_device_open_failure_messages(const char *open_err_str,
771 char *errmsg, size_t errmsg_len,
772 char *secondary_errmsg,
773 size_t secondary_errmsg_len)
776 const char *libpcap_warn;
777 static const char ppamsg[] = "can't find PPA for ";
780 g_snprintf(errmsg, (gulong) errmsg_len,
781 "The capture session could not be initiated on interface '%s' (%s).",
782 iface, open_err_str);
785 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
787 "In order to capture packets, WinPcap must be installed; see\n"
789 " http://www.winpcap.org/\n"
793 " http://www.mirrors.wiretapped.net/security/packet-capture/winpcap/\n"
797 " http://winpcap.cs.pu.edu.tw/\n"
799 "for a downloadable version of WinPcap and for instructions on how to install\n"
802 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
804 "Please check that \"%s\" is the proper interface.\n"
807 "Help can be found at:\n"
809 " http://wiki.wireshark.org/WinPcap\n"
810 " http://wiki.wireshark.org/CaptureSetup\n",
814 /* If we got a "can't find PPA for X" message, warn the user (who
815 is running dumpcap on HP-UX) that they don't have a version of
816 libpcap that properly handles HP-UX (libpcap 0.6.x and later
817 versions, which properly handle HP-UX, say "can't find /dev/dlpi
818 PPA for X" rather than "can't find PPA for X"). */
819 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
822 "You are running (T)Wireshark with a version of the libpcap library\n"
823 "that doesn't handle HP-UX network devices well; this means that\n"
824 "(T)Wireshark may not be able to capture packets.\n"
826 "To fix this, you should install libpcap 0.6.2, or a later version\n"
827 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
828 "packaged binary form from the Software Porting And Archive Centre\n"
829 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
830 "at the URL lists a number of mirror sites.";
834 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
835 "Please check to make sure you have sufficient permissions, and that you have "
836 "the proper interface or pipe specified.%s", libpcap_warn);
840 /* Set the data link type on a pcap. */
842 set_pcap_linktype(pcap_t *pcap_h, int linktype, char *name,
843 char *errmsg, size_t errmsg_len,
844 char *secondary_errmsg, size_t secondary_errmsg_len)
846 char *set_linktype_err_str;
849 return TRUE; /* just use the default */
850 #ifdef HAVE_PCAP_SET_DATALINK
851 if (pcap_set_datalink(pcap_h, linktype) == 0)
852 return TRUE; /* no error */
853 set_linktype_err_str = pcap_geterr(pcap_h);
855 /* Let them set it to the type it is; reject any other request. */
856 if (get_pcap_linktype(pcap_h, name) == linktype)
857 return TRUE; /* no error */
858 set_linktype_err_str =
859 "That DLT isn't one of the DLTs supported by this device";
861 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type on interface '%s' (%s).",
862 name, set_linktype_err_str);
864 * If the error isn't "XXX is not one of the DLTs supported by this device",
865 * tell the user to tell the Wireshark developers about it.
867 if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
868 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
870 secondary_errmsg[0] = '\0';
875 compile_capture_filter(const char *iface, pcap_t *pcap_h,
876 struct bpf_program *fcode, const char *cfilter)
878 bpf_u_int32 netnum, netmask;
879 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
881 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
883 * Well, we can't get the netmask for this interface; it's used
884 * only for filters that check for broadcast IP addresses, so
885 * we just punt and use 0. It might be nice to warn the user,
886 * but that's a pain in a GUI application, as it'd involve popping
887 * up a message box, and it's not clear how often this would make
888 * a difference (only filters that check for IP broadcast addresses
892 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
897 * Sigh. Older versions of libpcap don't properly declare the
898 * third argument to pcap_compile() as a const pointer. Cast
901 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
906 #ifdef HAVE_BPF_IMAGE
908 show_filter_code(capture_options *capture_opts)
910 interface_options interface_opts;
912 gchar open_err_str[PCAP_ERRBUF_SIZE];
913 char errmsg[MSG_MAX_LENGTH+1];
914 char secondary_errmsg[MSG_MAX_LENGTH+1];
915 struct bpf_program fcode;
916 struct bpf_insn *insn;
920 for (j = 0; j < capture_opts->ifaces->len; j++) {
921 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
922 pcap_h = open_capture_device(&interface_opts, &open_err_str);
923 if (pcap_h == NULL) {
924 /* Open failed; get messages */
925 get_capture_device_open_failure_messages(open_err_str,
927 errmsg, sizeof errmsg,
929 sizeof secondary_errmsg);
930 /* And report them */
931 report_capture_error(errmsg, secondary_errmsg);
935 /* Set the link-layer type. */
936 if (!set_pcap_linktype(pcap_h, interface_opts.linktype, interface_opts.name,
937 errmsg, sizeof errmsg,
938 secondary_errmsg, sizeof secondary_errmsg)) {
940 report_capture_error(errmsg, secondary_errmsg);
944 /* OK, try to compile the capture filter. */
945 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
946 interface_opts.cfilter)) {
948 report_cfilter_error(capture_opts, j, errmsg);
953 /* Now print the filter code. */
954 insn = fcode.bf_insns;
956 for (i = 0; i < fcode.bf_len; insn++, i++)
957 printf("%s\n", bpf_image(insn, i));
959 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
960 /* to remove any suid privileges. */
961 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
962 /* (euid/egid have already previously been set to ruid/rgid. */
963 /* (See comment in main() for details) */
965 relinquish_special_privs_perm();
967 relinquish_all_capabilities();
970 /* Let our parent know we succeeded. */
971 pipe_write_block(2, SP_SUCCESS, NULL);
978 * capture_interface_list() is expected to do the right thing to get
979 * a list of interfaces.
981 * In most of the programs in the Wireshark suite, "the right thing"
982 * is to run dumpcap and ask it for the list, because dumpcap may
983 * be the only program in the suite with enough privileges to get
986 * In dumpcap itself, however, we obviously can't run dumpcap to
987 * ask for the list. Therefore, our capture_interface_list() should
988 * just call get_interface_list().
991 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
993 return get_interface_list(err, err_str);
997 * Get the data-link type for a libpcap device.
998 * This works around AIX 5.x's non-standard and incompatible-with-the-
999 * rest-of-the-universe libpcap.
1002 get_pcap_linktype(pcap_t *pch, const char *devicename
1010 const char *ifacename;
1013 linktype = pcap_datalink(pch);
1017 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
1018 * rather than DLT_ values for link-layer types; the ifType values
1019 * for LAN devices are:
1026 * and the ifType value for a loopback device is 24.
1028 * The AIX names for LAN devices begin with:
1035 * and the AIX names for loopback devices begin with "lo".
1037 * (The difference between "Ethernet" and "802.3" is presumably
1038 * whether packets have an Ethernet header, with a packet type,
1039 * or an 802.3 header, with a packet length, followed by an 802.2
1040 * header and possibly a SNAP header.)
1042 * If the device name matches "linktype" interpreted as an ifType
1043 * value, rather than as a DLT_ value, we will assume this is AIX's
1044 * non-standard, incompatible libpcap, rather than a standard libpcap,
1045 * and will map the link-layer type to the standard DLT_ value for
1046 * that link-layer type, as that's what the rest of Wireshark expects.
1048 * (This means the capture files won't be readable by a tcpdump
1049 * linked with AIX's non-standard libpcap, but so it goes. They
1050 * *will* be readable by standard versions of tcpdump, Wireshark,
1053 * XXX - if we conclude we're using AIX libpcap, should we also
1054 * set a flag to cause us to assume the time stamps are in
1055 * seconds-and-nanoseconds form, and to convert them to
1056 * seconds-and-microseconds form before processing them and
1061 * Find the last component of the device name, which is the
1064 ifacename = strchr(devicename, '/');
1065 if (ifacename == NULL)
1066 ifacename = devicename;
1068 /* See if it matches any of the LAN device names. */
1069 if (strncmp(ifacename, "en", 2) == 0) {
1070 if (linktype == 6) {
1072 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
1076 } else if (strncmp(ifacename, "et", 2) == 0) {
1077 if (linktype == 7) {
1079 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
1080 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
1085 } else if (strncmp(ifacename, "tr", 2) == 0) {
1086 if (linktype == 9) {
1088 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
1089 * DLT_IEEE802, which is what's used for Token Ring.
1093 } else if (strncmp(ifacename, "fi", 2) == 0) {
1094 if (linktype == 15) {
1096 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
1100 } else if (strncmp(ifacename, "lo", 2) == 0) {
1101 if (linktype == 24) {
1103 * That's the RFC 1573 value for "software loopback" devices; map it
1104 * to DLT_NULL, which is what's used for loopback devices on BSD.
1114 static data_link_info_t *
1115 create_data_link_info(int dlt)
1117 data_link_info_t *data_link_info;
1120 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
1121 data_link_info->dlt = dlt;
1122 text = pcap_datalink_val_to_name(dlt);
1124 data_link_info->name = g_strdup(text);
1126 data_link_info->name = g_strdup_printf("DLT %d", dlt);
1127 text = pcap_datalink_val_to_description(dlt);
1129 data_link_info->description = g_strdup(text);
1131 data_link_info->description = NULL;
1132 return data_link_info;
1136 * Get the capabilities of a network device.
1138 static if_capabilities_t *
1139 get_if_capabilities(const char *devicename, gboolean monitor_mode
1140 #ifndef HAVE_PCAP_CREATE
1145 if_capabilities_t *caps;
1146 char errbuf[PCAP_ERRBUF_SIZE];
1148 #ifdef HAVE_PCAP_CREATE
1152 #ifdef HAVE_PCAP_LIST_DATALINKS
1156 data_link_info_t *data_link_info;
1159 * Allocate the interface capabilities structure.
1161 caps = (if_capabilities_t *)g_malloc(sizeof *caps);
1164 * WinPcap 4.1.2, and possibly earlier versions, have a bug
1165 * wherein, when an open with an rpcap: URL fails, the error
1166 * message for the error is not copied to errbuf and whatever
1167 * on-the-stack junk is in errbuf is treated as the error
1170 * To work around that (and any other bugs of that sort, we
1171 * initialize errbuf to an empty string. If we get an error
1172 * and the string is empty, we report it as an unknown error.
1173 * (If we *don't* get an error, and the string is *non*-empty,
1174 * that could be a warning returned, such as "can't turn
1175 * promiscuous mode on"; we currently don't do so.)
1178 #ifdef HAVE_PCAP_OPEN
1179 pch = pcap_open(devicename, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1180 caps->can_set_rfmon = FALSE;
1182 if (err_str != NULL)
1183 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1187 #elif defined(HAVE_PCAP_CREATE)
1188 pch = pcap_create(devicename, errbuf);
1190 if (err_str != NULL)
1191 *err_str = g_strdup(errbuf);
1195 status = pcap_can_set_rfmon(pch);
1198 if (status == PCAP_ERROR)
1199 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1202 *err_str = g_strdup(pcap_statustostr(status));
1208 caps->can_set_rfmon = FALSE;
1209 else if (status == 1) {
1210 caps->can_set_rfmon = TRUE;
1212 pcap_set_rfmon(pch, 1);
1214 if (err_str != NULL) {
1215 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1223 status = pcap_activate(pch);
1225 /* Error. We ignore warnings (status > 0). */
1226 if (err_str != NULL) {
1227 if (status == PCAP_ERROR)
1228 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1231 *err_str = g_strdup(pcap_statustostr(status));
1238 pch = pcap_open_live(devicename, MIN_PACKET_SIZE, 0, 0, errbuf);
1239 caps->can_set_rfmon = FALSE;
1241 if (err_str != NULL)
1242 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1247 deflt = get_pcap_linktype(pch, devicename);
1248 #ifdef HAVE_PCAP_LIST_DATALINKS
1249 nlt = pcap_list_datalinks(pch, &linktypes);
1250 if (nlt == 0 || linktypes == NULL) {
1252 if (err_str != NULL)
1253 *err_str = NULL; /* an empty list doesn't mean an error */
1257 caps->data_link_types = NULL;
1258 for (i = 0; i < nlt; i++) {
1259 data_link_info = create_data_link_info(linktypes[i]);
1262 * XXX - for 802.11, make the most detailed 802.11
1263 * version the default, rather than the one the
1264 * device has as the default?
1266 if (linktypes[i] == deflt)
1267 caps->data_link_types = g_list_prepend(caps->data_link_types,
1270 caps->data_link_types = g_list_append(caps->data_link_types,
1273 #ifdef HAVE_PCAP_FREE_DATALINKS
1274 pcap_free_datalinks(linktypes);
1277 * In Windows, there's no guarantee that if you have a library
1278 * built with one version of the MSVC++ run-time library, and
1279 * it returns a pointer to allocated data, you can free that
1280 * data from a program linked with another version of the
1281 * MSVC++ run-time library.
1283 * This is not an issue on UN*X.
1285 * See the mail threads starting at
1287 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1291 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1294 #define xx_free free /* hack so checkAPIs doesn't complain */
1297 #endif /* HAVE_PCAP_FREE_DATALINKS */
1298 #else /* HAVE_PCAP_LIST_DATALINKS */
1300 data_link_info = create_data_link_info(deflt);
1301 caps->data_link_types = g_list_append(caps->data_link_types,
1303 #endif /* HAVE_PCAP_LIST_DATALINKS */
1307 if (err_str != NULL)
1312 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1314 * Output a machine readable list of the interfaces
1315 * This list is retrieved by the sync_interface_list_open() function
1316 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
1319 print_machine_readable_interfaces(GList *if_list)
1326 char addr_str[ADDRSTRLEN];
1328 if (capture_child) {
1329 /* Let our parent know we succeeded. */
1330 pipe_write_block(2, SP_SUCCESS, NULL);
1333 i = 1; /* Interface id number */
1334 for (if_entry = g_list_first(if_list); if_entry != NULL;
1335 if_entry = g_list_next(if_entry)) {
1336 if_info = (if_info_t *)if_entry->data;
1337 printf("%d. %s\t", i++, if_info->name);
1340 * Print the contents of the if_entry struct in a parseable format.
1341 * Each if_entry element is tab-separated. Addresses are comma-
1344 /* XXX - Make sure our description doesn't contain a tab */
1345 if (if_info->vendor_description != NULL)
1346 printf("%s\t", if_info->vendor_description);
1350 /* XXX - Make sure our friendly name doesn't contain a tab */
1351 if (if_info->friendly_name != NULL)
1352 printf("%s\t", if_info->friendly_name);
1356 printf("%i\t", if_info->type);
1358 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1359 addr = g_slist_next(addr)) {
1360 if (addr != g_slist_nth(if_info->addrs, 0))
1363 if_addr = (if_addr_t *)addr->data;
1364 switch(if_addr->ifat_type) {
1366 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1368 printf("%s", addr_str);
1370 printf("<unknown IPv4>");
1374 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1375 addr_str, ADDRSTRLEN)) {
1376 printf("%s", addr_str);
1378 printf("<unknown IPv6>");
1382 printf("<type unknown %i>", if_addr->ifat_type);
1386 if (if_info->loopback)
1387 printf("\tloopback");
1389 printf("\tnetwork");
1396 * If you change the machine-readable output format of this function,
1397 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1400 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1403 data_link_info_t *data_link_info;
1404 const gchar *desc_str;
1406 if (capture_child) {
1407 /* Let our parent know we succeeded. */
1408 pipe_write_block(2, SP_SUCCESS, NULL);
1411 if (caps->can_set_rfmon)
1415 for (lt_entry = caps->data_link_types; lt_entry != NULL;
1416 lt_entry = g_list_next(lt_entry)) {
1417 data_link_info = (data_link_info_t *)lt_entry->data;
1418 if (data_link_info->description != NULL)
1419 desc_str = data_link_info->description;
1421 desc_str = "(not supported)";
1422 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1432 /* Print the number of packets captured for each interface until we're killed. */
1434 print_statistics_loop(gboolean machine_readable)
1436 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1442 char errbuf[PCAP_ERRBUF_SIZE];
1443 struct pcap_stat ps;
1445 if_list = get_interface_list(&err, &err_str);
1446 if (if_list == NULL) {
1448 case CANT_GET_INTERFACE_LIST:
1449 case DONT_HAVE_PCAP:
1450 cmdarg_err("%s", err_str);
1454 case NO_INTERFACES_FOUND:
1455 cmdarg_err("There are no interfaces on which a capture can be done");
1461 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1462 if_info = (if_info_t *)if_entry->data;
1463 #ifdef HAVE_PCAP_OPEN
1464 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1466 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1470 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1471 if_stat->name = g_strdup(if_info->name);
1473 stat_list = g_list_append(stat_list, if_stat);
1478 cmdarg_err("There are no interfaces on which a capture can be done");
1482 if (capture_child) {
1483 /* Let our parent know we succeeded. */
1484 pipe_write_block(2, SP_SUCCESS, NULL);
1487 if (!machine_readable) {
1488 printf("%-15s %10s %10s\n", "Interface", "Received",
1492 global_ld.go = TRUE;
1493 while (global_ld.go) {
1494 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1495 if_stat = (if_stat_t *)stat_entry->data;
1496 pcap_stats(if_stat->pch, &ps);
1498 if (!machine_readable) {
1499 printf("%-15s %10u %10u\n", if_stat->name,
1500 ps.ps_recv, ps.ps_drop);
1502 printf("%s\t%u\t%u\n", if_stat->name,
1503 ps.ps_recv, ps.ps_drop);
1508 /* If we have a dummy signal pipe check it */
1509 if (!signal_pipe_check_running()) {
1510 global_ld.go = FALSE;
1518 /* XXX - Not reached. Should we look for 'q' in stdin? */
1519 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1520 if_stat = (if_stat_t *)stat_entry->data;
1521 pcap_close(if_stat->pch);
1522 g_free(if_stat->name);
1525 g_list_free(stat_list);
1526 free_interface_list(if_list);
1534 capture_cleanup_handler(DWORD dwCtrlType)
1536 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1537 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1538 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1539 like SIGTERM at least when the machine's shutting down.
1541 For now, if we're running as a command rather than a capture child,
1542 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1543 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1544 in that way on UN*X.
1546 If we're not running as a capture child, we might be running as
1547 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1548 user logs out. (XXX - can we explicitly check whether we're
1549 running as a service?) */
1551 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1552 "Console: Control signal");
1553 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1554 "Console: Control signal, CtrlType: %u", dwCtrlType);
1556 /* Keep capture running if we're a service and a user logs off */
1557 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1558 capture_loop_stop();
1566 capture_cleanup_handler(int signum _U_)
1568 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1569 SIGTERM. We assume that if the user wanted it to keep running
1570 after they logged out, they'd have nohupped it. */
1572 /* Note: don't call g_log() in the signal handler: if we happened to be in
1573 * g_log() in process context when the signal came in, g_log will detect
1574 * the "recursion" and abort.
1577 capture_loop_stop();
1583 report_capture_count(gboolean reportit)
1585 /* Don't print this if we're a capture child. */
1586 if (!capture_child && reportit) {
1587 fprintf(stderr, "\rPackets captured: %u\n", global_ld.packet_count);
1588 /* stderr could be line buffered */
1596 report_counts_for_siginfo(void)
1598 report_capture_count(quiet);
1599 infoprint = FALSE; /* we just reported it */
1603 report_counts_siginfo(int signum _U_)
1605 int sav_errno = errno;
1607 /* If we've been told to delay printing, just set a flag asking
1608 that we print counts (if we're supposed to), otherwise print
1609 the count of packets captured (if we're supposed to). */
1613 report_counts_for_siginfo();
1616 #endif /* SIGINFO */
1619 exit_main(int status)
1622 /* Shutdown windows sockets */
1625 /* can be helpful for debugging */
1626 #ifdef DEBUG_DUMPCAP
1627 printf("Press any key\n");
1638 * If we were linked with libcap (not related to libpcap), make sure we have
1639 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1640 * (See comment in main() for details)
1643 relinquish_privs_except_capture(void)
1645 /* If 'started_with_special_privs' (ie: suid) then enable for
1646 * ourself the NET_ADMIN and NET_RAW capabilities and then
1647 * drop our suid privileges.
1649 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1650 * stuff we don't need (and shouldn't have).
1651 * CAP_NET_RAW: Packet capture (raw sockets).
1654 if (started_with_special_privs()) {
1655 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1656 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1658 cap_t caps = cap_init(); /* all capabilities initialized to off */
1660 print_caps("Pre drop, pre set");
1662 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1663 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1666 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1667 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1669 if (cap_set_proc(caps)) {
1670 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1672 print_caps("Pre drop, post set");
1674 relinquish_special_privs_perm();
1676 print_caps("Post drop, pre set");
1677 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1678 if (cap_set_proc(caps)) {
1679 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1681 print_caps("Post drop, post set");
1687 #endif /* HAVE_LIBCAP */
1689 /* Take care of byte order in the libpcap headers read from pipes.
1690 * (function taken from wiretap/libpcap.c) */
1692 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1695 /* Byte-swap the record header fields. */
1696 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1697 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1698 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1699 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1702 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1703 swapped, in order to match the BPF header layout.
1705 Unfortunately, some files were, according to a comment in the "libpcap"
1706 source, written with version 2.3 in their headers but without the
1707 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1708 would make no sense - we assume that we need to swap them. */
1709 if (hdr->version_major == 2 &&
1710 (hdr->version_minor < 3 ||
1711 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1714 temp = rechdr->orig_len;
1715 rechdr->orig_len = rechdr->incl_len;
1716 rechdr->incl_len = temp;
1720 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1724 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1728 return recv(pipe_fd, buf, (int)sz, 0);
1733 return ws_read(pipe_fd, buf, sz);
1739 * Thread function that reads from a pipe and pushes the data
1740 * to the main application thread.
1743 * XXX Right now we use async queues for basic signaling. The main thread
1744 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1745 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1746 * Iff the read is successful cap_pipe_read pushes an item onto
1747 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1748 * the queues themselves (yet).
1750 * We might want to move some of the cap_pipe_dispatch logic here so that
1751 * we can let cap_thread_read run independently, queuing up multiple reads
1752 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1754 static void *cap_thread_read(void *arg)
1756 pcap_options *pcap_opts;
1759 DWORD b, last_err, bytes_read;
1765 pcap_opts = (pcap_options *)arg;
1766 while (pcap_opts->cap_pipe_err == PIPOK) {
1767 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1768 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1770 while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1771 if ((pcap_opts->from_cap_socket)
1777 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1778 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1781 pcap_opts->cap_pipe_err = PIPEOF;
1785 pcap_opts->cap_pipe_err = PIPERR;
1796 /* If we try to use read() on a named pipe on Windows with partial
1797 * data it appears to return EOF.
1799 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1800 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1805 last_err = GetLastError();
1806 if (last_err == ERROR_MORE_DATA) {
1808 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1809 pcap_opts->cap_pipe_err = PIPEOF;
1813 pcap_opts->cap_pipe_err = PIPERR;
1816 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1817 pcap_opts->cap_pipe_err = PIPEOF;
1824 pcap_opts->cap_pipe_bytes_read = bytes_read;
1825 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1826 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1828 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1834 /* Provide select() functionality for a single file descriptor
1835 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1837 * Returns the same values as select.
1840 cap_pipe_select(int pipe_fd)
1843 struct timeval timeout;
1846 FD_SET(pipe_fd, &rfds);
1848 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1849 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1851 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1854 #define DEF_TCP_PORT 19000
1857 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1859 char *sockname = pipename + 4;
1860 struct sockaddr_in sa;
1867 memset(&sa, 0, sizeof(sa));
1869 p = strchr(sockname, ':');
1871 len = strlen(sockname);
1872 port = DEF_TCP_PORT;
1876 port = strtoul(p + 1, &p, 10);
1877 if (*p || port > 65535) {
1886 strncpy(buf, sockname, len);
1888 if (inet_pton(AF_INET, buf, &sa.sin_addr) <= 0) {
1892 sa.sin_family = AF_INET;
1893 sa.sin_port = htons((u_short)port);
1895 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1896 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1898 LPTSTR errorText = NULL;
1901 lastError = WSAGetLastError();
1902 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1903 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1904 FORMAT_MESSAGE_IGNORE_INSERTS,
1905 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1906 (LPTSTR)&errorText, 0, NULL);
1908 g_snprintf(errmsg, errmsgl,
1909 "The capture session could not be initiated due to the socket error: \n"
1911 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1913 LocalFree(errorText);
1915 " %d: %s", errno, strerror(errno));
1917 pcap_opts->cap_pipe_err = PIPERR;
1920 cap_pipe_close(fd, TRUE);
1924 pcap_opts->from_cap_socket = TRUE;
1928 g_snprintf(errmsg, errmsgl,
1929 "The capture session could not be initiated because\n"
1930 "\"%s\" is not a valid socket specification", pipename);
1931 pcap_opts->cap_pipe_err = PIPERR;
1935 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1939 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1943 closesocket(pipe_fd);
1950 /* Mimic pcap_open_live() for pipe captures
1952 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1953 * open it, and read the header.
1955 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1956 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1958 cap_pipe_open_live(char *pipename,
1959 pcap_options *pcap_opts,
1960 struct pcap_hdr *hdr,
1961 char *errmsg, int errmsgl)
1964 ws_statb64 pipe_stat;
1965 struct sockaddr_un sa;
1971 int fd = -1, sel_ret;
1975 pcap_opts->cap_pipe_fd = -1;
1977 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1979 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1982 * XXX - this blocks until a pcap per-file header has been written to
1983 * the pipe, so it could block indefinitely.
1985 if (strcmp(pipename, "-") == 0) {
1987 fd = 0; /* read from stdin */
1989 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1991 } else if (!strncmp(pipename, "TCP@", 4)) {
1992 if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
1997 if (ws_stat64(pipename, &pipe_stat) < 0) {
1998 if (errno == ENOENT || errno == ENOTDIR)
1999 pcap_opts->cap_pipe_err = PIPNEXIST;
2001 g_snprintf(errmsg, errmsgl,
2002 "The capture session could not be initiated "
2003 "due to error getting information on pipe/socket: %s", g_strerror(errno));
2004 pcap_opts->cap_pipe_err = PIPERR;
2008 if (S_ISFIFO(pipe_stat.st_mode)) {
2009 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
2011 g_snprintf(errmsg, errmsgl,
2012 "The capture session could not be initiated "
2013 "due to error on pipe open: %s", g_strerror(errno));
2014 pcap_opts->cap_pipe_err = PIPERR;
2017 } else if (S_ISSOCK(pipe_stat.st_mode)) {
2018 fd = socket(AF_UNIX, SOCK_STREAM, 0);
2020 g_snprintf(errmsg, errmsgl,
2021 "The capture session could not be initiated "
2022 "due to error on socket create: %s", g_strerror(errno));
2023 pcap_opts->cap_pipe_err = PIPERR;
2026 sa.sun_family = AF_UNIX;
2028 * The Single UNIX Specification says:
2030 * The size of sun_path has intentionally been left undefined.
2031 * This is because different implementations use different sizes.
2032 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
2033 * of 104. Since most implementations originate from BSD versions,
2034 * the size is typically in the range 92 to 108.
2036 * Applications should not assume a particular length for sun_path
2037 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
2041 * The <sys/un.h> header shall define the sockaddr_un structure,
2042 * which shall include at least the following members:
2044 * sa_family_t sun_family Address family.
2045 * char sun_path[] Socket pathname.
2047 * so we assume that it's an array, with a specified size,
2048 * and that the size reflects the maximum path length.
2050 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
2051 /* Path name too long */
2052 g_snprintf(errmsg, errmsgl,
2053 "The capture session coud not be initiated "
2054 "due to error on socket connect: Path name too long");
2055 pcap_opts->cap_pipe_err = PIPERR;
2059 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
2061 g_snprintf(errmsg, errmsgl,
2062 "The capture session coud not be initiated "
2063 "due to error on socket connect: %s", g_strerror(errno));
2064 pcap_opts->cap_pipe_err = PIPERR;
2069 if (S_ISCHR(pipe_stat.st_mode)) {
2071 * Assume the user specified an interface on a system where
2072 * interfaces are in /dev. Pretend we haven't seen it.
2074 pcap_opts->cap_pipe_err = PIPNEXIST;
2076 g_snprintf(errmsg, errmsgl,
2077 "The capture session could not be initiated because\n"
2078 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
2079 pcap_opts->cap_pipe_err = PIPERR;
2084 #define PIPE_STR "\\pipe\\"
2085 /* Under Windows, named pipes _must_ have the form
2086 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
2088 pncopy = g_strdup(pipename);
2089 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
2090 pos = strchr(pncopy + 3, '\\');
2091 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
2098 g_snprintf(errmsg, errmsgl,
2099 "The capture session could not be initiated because\n"
2100 "\"%s\" is neither an interface nor a pipe", pipename);
2101 pcap_opts->cap_pipe_err = PIPNEXIST;
2105 /* Wait for the pipe to appear */
2107 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
2108 OPEN_EXISTING, 0, NULL);
2110 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
2113 if (GetLastError() != ERROR_PIPE_BUSY) {
2114 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2115 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2116 g_snprintf(errmsg, errmsgl,
2117 "The capture session on \"%s\" could not be started "
2118 "due to error on pipe open: %s (error %d)",
2119 pipename, utf_16to8(err_str), GetLastError());
2121 pcap_opts->cap_pipe_err = PIPERR;
2125 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
2126 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2127 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2128 g_snprintf(errmsg, errmsgl,
2129 "The capture session on \"%s\" timed out during "
2130 "pipe open: %s (error %d)",
2131 pipename, utf_16to8(err_str), GetLastError());
2133 pcap_opts->cap_pipe_err = PIPERR;
2140 pcap_opts->from_cap_pipe = TRUE;
2143 if (pcap_opts->from_cap_socket)
2146 /* read the pcap header */
2148 while (bytes_read < sizeof magic) {
2150 g_snprintf(errmsg, errmsgl, "Invalid file descriptor");
2154 sel_ret = cap_pipe_select(fd);
2156 g_snprintf(errmsg, errmsgl,
2157 "Unexpected error from select: %s", g_strerror(errno));
2159 } else if (sel_ret > 0) {
2160 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
2161 sizeof magic-bytes_read,
2162 pcap_opts->from_cap_socket);
2165 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2167 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2177 #if GLIB_CHECK_VERSION(2,31,0)
2178 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
2180 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
2183 pcap_opts->cap_pipe_buf = (char *) &magic;
2184 pcap_opts->cap_pipe_bytes_read = 0;
2185 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
2186 /* We don't have to worry about cap_pipe_read_mtx here */
2187 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2188 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2189 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2190 if (pcap_opts->cap_pipe_bytes_read == 0)
2191 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2193 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2202 case PCAP_NSEC_MAGIC:
2203 /* Host that wrote it has our byte order, and was running
2204 a program using either standard or ss990417 libpcap. */
2205 pcap_opts->cap_pipe_byte_swapped = FALSE;
2206 pcap_opts->cap_pipe_modified = FALSE;
2207 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
2209 case PCAP_MODIFIED_MAGIC:
2210 /* Host that wrote it has our byte order, but was running
2211 a program using either ss990915 or ss991029 libpcap. */
2212 pcap_opts->cap_pipe_byte_swapped = FALSE;
2213 pcap_opts->cap_pipe_modified = TRUE;
2215 case PCAP_SWAPPED_MAGIC:
2216 case PCAP_SWAPPED_NSEC_MAGIC:
2217 /* Host that wrote it has a byte order opposite to ours,
2218 and was running a program using either standard or
2219 ss990417 libpcap. */
2220 pcap_opts->cap_pipe_byte_swapped = TRUE;
2221 pcap_opts->cap_pipe_modified = FALSE;
2222 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2224 case PCAP_SWAPPED_MODIFIED_MAGIC:
2225 /* Host that wrote it out has a byte order opposite to
2226 ours, and was running a program using either ss990915
2227 or ss991029 libpcap. */
2228 pcap_opts->cap_pipe_byte_swapped = TRUE;
2229 pcap_opts->cap_pipe_modified = TRUE;
2232 /* Not a "libpcap" type we know about. */
2233 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2238 if (pcap_opts->from_cap_socket)
2241 /* Read the rest of the header */
2243 while (bytes_read < sizeof(struct pcap_hdr)) {
2244 sel_ret = cap_pipe_select(fd);
2246 g_snprintf(errmsg, errmsgl,
2247 "Unexpected error from select: %s", g_strerror(errno));
2249 } else if (sel_ret > 0) {
2250 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2251 sizeof(struct pcap_hdr) - bytes_read,
2252 pcap_opts->from_cap_socket);
2255 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2257 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
2267 pcap_opts->cap_pipe_buf = (char *) hdr;
2268 pcap_opts->cap_pipe_bytes_read = 0;
2269 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
2270 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2271 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2272 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2273 if (pcap_opts->cap_pipe_bytes_read == 0)
2274 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2276 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
2283 if (pcap_opts->cap_pipe_byte_swapped) {
2284 /* Byte-swap the header fields about which we care. */
2285 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
2286 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
2287 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
2288 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
2290 pcap_opts->linktype = hdr->network;
2292 if (hdr->version_major < 2) {
2293 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2297 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2298 pcap_opts->cap_pipe_err = PIPOK;
2299 pcap_opts->cap_pipe_fd = fd;
2303 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2304 pcap_opts->cap_pipe_err = PIPERR;
2305 cap_pipe_close(fd, pcap_opts->from_cap_socket);
2306 pcap_opts->cap_pipe_fd = -1;
2310 /* We read one record from the pipe, take care of byte order in the record
2311 * header, write the record to the capture file, and update capture statistics. */
2313 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2315 struct pcap_pkthdr phdr;
2316 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2319 #if !GLIB_CHECK_VERSION(2,31,18)
2327 #ifdef LOG_CAPTURE_VERBOSE
2328 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2331 switch (pcap_opts->cap_pipe_state) {
2333 case STATE_EXPECT_REC_HDR:
2335 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2338 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2339 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2340 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2341 pcap_opts->cap_pipe_bytes_read = 0;
2344 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2345 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2346 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2351 case STATE_READ_REC_HDR:
2353 if (pcap_opts->from_cap_socket)
2356 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2357 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
2360 result = PD_PIPE_EOF;
2362 result = PD_PIPE_ERR;
2365 pcap_opts->cap_pipe_bytes_read += b;
2369 #if GLIB_CHECK_VERSION(2,31,18)
2370 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2372 g_get_current_time(&wait_time);
2373 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2374 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2376 if (pcap_opts->cap_pipe_err == PIPEOF) {
2377 result = PD_PIPE_EOF;
2379 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2380 result = PD_PIPE_ERR;
2388 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2390 result = PD_REC_HDR_READ;
2393 case STATE_EXPECT_DATA:
2395 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2398 pcap_opts->cap_pipe_state = STATE_READ_DATA;
2399 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2400 pcap_opts->cap_pipe_bytes_read = 0;
2403 pcap_opts->cap_pipe_buf = (char *) data;
2404 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2405 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2410 case STATE_READ_DATA:
2412 if (pcap_opts->from_cap_socket)
2415 b = cap_pipe_read(pcap_opts->cap_pipe_fd,
2416 data+pcap_opts->cap_pipe_bytes_read,
2417 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
2418 pcap_opts->from_cap_socket);
2421 result = PD_PIPE_EOF;
2423 result = PD_PIPE_ERR;
2426 pcap_opts->cap_pipe_bytes_read += b;
2431 #if GLIB_CHECK_VERSION(2,31,18)
2432 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2434 g_get_current_time(&wait_time);
2435 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2436 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2437 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2438 if (pcap_opts->cap_pipe_err == PIPEOF) {
2439 result = PD_PIPE_EOF;
2441 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2442 result = PD_PIPE_ERR;
2450 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2452 result = PD_DATA_READ;
2456 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2459 } /* switch (pcap_opts->cap_pipe_state) */
2462 * We've now read as much data as we were expecting, so process it.
2466 case PD_REC_HDR_READ:
2467 /* We've read the header. Take care of byte order. */
2468 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2469 &pcap_opts->cap_pipe_rechdr.hdr);
2470 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2471 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2472 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2476 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2477 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2480 /* no data to read? fall through */
2483 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2484 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2485 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2486 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2487 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2490 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2492 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2494 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2498 pcap_opts->cap_pipe_err = PIPEOF;
2503 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2504 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2505 g_snprintf(errmsg, errmsgl,
2506 "Error reading from pipe: %s (error %d)",
2507 utf_16to8(err_str), GetLastError());
2510 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2518 pcap_opts->cap_pipe_err = PIPERR;
2519 /* Return here rather than inside the switch to prevent GCC warning */
2524 /** Open the capture input file (pcap or capture pipe).
2525 * Returns TRUE if it succeeds, FALSE otherwise. */
2527 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2528 char *errmsg, size_t errmsg_len,
2529 char *secondary_errmsg, size_t secondary_errmsg_len)
2531 gchar open_err_str[PCAP_ERRBUF_SIZE];
2532 gchar *sync_msg_str;
2533 interface_options interface_opts;
2534 pcap_options *pcap_opts;
2538 gchar *sync_secondary_msg_str;
2539 WORD wVersionRequested;
2543 /* XXX - opening Winsock on tshark? */
2545 /* Initialize Windows Socket if we are in a WIN32 OS
2546 This needs to be done before querying the interface for network/netmask */
2548 /* XXX - do we really require 1.1 or earlier?
2549 Are there any versions that support only 2.0 or higher? */
2550 wVersionRequested = MAKEWORD(1, 1);
2551 err = WSAStartup(wVersionRequested, &wsaData);
2555 case WSASYSNOTREADY:
2556 g_snprintf(errmsg, (gulong) errmsg_len,
2557 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2560 case WSAVERNOTSUPPORTED:
2561 g_snprintf(errmsg, (gulong) errmsg_len,
2562 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2563 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2566 case WSAEINPROGRESS:
2567 g_snprintf(errmsg, (gulong) errmsg_len,
2568 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2572 g_snprintf(errmsg, (gulong) errmsg_len,
2573 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2577 g_snprintf(errmsg, (gulong) errmsg_len,
2578 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2582 g_snprintf(errmsg, (gulong) errmsg_len,
2583 "Couldn't initialize Windows Sockets: error %d", err);
2586 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2590 if ((use_threads == FALSE) &&
2591 (capture_opts->ifaces->len > 1)) {
2592 g_snprintf(errmsg, (gulong) errmsg_len,
2593 "Using threads is required for capturing on multiple interfaces!");
2597 for (i = 0; i < capture_opts->ifaces->len; i++) {
2598 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2599 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2600 if (pcap_opts == NULL) {
2601 g_snprintf(errmsg, (gulong) errmsg_len,
2602 "Could not allocate memory.");
2605 pcap_opts->received = 0;
2606 pcap_opts->dropped = 0;
2607 pcap_opts->flushed = 0;
2608 pcap_opts->pcap_h = NULL;
2609 #ifdef MUST_DO_SELECT
2610 pcap_opts->pcap_fd = -1;
2612 pcap_opts->pcap_err = FALSE;
2613 pcap_opts->interface_id = i;
2614 pcap_opts->tid = NULL;
2615 pcap_opts->snaplen = 0;
2616 pcap_opts->linktype = -1;
2617 pcap_opts->ts_nsec = FALSE;
2618 pcap_opts->from_cap_pipe = FALSE;
2619 pcap_opts->from_cap_socket = FALSE;
2620 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2621 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2623 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2625 pcap_opts->cap_pipe_fd = -1;
2626 pcap_opts->cap_pipe_modified = FALSE;
2627 pcap_opts->cap_pipe_byte_swapped = FALSE;
2629 pcap_opts->cap_pipe_buf = NULL;
2631 pcap_opts->cap_pipe_bytes_to_read = 0;
2632 pcap_opts->cap_pipe_bytes_read = 0;
2633 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2634 pcap_opts->cap_pipe_err = PIPOK;
2636 #if GLIB_CHECK_VERSION(2,31,0)
2637 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2638 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2640 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2642 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2643 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2645 g_array_append_val(ld->pcaps, pcap_opts);
2647 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2648 pcap_opts->pcap_h = open_capture_device(&interface_opts, &open_err_str);
2650 if (pcap_opts->pcap_h != NULL) {
2651 /* we've opened "iface" as a network device */
2653 /* try to set the capture buffer size */
2654 if (interface_opts.buffer_size > 1 &&
2655 pcap_setbuff(pcap_opts->pcap_h, interface_opts.buffer_size * 1024 * 1024) != 0) {
2656 sync_secondary_msg_str = g_strdup_printf(
2657 "The capture buffer size of %d MiB seems to be too high for your machine,\n"
2658 "the default of %d MiB will be used.\n"
2660 "Nonetheless, the capture is started.\n",
2661 interface_opts.buffer_size, DEFAULT_CAPTURE_BUFFER_SIZE);
2662 report_capture_error("Couldn't set the capture buffer size!",
2663 sync_secondary_msg_str);
2664 g_free(sync_secondary_msg_str);
2668 #if defined(HAVE_PCAP_SETSAMPLING)
2669 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2670 struct pcap_samp *samp;
2672 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2673 switch (interface_opts.sampling_method) {
2674 case CAPTURE_SAMP_BY_COUNT:
2675 samp->method = PCAP_SAMP_1_EVERY_N;
2678 case CAPTURE_SAMP_BY_TIMER:
2679 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2683 sync_msg_str = g_strdup_printf(
2684 "Unknown sampling method %d specified,\n"
2685 "continue without packet sampling",
2686 interface_opts.sampling_method);
2687 report_capture_error("Couldn't set the capture "
2688 "sampling", sync_msg_str);
2689 g_free(sync_msg_str);
2691 samp->value = interface_opts.sampling_param;
2693 report_capture_error("Couldn't set the capture sampling",
2694 "Cannot get packet sampling data structure");
2699 /* setting the data link type only works on real interfaces */
2700 if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2702 secondary_errmsg, secondary_errmsg_len)) {
2705 pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2707 /* We couldn't open "iface" as a network device. */
2708 /* Try to open it as a pipe */
2709 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2712 if (pcap_opts->cap_pipe_fd == -1) {
2714 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2716 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2717 /* Pipe doesn't exist, so output message for interface */
2718 get_capture_device_open_failure_messages(open_err_str,
2719 interface_opts.name,
2723 secondary_errmsg_len);
2726 * Else pipe (or file) does exist and cap_pipe_open_live() has
2731 /* cap_pipe_open_live() succeeded; don't want
2732 error message from pcap_open_live() */
2733 open_err_str[0] = '\0';
2737 /* XXX - will this work for tshark? */
2738 #ifdef MUST_DO_SELECT
2739 if (!pcap_opts->from_cap_pipe) {
2740 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2741 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2743 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2748 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2749 returned a warning; print it, but keep capturing. */
2750 if (open_err_str[0] != '\0') {
2751 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2752 report_capture_error(sync_msg_str, "");
2753 g_free(sync_msg_str);
2755 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2756 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2759 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2760 /* to remove any suid privileges. */
2761 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2762 /* (euid/egid have already previously been set to ruid/rgid. */
2763 /* (See comment in main() for details) */
2765 relinquish_special_privs_perm();
2767 relinquish_all_capabilities();
2772 /* close the capture input file (pcap or capture pipe) */
2773 static void capture_loop_close_input(loop_data *ld)
2776 pcap_options *pcap_opts;
2778 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2780 for (i = 0; i < ld->pcaps->len; i++) {
2781 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2782 /* if open, close the capture pipe "input file" */
2783 if (pcap_opts->cap_pipe_fd >= 0) {
2784 g_assert(pcap_opts->from_cap_pipe);
2785 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2786 pcap_opts->cap_pipe_fd = -1;
2789 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2790 CloseHandle(pcap_opts->cap_pipe_h);
2791 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2794 /* if open, close the pcap "input file" */
2795 if (pcap_opts->pcap_h != NULL) {
2796 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2797 pcap_close(pcap_opts->pcap_h);
2798 pcap_opts->pcap_h = NULL;
2805 /* Shut down windows sockets */
2811 /* init the capture filter */
2812 static initfilter_status_t
2813 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2814 const gchar * name, const gchar * cfilter)
2816 struct bpf_program fcode;
2818 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2820 /* capture filters only work on real interfaces */
2821 if (cfilter && !from_cap_pipe) {
2822 /* A capture filter was specified; set it up. */
2823 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2824 /* Treat this specially - our caller might try to compile this
2825 as a display filter and, if that succeeds, warn the user that
2826 the display and capture filter syntaxes are different. */
2827 return INITFILTER_BAD_FILTER;
2829 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2830 #ifdef HAVE_PCAP_FREECODE
2831 pcap_freecode(&fcode);
2833 return INITFILTER_OTHER_ERROR;
2835 #ifdef HAVE_PCAP_FREECODE
2836 pcap_freecode(&fcode);
2840 return INITFILTER_NO_ERROR;
2844 /* set up to write to the already-opened capture output file/files */
2846 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2850 pcap_options *pcap_opts;
2851 interface_options interface_opts;
2852 gboolean successful;
2854 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2856 if ((capture_opts->use_pcapng == FALSE) &&
2857 (capture_opts->ifaces->len > 1)) {
2858 g_snprintf(errmsg, errmsg_len,
2859 "Using PCAPNG is required for capturing on multiple interfaces! Use the -n option.");
2863 /* Set up to write to the capture file. */
2864 if (capture_opts->multi_files_on) {
2865 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2867 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2868 if (ld->pdh == NULL) {
2873 if (capture_opts->use_pcapng) {
2875 GString *os_info_str;
2877 os_info_str = g_string_new("");
2878 get_os_version_info(os_info_str);
2880 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_gitversion);
2881 successful = pcapng_write_session_header_block(ld->pdh,
2882 (const char *)capture_opts->capture_comment, /* Comment*/
2884 os_info_str->str, /* OS*/
2886 -1, /* section_length */
2890 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2891 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2892 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2893 if (pcap_opts->from_cap_pipe) {
2894 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2896 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2898 successful = pcapng_write_interface_description_block(global_ld.pdh,
2899 NULL, /* OPT_COMMENT 1 */
2900 interface_opts.name, /* IDB_NAME 2 */
2901 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2902 interface_opts.cfilter, /* IDB_FILTER 11 */
2903 os_info_str->str, /* IDB_OS 12 */
2904 pcap_opts->linktype,
2906 &(global_ld.bytes_written),
2907 0, /* IDB_IF_SPEED 8 */
2908 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2912 g_string_free(os_info_str, TRUE);
2915 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2916 if (pcap_opts->from_cap_pipe) {
2917 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2919 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2921 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2922 pcap_opts->ts_nsec, &ld->bytes_written, &err);
2930 if (ld->pdh == NULL) {
2931 /* We couldn't set up to write to the capture file. */
2932 /* XXX - use cf_open_error_message from tshark instead? */
2937 g_snprintf(errmsg, errmsg_len,
2938 "The file to which the capture would be"
2939 " saved (\"%s\") could not be opened: Error %d.",
2940 capture_opts->save_file, err);
2942 g_snprintf(errmsg, errmsg_len,
2943 "The file to which the capture would be"
2944 " saved (\"%s\") could not be opened: %s.",
2945 capture_opts->save_file, g_strerror(err));
2957 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2961 pcap_options *pcap_opts;
2962 guint64 end_time = create_timestamp();
2964 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2966 if (capture_opts->multi_files_on) {
2967 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2969 if (capture_opts->use_pcapng) {
2970 for (i = 0; i < global_ld.pcaps->len; i++) {
2971 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2972 if (!pcap_opts->from_cap_pipe) {
2973 guint64 isb_ifrecv, isb_ifdrop;
2974 struct pcap_stat stats;
2976 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
2977 isb_ifrecv = pcap_opts->received;
2978 isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
2980 isb_ifrecv = G_MAXUINT64;
2981 isb_ifdrop = G_MAXUINT64;
2983 pcapng_write_interface_statistics_block(ld->pdh,
2986 "Counters provided by dumpcap",
2995 if (fclose(ld->pdh) == EOF) {
2996 if (err_close != NULL) {
3006 /* dispatch incoming packets (pcap or capture pipe)
3008 * Waits for incoming packets to be available, and calls pcap_dispatch()
3009 * to cause them to be processed.
3011 * Returns the number of packets which were processed.
3013 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3014 * packet-batching behaviour does not cause packets to get held back
3018 capture_loop_dispatch(loop_data *ld,
3019 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
3022 gint packet_count_before;
3023 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
3028 packet_count_before = ld->packet_count;
3029 if (pcap_opts->from_cap_pipe) {
3030 /* dispatch from capture pipe */
3031 #ifdef LOG_CAPTURE_VERBOSE
3032 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3035 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
3037 if (sel_ret < 0 && errno != EINTR) {
3038 g_snprintf(errmsg, errmsg_len,
3039 "Unexpected error from select: %s", g_strerror(errno));
3040 report_capture_error(errmsg, please_report);
3045 * "select()" says we can read from the pipe without blocking
3048 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
3058 /* dispatch from pcap */
3059 #ifdef MUST_DO_SELECT
3061 * If we have "pcap_get_selectable_fd()", we use it to get the
3062 * descriptor on which to select; if that's -1, it means there
3063 * is no descriptor on which you can do a "select()" (perhaps
3064 * because you're capturing on a special device, and that device's
3065 * driver unfortunately doesn't support "select()", in which case
3066 * we don't do the select - which means it might not be possible
3067 * to stop a capture until a packet arrives. If that's unacceptable,
3068 * plead with whoever supplies the software for that device to add
3069 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3070 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3071 * later, so it can use pcap_breakloop().
3073 #ifdef LOG_CAPTURE_VERBOSE
3074 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3076 if (pcap_opts->pcap_fd != -1) {
3077 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
3080 * "select()" says we can read from it without blocking; go for
3083 * We don't have pcap_breakloop(), so we only process one packet
3084 * per pcap_dispatch() call, to allow a signal to stop the
3085 * processing immediately, rather than processing all packets
3086 * in a batch before quitting.
3089 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3091 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3095 /* Error, rather than pcap_breakloop(). */
3096 pcap_opts->pcap_err = TRUE;
3098 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3101 if (sel_ret < 0 && errno != EINTR) {
3102 g_snprintf(errmsg, errmsg_len,
3103 "Unexpected error from select: %s", g_strerror(errno));
3104 report_capture_error(errmsg, please_report);
3110 #endif /* MUST_DO_SELECT */
3112 /* dispatch from pcap without select */
3114 #ifdef LOG_CAPTURE_VERBOSE
3115 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3119 * On Windows, we don't support asynchronously telling a process to
3120 * stop capturing; instead, we check for an indication on a pipe
3121 * after processing packets. We therefore process only one packet
3122 * at a time, so that we can check the pipe after every packet.
3125 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3127 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3131 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3133 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3138 /* Error, rather than pcap_breakloop(). */
3139 pcap_opts->pcap_err = TRUE;
3141 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3143 #else /* pcap_next_ex */
3144 #ifdef LOG_CAPTURE_VERBOSE
3145 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3147 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3150 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3151 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
3152 * This should be fixed in the WinPcap 4.0 alpha release.
3154 * For reference, an example remote interface:
3155 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3158 /* emulate dispatch from pcap */
3161 struct pcap_pkthdr *pkt_header;
3166 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
3168 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3170 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3175 pcap_opts->pcap_err = TRUE;
3179 #endif /* pcap_next_ex */
3183 #ifdef LOG_CAPTURE_VERBOSE
3184 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3187 return ld->packet_count - packet_count_before;
3191 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3192 * want to grab only the characters between the '{' and '}' delimiters.
3194 * Returns a GString that must be freed with g_string_free(). */
3196 isolate_uuid(const char *iface)
3201 ptr = strchr(iface, '{');
3203 return g_string_new(iface);
3204 gstr = g_string_new(ptr + 1);
3206 ptr = strchr(gstr->str, '}');
3210 gstr = g_string_truncate(gstr, ptr - gstr->str);
3215 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3216 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3218 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3219 char *errmsg, int errmsg_len)
3222 gchar *capfile_name;
3224 gboolean is_tempfile;
3226 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3227 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3229 if (capture_opts->save_file != NULL) {
3230 /* We return to the caller while the capture is in progress.
3231 * Therefore we need to take a copy of save_file in
3232 * case the caller destroys it after we return.
3234 capfile_name = g_strdup(capture_opts->save_file);
3236 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3237 if (capture_opts->multi_files_on) {
3238 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3239 g_snprintf(errmsg, errmsg_len,
3240 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3241 g_free(capfile_name);
3244 if (strcmp(capfile_name, "-") == 0) {
3245 /* write to stdout */
3248 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3249 _setmode(1, O_BINARY);
3252 } /* if (...output_to_pipe ... */
3255 if (capture_opts->multi_files_on) {
3256 /* ringbuffer is enabled */
3257 *save_file_fd = ringbuf_init(capfile_name,
3258 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3259 capture_opts->group_read_access);
3261 /* we need the ringbuf name */
3262 if (*save_file_fd != -1) {
3263 g_free(capfile_name);
3264 capfile_name = g_strdup(ringbuf_current_filename());
3267 /* Try to open/create the specified file for use as a capture buffer. */
3268 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
3269 (capture_opts->group_read_access) ? 0640 : 0600);
3272 is_tempfile = FALSE;
3274 /* Choose a random name for the temporary capture buffer */
3275 if (global_capture_opts.ifaces->len > 1) {
3276 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3279 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
3281 /* use the generic portion of the interface guid to form the basis of the filename */
3282 if (strncmp("NPF_{", basename, 5)==0)
3284 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3286 iface = isolate_uuid(basename);
3288 basename = g_strdup(iface->str);
3289 g_string_free(iface, TRUE);
3292 /* generate the temp file name prefix...
3293 * It would be nice if we could specify a pcapng/pcap filename suffix,
3294 * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
3295 if (capture_opts->use_pcapng) {
3296 prefix = g_strconcat("wireshark_pcapng_", basename, NULL);
3298 prefix = g_strconcat("wireshark_pcap_", basename, NULL);
3302 *save_file_fd = create_tempfile(&tmpname, prefix);
3304 capfile_name = g_strdup(tmpname);
3308 /* did we fail to open the output file? */
3309 if (*save_file_fd == -1) {
3311 g_snprintf(errmsg, errmsg_len,
3312 "The temporary file to which the capture would be saved (\"%s\") "
3313 "could not be opened: %s.", capfile_name, g_strerror(errno));
3315 if (capture_opts->multi_files_on) {
3316 ringbuf_error_cleanup();
3319 g_snprintf(errmsg, errmsg_len,
3320 "The file to which the capture would be saved (\"%s\") "
3321 "could not be opened: %s.", capfile_name,
3324 g_free(capfile_name);
3328 if (capture_opts->save_file != NULL) {
3329 g_free(capture_opts->save_file);
3331 capture_opts->save_file = capfile_name;
3332 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3333 "g_free(capfile_name)". */
3339 /* Do the work of handling either the file size or file duration capture
3340 conditions being reached, and switching files or stopping. */
3342 do_file_switch_or_stop(capture_options *capture_opts,
3343 condition *cnd_autostop_files,
3344 condition *cnd_autostop_size,
3345 condition *cnd_file_duration)
3348 pcap_options *pcap_opts;
3349 interface_options interface_opts;
3350 gboolean successful;
3352 if (capture_opts->multi_files_on) {
3353 if (cnd_autostop_files != NULL &&
3354 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
3355 /* no files left: stop here */
3356 global_ld.go = FALSE;
3360 /* Switch to the next ringbuffer file */
3361 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3362 &global_ld.save_file_fd, &global_ld.err)) {
3364 /* File switch succeeded: reset the conditions */
3365 global_ld.bytes_written = 0;
3366 if (capture_opts->use_pcapng) {
3368 GString *os_info_str;
3370 os_info_str = g_string_new("");
3371 get_os_version_info(os_info_str);
3373 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_gitversion);
3374 successful = pcapng_write_session_header_block(global_ld.pdh,
3377 os_info_str->str, /* OS */
3379 -1, /* section_length */
3380 &(global_ld.bytes_written),
3383 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3384 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3385 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3386 successful = pcapng_write_interface_description_block(global_ld.pdh,
3387 NULL, /* OPT_COMMENT 1 */
3388 interface_opts.name, /* IDB_NAME 2 */
3389 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3390 interface_opts.cfilter, /* IDB_FILTER 11 */
3391 os_info_str->str, /* IDB_OS 12 */
3392 pcap_opts->linktype,
3394 &(global_ld.bytes_written),
3395 0, /* IDB_IF_SPEED 8 */
3396 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3400 g_string_free(os_info_str, TRUE);
3403 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3404 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3405 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3408 fclose(global_ld.pdh);
3409 global_ld.pdh = NULL;
3410 global_ld.go = FALSE;
3413 if (cnd_autostop_size)
3414 cnd_reset(cnd_autostop_size);
3415 if (cnd_file_duration)
3416 cnd_reset(cnd_file_duration);
3417 fflush(global_ld.pdh);
3419 report_packet_count(global_ld.inpkts_to_sync_pipe);
3420 global_ld.inpkts_to_sync_pipe = 0;
3421 report_new_capture_file(capture_opts->save_file);
3423 /* File switch failed: stop here */
3424 global_ld.go = FALSE;
3428 /* single file, stop now */
3429 global_ld.go = FALSE;
3436 pcap_read_handler(void* arg)
3438 pcap_options *pcap_opts;
3439 char errmsg[MSG_MAX_LENGTH+1];
3441 pcap_opts = (pcap_options *)arg;
3443 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3444 pcap_opts->interface_id);
3446 while (global_ld.go) {
3447 /* dispatch incoming packets */
3448 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3450 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3451 pcap_opts->interface_id);
3452 g_thread_exit(NULL);
3456 /* Do the low-level work of a capture.
3457 Returns TRUE if it succeeds, FALSE otherwise. */
3459 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3462 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3464 struct timeval upd_time, cur_time;
3468 condition *cnd_file_duration = NULL;
3469 condition *cnd_autostop_files = NULL;
3470 condition *cnd_autostop_size = NULL;
3471 condition *cnd_autostop_duration = NULL;
3474 gboolean cfilter_error = FALSE;
3475 char errmsg[MSG_MAX_LENGTH+1];
3476 char secondary_errmsg[MSG_MAX_LENGTH+1];
3477 pcap_options *pcap_opts;
3478 interface_options interface_opts;
3479 guint i, error_index = 0;
3482 *secondary_errmsg = '\0';
3484 /* init the loop data */
3485 global_ld.go = TRUE;
3486 global_ld.packet_count = 0;
3488 global_ld.report_packet_count = FALSE;
3490 if (capture_opts->has_autostop_packets)
3491 global_ld.packet_max = capture_opts->autostop_packets;
3493 global_ld.packet_max = 0; /* no limit */
3494 global_ld.inpkts_to_sync_pipe = 0;
3495 global_ld.err = 0; /* no error seen yet */
3496 global_ld.pdh = NULL;
3497 global_ld.autostop_files = 0;
3498 global_ld.save_file_fd = -1;
3500 /* We haven't yet gotten the capture statistics. */
3501 *stats_known = FALSE;
3503 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3504 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3506 /* open the "input file" from network interface or capture pipe */
3507 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3508 secondary_errmsg, sizeof(secondary_errmsg))) {
3511 for (i = 0; i < capture_opts->ifaces->len; i++) {
3512 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3513 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3514 /* init the input filter from the network interface (capture pipe will do nothing) */
3516 * When remote capturing WinPCap crashes when the capture filter
3517 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3520 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3521 interface_opts.name,
3522 interface_opts.cfilter?interface_opts.cfilter:"")) {
3524 case INITFILTER_NO_ERROR:
3527 case INITFILTER_BAD_FILTER:
3528 cfilter_error = TRUE;
3530 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3533 case INITFILTER_OTHER_ERROR:
3534 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3535 pcap_geterr(pcap_opts->pcap_h));
3536 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3541 /* If we're supposed to write to a capture file, open it for output
3542 (temporary/specified name/ringbuffer) */
3543 if (capture_opts->saving_to_file) {
3544 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3545 errmsg, sizeof(errmsg))) {
3549 /* set up to write to the already-opened capture output file/files */
3550 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3555 /* XXX - capture SIGTERM and close the capture, in case we're on a
3556 Linux 2.0[.x] system and you have to explicitly close the capture
3557 stream in order to turn promiscuous mode off? We need to do that
3558 in other places as well - and I don't think that works all the
3559 time in any case, due to libpcap bugs. */
3561 /* Well, we should be able to start capturing.
3563 Sync out the capture file, so the header makes it to the file system,
3564 and send a "capture started successfully and capture file created"
3565 message to our parent so that they'll open the capture file and
3566 update its windows to indicate that we have a live capture in
3568 fflush(global_ld.pdh);
3569 report_new_capture_file(capture_opts->save_file);
3572 /* initialize capture stop (and alike) conditions */
3573 init_capture_stop_conditions();
3574 /* create stop conditions */
3575 if (capture_opts->has_autostop_filesize) {
3576 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3577 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3580 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3582 if (capture_opts->has_autostop_duration)
3583 cnd_autostop_duration =
3584 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3586 if (capture_opts->multi_files_on) {
3587 if (capture_opts->has_file_duration)
3589 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3591 if (capture_opts->has_autostop_files)
3592 cnd_autostop_files =
3593 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3596 /* init the time values */
3598 upd_time = GetTickCount();
3600 gettimeofday(&upd_time, NULL);
3602 start_time = create_timestamp();
3603 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
3605 /* WOW, everything is prepared! */
3606 /* please fasten your seat belts, we will enter now the actual capture loop */
3608 pcap_queue = g_async_queue_new();
3609 pcap_queue_bytes = 0;
3610 pcap_queue_packets = 0;
3611 for (i = 0; i < global_ld.pcaps->len; i++) {
3612 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3613 #if GLIB_CHECK_VERSION(2,31,0)
3614 /* XXX - Add an interface name here? */
3615 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3617 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3621 while (global_ld.go) {
3622 /* dispatch incoming packets */
3624 pcap_queue_element *queue_element;
3625 #if GLIB_CHECK_VERSION(2,31,18)
3627 g_async_queue_lock(pcap_queue);
3628 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3630 GTimeVal write_thread_time;
3632 g_get_current_time(&write_thread_time);
3633 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3634 g_async_queue_lock(pcap_queue);
3635 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3637 if (queue_element) {
3638 pcap_queue_bytes -= queue_element->phdr.caplen;
3639 pcap_queue_packets -= 1;
3641 g_async_queue_unlock(pcap_queue);
3642 if (queue_element) {
3643 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3644 "Dequeued a packet of length %d captured on interface %d.",
3645 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3647 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3648 &queue_element->phdr,
3650 g_free(queue_element->pd);
3651 g_free(queue_element);
3657 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3658 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3659 sizeof(errmsg), pcap_opts);
3662 /* Were we asked to print packet counts by the SIGINFO handler? */
3663 if (global_ld.report_packet_count) {
3664 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3665 plurality(global_ld.packet_count, "", "s"));
3666 global_ld.report_packet_count = FALSE;
3671 /* any news from our parent (signal pipe)? -> just stop the capture */
3672 if (!signal_pipe_check_running()) {
3673 global_ld.go = FALSE;
3678 global_ld.inpkts_to_sync_pipe += inpkts;
3680 /* check capture size condition */
3681 if (cnd_autostop_size != NULL &&
3682 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3683 /* Capture size limit reached, do we have another file? */
3684 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3685 cnd_autostop_size, cnd_file_duration))
3687 } /* cnd_autostop_size */
3688 if (capture_opts->output_to_pipe) {
3689 fflush(global_ld.pdh);
3693 /* Only update once every 500ms so as not to overload slow displays.
3694 * This also prevents too much context-switching between the dumpcap
3695 * and wireshark processes.
3697 #define DUMPCAP_UPD_TIME 500
3700 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3701 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3703 gettimeofday(&cur_time, NULL);
3704 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3705 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3708 upd_time = cur_time;
3711 if (pcap_stats(pch, stats) >= 0) {
3712 *stats_known = TRUE;
3715 /* Let the parent process know. */
3716 if (global_ld.inpkts_to_sync_pipe) {
3718 fflush(global_ld.pdh);
3720 /* Send our parent a message saying we've written out
3721 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3723 report_packet_count(global_ld.inpkts_to_sync_pipe);
3725 global_ld.inpkts_to_sync_pipe = 0;
3728 /* check capture duration condition */
3729 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3730 /* The maximum capture time has elapsed; stop the capture. */
3731 global_ld.go = FALSE;
3735 /* check capture file duration condition */
3736 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3737 /* duration limit reached, do we have another file? */
3738 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3739 cnd_autostop_size, cnd_file_duration))
3741 } /* cnd_file_duration */
3745 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3747 pcap_queue_element *queue_element;
3749 for (i = 0; i < global_ld.pcaps->len; i++) {
3750 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3751 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3752 pcap_opts->interface_id);
3753 g_thread_join(pcap_opts->tid);
3754 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3755 pcap_opts->interface_id);
3758 g_async_queue_lock(pcap_queue);
3759 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3760 if (queue_element) {
3761 pcap_queue_bytes -= queue_element->phdr.caplen;
3762 pcap_queue_packets -= 1;
3764 g_async_queue_unlock(pcap_queue);
3765 if (queue_element == NULL) {
3768 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3769 "Dequeued a packet of length %d captured on interface %d.",
3770 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3771 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3772 &queue_element->phdr,
3774 g_free(queue_element->pd);
3775 g_free(queue_element);
3776 global_ld.inpkts_to_sync_pipe += 1;
3777 if (capture_opts->output_to_pipe) {
3778 fflush(global_ld.pdh);
3784 /* delete stop conditions */
3785 if (cnd_file_duration != NULL)
3786 cnd_delete(cnd_file_duration);
3787 if (cnd_autostop_files != NULL)
3788 cnd_delete(cnd_autostop_files);
3789 if (cnd_autostop_size != NULL)
3790 cnd_delete(cnd_autostop_size);
3791 if (cnd_autostop_duration != NULL)
3792 cnd_delete(cnd_autostop_duration);
3794 /* did we have a pcap (input) error? */
3795 for (i = 0; i < capture_opts->ifaces->len; i++) {
3796 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3797 if (pcap_opts->pcap_err) {
3798 /* On Linux, if an interface goes down while you're capturing on it,
3799 you'll get a "recvfrom: Network is down" or
3800 "The interface went down" error (ENETDOWN).
3801 (At least you will if g_strerror() doesn't show a local translation
3804 On FreeBSD and OS X, if a network adapter disappears while
3805 you're capturing on it, you'll get a "read: Device not configured"
3806 error (ENXIO). (See previous parenthetical note.)
3808 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3810 These should *not* be reported to the Wireshark developers. */
3813 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3814 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3815 strcmp(cap_err_str, "The interface went down") == 0 ||
3816 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3817 strcmp(cap_err_str, "read: I/O error") == 0 ||
3818 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3819 report_capture_error("The network adapter on which the capture was being done "
3820 "is no longer running; the capture has stopped.",
3823 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3825 report_capture_error(errmsg, please_report);
3828 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3829 report_capture_error(errmsg, "");
3833 /* did we have an output error while capturing? */
3834 if (global_ld.err == 0) {
3837 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3838 global_ld.err, FALSE);
3839 report_capture_error(errmsg, please_report);
3843 if (capture_opts->saving_to_file) {
3844 /* close the output file */
3845 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3849 /* there might be packets not yet notified to the parent */
3850 /* (do this after closing the file, so all packets are already flushed) */
3851 if (global_ld.inpkts_to_sync_pipe) {
3853 report_packet_count(global_ld.inpkts_to_sync_pipe);
3854 global_ld.inpkts_to_sync_pipe = 0;
3857 /* If we've displayed a message about a write error, there's no point
3858 in displaying another message about an error on close. */
3859 if (!close_ok && write_ok) {
3860 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3862 report_capture_error(errmsg, "");
3866 * XXX We exhibit different behaviour between normal mode and sync mode
3867 * when the pipe is stdin and not already at EOF. If we're a child, the
3868 * parent's stdin isn't closed, so if the user starts another capture,
3869 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3870 * will say "Unrecognized libpcap format". On the other hand, in normal
3871 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3874 report_capture_count(TRUE);
3876 /* get packet drop statistics from pcap */
3877 for (i = 0; i < capture_opts->ifaces->len; i++) {
3879 guint32 pcap_dropped = 0;
3881 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3882 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3883 received = pcap_opts->received;
3884 if (pcap_opts->pcap_h != NULL) {
3885 g_assert(!pcap_opts->from_cap_pipe);
3886 /* Get the capture statistics, so we know how many packets were dropped. */
3888 * Older versions of libpcap didn't set ps_ifdrop on some
3889 * platforms; initialize it to 0 to handle that.
3891 stats->ps_ifdrop = 0;
3892 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3893 *stats_known = TRUE;
3894 /* Let the parent process know. */
3895 pcap_dropped += stats->ps_drop;
3897 g_snprintf(errmsg, sizeof(errmsg),
3898 "Can't get packet-drop statistics: %s",
3899 pcap_geterr(pcap_opts->pcap_h));
3900 report_capture_error(errmsg, please_report);
3903 report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
3906 /* close the input file (pcap or capture pipe) */
3907 capture_loop_close_input(&global_ld);
3909 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3911 /* ok, if the write and the close were successful. */
3912 return write_ok && close_ok;
3915 if (capture_opts->multi_files_on) {
3916 /* cleanup ringbuffer */
3917 ringbuf_error_cleanup();
3919 /* We can't use the save file, and we have no FILE * for the stream
3920 to close in order to close it, so close the FD directly. */
3921 if (global_ld.save_file_fd != -1) {
3922 ws_close(global_ld.save_file_fd);
3925 /* We couldn't even start the capture, so get rid of the capture
3927 if (capture_opts->save_file != NULL) {
3928 ws_unlink(capture_opts->save_file);
3929 g_free(capture_opts->save_file);
3932 capture_opts->save_file = NULL;
3934 report_cfilter_error(capture_opts, error_index, errmsg);
3936 report_capture_error(errmsg, secondary_errmsg);
3938 /* close the input file (pcap or cap_pipe) */
3939 capture_loop_close_input(&global_ld);
3941 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3948 capture_loop_stop(void)
3950 #ifdef HAVE_PCAP_BREAKLOOP
3952 pcap_options *pcap_opts;
3954 for (i = 0; i < global_ld.pcaps->len; i++) {
3955 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3956 if (pcap_opts->pcap_h != NULL)
3957 pcap_breakloop(pcap_opts->pcap_h);
3960 global_ld.go = FALSE;
3965 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3966 int err, gboolean is_close)
3971 g_snprintf(errmsg, errmsglen,
3972 "Not all the packets could be written to the file"
3973 " to which the capture was being saved\n"
3974 "(\"%s\") because there is no space left on the file system\n"
3975 "on which that file resides.",
3981 g_snprintf(errmsg, errmsglen,
3982 "Not all the packets could be written to the file"
3983 " to which the capture was being saved\n"
3984 "(\"%s\") because you are too close to, or over,"
3985 " your disk quota\n"
3986 "on the file system on which that file resides.",
3993 g_snprintf(errmsg, errmsglen,
3994 "The file to which the capture was being saved\n"
3995 "(\"%s\") could not be closed: %s.",
3996 fname, g_strerror(err));
3998 g_snprintf(errmsg, errmsglen,
3999 "An error occurred while writing to the file"
4000 " to which the capture was being saved\n"
4002 fname, g_strerror(err));
4009 /* one packet was captured, process it */
4011 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4014 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4016 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
4018 /* We may be called multiple times from pcap_dispatch(); if we've set
4019 the "stop capturing" flag, ignore this packet, as we're not
4020 supposed to be saving any more packets. */
4021 if (!global_ld.go) {
4022 pcap_opts->flushed++;
4026 if (global_ld.pdh) {
4027 gboolean successful;
4029 /* We're supposed to write the packet to a file; do so.
4030 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4031 "ld->err" to the error. */
4032 if (global_capture_opts.use_pcapng) {
4033 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4035 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4036 phdr->caplen, phdr->len,
4037 pcap_opts->interface_id,
4040 &global_ld.bytes_written, &err);
4042 successful = libpcap_write_packet(global_ld.pdh,
4043 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4044 phdr->caplen, phdr->len,
4046 &global_ld.bytes_written, &err);
4049 global_ld.go = FALSE;
4050 global_ld.err = err;
4051 pcap_opts->dropped++;
4053 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4054 "Wrote a packet of length %d captured on interface %u.",
4055 phdr->caplen, pcap_opts->interface_id);
4056 global_ld.packet_count++;
4057 pcap_opts->received++;
4058 /* if the user told us to stop after x packets, do we already have enough? */
4059 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4060 global_ld.go = FALSE;
4066 /* one packet was captured, queue it */
4068 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4071 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4072 pcap_queue_element *queue_element;
4073 gboolean limit_reached;
4075 /* We may be called multiple times from pcap_dispatch(); if we've set
4076 the "stop capturing" flag, ignore this packet, as we're not
4077 supposed to be saving any more packets. */
4078 if (!global_ld.go) {
4079 pcap_opts->flushed++;
4083 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4084 if (queue_element == NULL) {
4085 pcap_opts->dropped++;
4088 queue_element->pcap_opts = pcap_opts;
4089 queue_element->phdr = *phdr;
4090 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4091 if (queue_element->pd == NULL) {
4092 pcap_opts->dropped++;
4093 g_free(queue_element);
4096 memcpy(queue_element->pd, pd, phdr->caplen);
4097 g_async_queue_lock(pcap_queue);
4098 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4099 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4100 limit_reached = FALSE;
4101 g_async_queue_push_unlocked(pcap_queue, queue_element);
4102 pcap_queue_bytes += phdr->caplen;
4103 pcap_queue_packets += 1;
4105 limit_reached = TRUE;
4107 g_async_queue_unlock(pcap_queue);
4108 if (limit_reached) {
4109 pcap_opts->dropped++;
4110 g_free(queue_element->pd);
4111 g_free(queue_element);
4112 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4113 "Dropped a packet of length %d captured on interface %u.",
4114 phdr->caplen, pcap_opts->interface_id);
4116 pcap_opts->received++;
4117 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4118 "Queued a packet of length %d captured on interface %u.",
4119 phdr->caplen, pcap_opts->interface_id);
4121 /* I don't want to hold the mutex over the debug output. So the
4122 output may be wrong */
4123 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4124 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4125 pcap_queue_bytes, pcap_queue_packets);
4129 set_80211_channel(const char *iface, const char *opt)
4131 int freq = 0, type, ret;
4132 gchar **options = NULL;
4134 options = g_strsplit_set(opt, ",", 2);
4137 freq = atoi(options[0]);
4140 type = ws80211_str_to_chan_type(options[1]);
4149 ret = ws80211_init();
4151 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4155 ret = ws80211_set_freq(iface, freq, type);
4158 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4164 pipe_write_block(2, SP_SUCCESS, NULL);
4168 g_strfreev(options);
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 struct option long_options[] = {
4180 {(char *)"capture-comment", required_argument, NULL, LONGOPT_NUM_CAP_COMMENT },
4184 gboolean arg_error = FALSE;
4189 struct sigaction action, oldaction;
4192 gboolean start_capture = TRUE;
4193 gboolean stats_known;
4194 struct pcap_stat stats;
4195 GLogLevelFlags log_flags;
4196 gboolean list_interfaces = FALSE;
4197 gboolean list_link_layer_types = FALSE;
4198 #ifdef HAVE_BPF_IMAGE
4199 gboolean print_bpf_code = FALSE;
4201 gboolean set_chan = FALSE;
4202 gchar *set_chan_arg = NULL;
4203 gboolean machine_readable = FALSE;
4204 gboolean print_statistics = FALSE;
4205 int status, run_once_args = 0;
4208 #if defined(__APPLE__) && defined(__LP64__)
4209 struct utsname osinfo;
4213 /* Assemble the compile-time version information string */
4214 comp_info_str = g_string_new("Compiled ");
4215 get_compiled_version_info(comp_info_str, NULL, NULL);
4217 /* Assemble the run-time version information string */
4218 runtime_info_str = g_string_new("Running ");
4219 get_runtime_version_info(runtime_info_str, NULL);
4221 /* Add it to the information to be reported on a crash. */
4222 ws_add_crash_info("Dumpcap " VERSION "%s\n"
4227 wireshark_gitversion, comp_info_str->str, runtime_info_str->str);
4230 arg_list_utf_16to8(argc, argv);
4231 create_app_running_mutex();
4234 * Initialize our DLL search path. MUST be called before LoadLibrary
4237 ws_init_dll_search_path();
4240 #ifdef HAVE_PCAP_REMOTE
4241 #define OPTSTRING_A "A:"
4242 #define OPTSTRING_r "r"
4243 #define OPTSTRING_u "u"
4245 #define OPTSTRING_A ""
4246 #define OPTSTRING_r ""
4247 #define OPTSTRING_u ""
4250 #ifdef HAVE_PCAP_SETSAMPLING
4251 #define OPTSTRING_m "m:"
4253 #define OPTSTRING_m ""
4256 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4257 #define OPTSTRING_B "B:"
4259 #define OPTSTRING_B ""
4260 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4262 #ifdef HAVE_PCAP_CREATE
4263 #define OPTSTRING_I "I"
4265 #define OPTSTRING_I ""
4268 #ifdef HAVE_BPF_IMAGE
4269 #define OPTSTRING_d "d"
4271 #define OPTSTRING_d ""
4274 #define OPTSTRING "a:" OPTSTRING_A "b:" OPTSTRING_B "C:c:" OPTSTRING_d "Df:ghi:" OPTSTRING_I "k:L" OPTSTRING_m "MN:npPq" OPTSTRING_r "Ss:t" OPTSTRING_u "vw:y:Z:"
4276 #ifdef DEBUG_CHILD_DUMPCAP
4277 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4278 fprintf (stderr, "Unable to open debug log file !\n");
4283 #if defined(__APPLE__) && defined(__LP64__)
4285 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4286 * a bug workaround - timeouts less than 1 second don't work with libpcap
4287 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4288 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4289 * The problem is extremely unlikely to be reintroduced in a future
4292 if (uname(&osinfo) == 0) {
4294 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
4295 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4296 * number of 10.0.0, not 10.1.0 - go figure).
4298 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4299 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4300 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4301 need_timeout_workaround = TRUE;
4306 * Determine if dumpcap is being requested to run in a special
4307 * capture_child mode by going thru the command line args to see if
4308 * a -Z is present. (-Z is a hidden option).
4310 * The primary result of running in capture_child mode is that
4311 * all messages sent out on stderr are in a special type/len/string
4312 * format to allow message processing by type. These messages include
4313 * error messages if dumpcap fails to start the operation it was
4314 * requested to do, as well as various "status" messages which are sent
4315 * when an actual capture is in progress, and a "success" message sent
4316 * if dumpcap was requested to perform an operation other than a
4319 * Capture_child mode would normally be requested by a parent process
4320 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4321 * to which dumpcap stderr has been redirected. It might also have
4322 * another pipe to obtain dumpcap stdout output; for operations other
4323 * than a capture, that information is formatted specially for easier
4324 * parsing by the parent process.
4326 * Capture_child mode needs to be determined immediately upon
4327 * startup so that any messages generated by dumpcap in this mode
4328 * (eg: during initialization) will be formatted properly.
4331 for (i=1; i<argc; i++) {
4332 if (strcmp("-Z", argv[i]) == 0) {
4333 capture_child = TRUE;
4334 machine_readable = TRUE; /* request machine-readable output */
4336 /* set output pipe to binary mode, to avoid ugly text conversions */
4337 _setmode(2, O_BINARY);
4342 /* The default_log_handler will use stdout, which makes trouble in */
4343 /* capture child mode, as it uses stdout for its sync_pipe. */
4344 /* So: the filtering is done in the console_log_handler and not here.*/
4345 /* We set the log handlers right up front to make sure that any log */
4346 /* messages when running as child will be sent back to the parent */
4347 /* with the correct format. */
4352 G_LOG_LEVEL_CRITICAL|
4353 G_LOG_LEVEL_WARNING|
4354 G_LOG_LEVEL_MESSAGE|
4358 G_LOG_FLAG_RECURSION);
4360 g_log_set_handler(NULL,
4362 console_log_handler, NULL /* user_data */);
4363 g_log_set_handler(LOG_DOMAIN_MAIN,
4365 console_log_handler, NULL /* user_data */);
4366 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4368 console_log_handler, NULL /* user_data */);
4369 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4371 console_log_handler, NULL /* user_data */);
4373 /* Initialize the pcaps list */
4374 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
4376 #if !GLIB_CHECK_VERSION(2,31,0)
4377 /* Initialize the thread system */
4378 g_thread_init(NULL);
4382 /* Load wpcap if possible. Do this before collecting the run-time version information */
4385 /* ... and also load the packet.dll from wpcap */
4386 /* XXX - currently not required, may change later. */
4387 /*wpcap_packet_load();*/
4389 /* Start windows sockets */
4390 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4392 /* Set handler for Ctrl+C key */
4393 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4395 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4396 and exit. Do the same with SIGPIPE, in case, for example,
4397 we're writing to our standard output and it's a pipe.
4398 Do the same with SIGHUP if it's not being ignored (if we're
4399 being run under nohup, it might be ignored, in which case we
4400 should leave it ignored).
4402 XXX - apparently, Coverity complained that part of action
4403 wasn't initialized. Perhaps it's running on Linux, where
4404 struct sigaction has an ignored "sa_restorer" element and
4405 where "sa_handler" and "sa_sigaction" might not be two
4406 members of a union. */
4407 memset(&action, 0, sizeof(action));
4408 action.sa_handler = capture_cleanup_handler;
4410 * Arrange that system calls not get restarted, because when
4411 * our signal handler returns we don't want to restart
4412 * a call that was waiting for packets to arrive.
4414 action.sa_flags = 0;
4415 sigemptyset(&action.sa_mask);
4416 sigaction(SIGTERM, &action, NULL);
4417 sigaction(SIGINT, &action, NULL);
4418 sigaction(SIGPIPE, &action, NULL);
4419 sigaction(SIGHUP, NULL, &oldaction);
4420 if (oldaction.sa_handler == SIG_DFL)
4421 sigaction(SIGHUP, &action, NULL);
4424 /* Catch SIGINFO and, if we get it and we're capturing in
4425 quiet mode, report the number of packets we've captured. */
4426 action.sa_handler = report_counts_siginfo;
4427 action.sa_flags = SA_RESTART;
4428 sigemptyset(&action.sa_mask);
4429 sigaction(SIGINFO, &action, NULL);
4430 #endif /* SIGINFO */
4434 enable_kernel_bpf_jit_compiler();
4437 /* ----------------------------------------------------------------- */
4438 /* Privilege and capability handling */
4440 /* 1. Running not as root or suid root; no special capabilities. */
4443 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4446 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4448 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4449 /* capabilities; Drop all other capabilities; */
4450 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4451 /* else: after pcap_open_live() in capture_loop_open_input() */
4452 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4453 /* (Note: this means that the process, although logged in */
4454 /* as root, does not have various permissions such as the */
4455 /* ability to bypass file access permissions). */
4456 /* XXX: Should we just leave capabilities alone in this case */
4457 /* so that user gets expected effect that root can do */
4460 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
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 suid root (set euid=ruid).(ie: keep suid until after */
4465 /* pcap_open_live). */
4467 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4469 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4470 /* capabilities; Drop all other capabilities; */
4471 /* Drop suid privileges (euid=ruid); */
4472 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4473 /* else: after pcap_open_live() in capture_loop_open_input() */
4474 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4476 /* XXX: For some Linux versions/distros with capabilities */
4477 /* a 'normal' process with any capabilities cannot be */
4478 /* 'killed' (signaled) from another (same uid) non-privileged */
4480 /* For example: If (non-suid) Wireshark forks a */
4481 /* child suid dumpcap which acts as described here (case 5), */
4482 /* Wireshark will be unable to kill (signal) the child */
4483 /* dumpcap process until the capabilities have been dropped */
4484 /* (after pcap_open_live()). */
4485 /* This behaviour will apparently be changed in the kernel */
4486 /* to allow the kill (signal) in this case. */
4487 /* See the following for details: */
4488 /* http://www.mail-archive.com/ [wrapped] */
4489 /* linux-security-module@vger.kernel.org/msg02913.html */
4491 /* It is therefore conceivable that if dumpcap somehow hangs */
4492 /* in pcap_open_live or before that wireshark will not */
4493 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4494 /* In this case, exiting wireshark will kill the child */
4495 /* dumpcap process. */
4497 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4498 /* capabilities; Using libcap. Note: capset cmd (which see) */
4499 /* used to assign capabilities to file. */
4501 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4502 /* else: after pcap_open_live() in capture_loop_open_input() */
4503 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4505 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4506 /* longer required (similar to capture). */
4508 /* ----------------------------------------------------------------- */
4510 init_process_policies();
4513 /* If 'started with special privileges' (and using libcap) */
4514 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4515 /* Set euid/egid = ruid/rgid to remove suid privileges */
4516 relinquish_privs_except_capture();
4519 /* Set the initial values in the capture options. This might be overwritten
4520 by the command line parameters. */
4521 capture_opts_init(&global_capture_opts);
4523 /* We always save to a file - if no file was specified, we save to a
4525 global_capture_opts.saving_to_file = TRUE;
4526 global_capture_opts.has_ring_num_files = TRUE;
4528 /* Pass on capture_child mode for capture_opts */
4529 global_capture_opts.capture_child = capture_child;
4531 /* Now get our args */
4532 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4534 case 'h': /* Print help and exit */
4538 case 'v': /* Show version and exit */
4540 show_version(comp_info_str, runtime_info_str);
4541 g_string_free(comp_info_str, TRUE);
4542 g_string_free(runtime_info_str, TRUE);
4546 /*** capture option specific ***/
4547 case 'a': /* autostop criteria */
4548 case 'b': /* Ringbuffer option */
4549 case 'c': /* Capture x packets */
4550 case 'f': /* capture filter */
4551 case 'g': /* enable group read access on file(s) */
4552 case 'i': /* Use interface x */
4553 case 'n': /* Use pcapng format */
4554 case 'p': /* Don't capture in promiscuous mode */
4555 case 'P': /* Use pcap format */
4556 case 's': /* Set the snapshot (capture) length */
4557 case 'w': /* Write to capture file x */
4558 case 'y': /* Set the pcap data link type */
4559 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4560 #ifdef HAVE_PCAP_REMOTE
4561 case 'u': /* Use UDP for data transfer */
4562 case 'r': /* Capture own RPCAP traffic too */
4563 case 'A': /* Authentication */
4565 #ifdef HAVE_PCAP_SETSAMPLING
4566 case 'm': /* Sampling */
4568 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4569 case 'B': /* Buffer size */
4570 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4571 #ifdef HAVE_PCAP_CREATE
4572 case 'I': /* Monitor mode */
4574 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4579 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4581 capture_child = TRUE;
4583 /* set output pipe to binary mode, to avoid ugly text conversions */
4584 _setmode(2, O_BINARY);
4586 * optarg = the control ID, aka the PPID, currently used for the
4589 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4590 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4591 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4592 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4594 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4595 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4596 "Signal pipe: Unable to open %s. Dead parent?",
4604 case 'q': /* Quiet */
4610 /*** all non capture option specific ***/
4611 case 'D': /* Print a list of capture devices and exit */
4612 list_interfaces = TRUE;
4615 case 'L': /* Print list of link-layer types and exit */
4616 list_link_layer_types = TRUE;
4619 #ifdef HAVE_BPF_IMAGE
4620 case 'd': /* Print BPF code for capture filter and exit */
4621 print_bpf_code = TRUE;
4625 case 'S': /* Print interface statistics once a second */
4626 print_statistics = TRUE;
4629 case 'k': /* Set wireless channel */
4631 set_chan_arg = optarg;
4634 case 'M': /* For -D, -L, and -S, print machine-readable output */
4635 machine_readable = TRUE;
4638 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4641 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4644 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4646 case '?': /* Bad flag - print usage message */
4655 /* user specified file name as regular command-line argument */
4656 /* XXX - use it as the capture file name (or something else)? */
4662 * Extra command line arguments were specified; complain.
4663 * XXX - interpret as capture filter, as tcpdump and tshark do?
4665 cmdarg_err("Invalid argument: %s", argv[0]);
4670 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4673 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4674 /* Use some default if the user hasn't specified some */
4675 /* XXX: Are these defaults good enough? */
4676 pcap_queue_byte_limit = 1000 * 1000;
4677 pcap_queue_packet_limit = 1000;
4684 if (run_once_args > 1) {
4685 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4687 } else if (run_once_args == 1) {
4688 /* We're supposed to print some information, rather than
4689 to capture traffic; did they specify a ring buffer option? */
4690 if (global_capture_opts.multi_files_on) {
4691 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4695 /* We're supposed to capture traffic; */
4697 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4698 if (global_capture_opts.ifaces->len > 1) {
4700 global_capture_opts.use_pcapng = TRUE;
4703 if (global_capture_opts.capture_comment &&
4704 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4705 /* XXX - for ringbuffer, should we apply the comment to each file? */
4706 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4710 /* Was the ring buffer option specified and, if so, does it make sense? */
4711 if (global_capture_opts.multi_files_on) {
4712 /* Ring buffer works only under certain conditions:
4713 a) ring buffer does not work with temporary files;
4714 b) it makes no sense to enable the ring buffer if the maximum
4715 file size is set to "infinite". */
4716 if (global_capture_opts.save_file == NULL) {
4717 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4718 global_capture_opts.multi_files_on = FALSE;
4720 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4721 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4723 /* XXX - this must be redesigned as the conditions changed */
4724 global_capture_opts.multi_files_on = FALSE;
4731 * "-D" requires no interface to be selected; it's supposed to list
4734 if (list_interfaces) {
4735 /* Get the list of interfaces */
4740 if_list = capture_interface_list(&err, &err_str,NULL);
4741 if (if_list == NULL) {
4743 case CANT_GET_INTERFACE_LIST:
4744 case DONT_HAVE_PCAP:
4745 cmdarg_err("%s", err_str);
4750 case NO_INTERFACES_FOUND:
4752 * If we're being run by another program, just give them
4753 * an empty list of interfaces, don't report this as
4754 * an error; that lets them decide whether to report
4755 * this as an error or not.
4757 if (!machine_readable) {
4758 cmdarg_err("There are no interfaces on which a capture can be done");
4765 if (machine_readable) /* tab-separated values to stdout */
4766 print_machine_readable_interfaces(if_list);
4768 capture_opts_print_interfaces(if_list);
4769 free_interface_list(if_list);
4774 * "-S" requires no interface to be selected; it gives statistics
4775 * for all interfaces.
4777 if (print_statistics) {
4778 status = print_statistics_loop(machine_readable);
4783 interface_options interface_opts;
4785 if (global_capture_opts.ifaces->len != 1) {
4786 cmdarg_err("Need one interface");
4790 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4791 status = set_80211_channel(interface_opts.name, set_chan_arg);
4796 * "-L", "-d", and capturing act on a particular interface, so we have to
4797 * have an interface; if none was specified, pick a default.
4799 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4801 /* cmdarg_err() already called .... */
4805 /* Let the user know what interfaces were chosen. */
4806 if (capture_child) {
4807 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4808 interface_options interface_opts;
4810 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4811 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4812 interface_opts.name);
4815 str = g_string_new("");
4817 if (global_capture_opts.ifaces->len < 2)
4819 if (global_capture_opts.ifaces->len < 4)
4822 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4823 interface_options interface_opts;
4825 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4827 if (global_capture_opts.ifaces->len > 2) {
4828 g_string_append_printf(str, ",");
4830 g_string_append_printf(str, " ");
4831 if (j == global_capture_opts.ifaces->len - 1) {
4832 g_string_append_printf(str, "and ");
4835 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4838 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4840 fprintf(stderr, "Capturing on %s\n", str->str);
4841 g_string_free(str, TRUE);
4844 if (list_link_layer_types) {
4845 /* Get the list of link-layer types for the capture device. */
4846 if_capabilities_t *caps;
4850 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4851 interface_options interface_opts;
4853 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4854 caps = get_if_capabilities(interface_opts.name,
4855 interface_opts.monitor_mode, &err_str);
4857 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4858 "Please check to make sure you have sufficient permissions, and that\n"
4859 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4863 if (caps->data_link_types == NULL) {
4864 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4867 if (machine_readable) /* tab-separated values to stdout */
4868 /* XXX: We need to change the format and adopt consumers */
4869 print_machine_readable_if_capabilities(caps);
4871 /* XXX: We might want to print also the interface name */
4872 capture_opts_print_if_capabilities(caps, interface_opts.name,
4873 interface_opts.monitor_mode);
4874 free_if_capabilities(caps);
4879 /* We're supposed to do a capture, or print the BPF code for a filter.
4880 Process the snapshot length, as that affects the generated BPF code. */
4881 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4883 #ifdef HAVE_BPF_IMAGE
4884 if (print_bpf_code) {
4885 show_filter_code(&global_capture_opts);
4890 /* We're supposed to do a capture. Process the ring buffer arguments. */
4891 capture_opts_trim_ring_num_files(&global_capture_opts);
4893 /* flush stderr prior to starting the main capture loop */
4896 /* Now start the capture. */
4898 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4902 /* capture failed */
4905 return 0; /* never here, make compiler happy */
4910 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4911 const char *message, gpointer user_data _U_)
4918 /* ignore log message, if log_level isn't interesting */
4919 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4920 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4925 /* create a "timestamp" */
4927 today = localtime(&curr);
4929 switch(log_level & G_LOG_LEVEL_MASK) {
4930 case G_LOG_LEVEL_ERROR:
4933 case G_LOG_LEVEL_CRITICAL:
4936 case G_LOG_LEVEL_WARNING:
4939 case G_LOG_LEVEL_MESSAGE:
4942 case G_LOG_LEVEL_INFO:
4945 case G_LOG_LEVEL_DEBUG:
4949 fprintf(stderr, "unknown log_level %u\n", log_level);
4951 g_assert_not_reached();
4954 /* Generate the output message */
4955 if (log_level & G_LOG_LEVEL_MESSAGE) {
4956 /* normal user messages without additional infos */
4957 msg = g_strdup_printf("%s\n", message);
4959 /* info/debug messages with additional infos */
4960 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4961 today->tm_hour, today->tm_min, today->tm_sec,
4962 log_domain != NULL ? log_domain : "",
4966 /* DEBUG & INFO msgs (if we're debugging today) */
4967 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4968 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4969 #ifdef DEBUG_DUMPCAP
4970 fprintf(stderr, "%s", msg);
4973 #ifdef DEBUG_CHILD_DUMPCAP
4974 fprintf(debug_log, "%s", msg);
4982 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4983 /* to parent especially formatted if dumpcap running as child. */
4984 if (capture_child) {
4985 sync_pipe_errmsg_to_parent(2, msg, "");
4987 fprintf(stderr, "%s", msg);
4994 /****************************************************************************************************************/
4995 /* indication report routines */
4999 report_packet_count(unsigned int packet_count)
5001 char tmp[SP_DECISIZE+1+1];
5002 static unsigned int count = 0;
5004 if (capture_child) {
5005 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
5006 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
5007 pipe_write_block(2, SP_PACKET_COUNT, tmp);
5009 count += packet_count;
5010 fprintf(stderr, "\rPackets: %u ", count);
5011 /* stderr could be line buffered */
5017 report_new_capture_file(const char *filename)
5019 if (capture_child) {
5020 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
5021 pipe_write_block(2, SP_FILE, filename);
5025 * Prevent a SIGINFO handler from writing to the standard error
5026 * while we're doing so; instead, have it just set a flag telling
5027 * us to print that information when we're done.
5030 #endif /* SIGINFO */
5031 fprintf(stderr, "File: %s\n", filename);
5032 /* stderr could be line buffered */
5037 * Allow SIGINFO handlers to write.
5042 * If a SIGINFO handler asked us to write out capture counts, do so.
5045 report_counts_for_siginfo();
5046 #endif /* SIGINFO */
5051 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5053 interface_options interface_opts;
5054 char tmp[MSG_MAX_LENGTH+1+6];
5056 if (i < capture_opts->ifaces->len) {
5057 if (capture_child) {
5058 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5059 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5060 pipe_write_block(2, SP_BAD_FILTER, tmp);
5063 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5064 * the error message below.
5066 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
5068 "Invalid capture filter \"%s\" for interface '%s'!\n"
5070 "That string isn't a valid capture filter (%s).\n"
5071 "See the User's Guide for a description of the capture filter syntax.",
5072 interface_opts.cfilter, interface_opts.name, errmsg);
5078 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5080 if (capture_child) {
5081 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5082 "Primary Error: %s", error_msg);
5083 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5084 "Secondary Error: %s", secondary_error_msg);
5085 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5087 cmdarg_err("%s", error_msg);
5088 if (secondary_error_msg[0] != '\0')
5089 cmdarg_err_cont("%s", secondary_error_msg);
5094 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
5096 char tmp[SP_DECISIZE+1+1];
5097 guint32 total_drops = pcap_drops + drops + flushed;
5099 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5101 if (capture_child) {
5102 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5103 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5104 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
5105 /* XXX: Need to provide interface id, changes to consumers required. */
5106 pipe_write_block(2, SP_DROPS, tmp);
5109 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5110 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
5111 received ? 100.0 * received / (received + total_drops) : 0.0);
5112 /* stderr could be line buffered */
5118 /************************************************************************************************/
5119 /* signal_pipe handling */
5124 signal_pipe_check_running(void)
5126 /* any news from our parent? -> just stop the capture */
5130 /* if we are running standalone, no check required */
5131 if (!capture_child) {
5135 if (!sig_pipe_name || !sig_pipe_handle) {
5136 /* This shouldn't happen */
5137 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5138 "Signal pipe: No name or handle");
5143 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5144 * at this point. Should we check to see if the parent is still alive,
5145 * e.g. by using OpenProcess?
5148 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5150 if (!result || avail > 0) {
5151 /* peek failed or some bytes really available */
5152 /* (if not piping from stdin this would fail) */
5153 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5154 "Signal pipe: Stop capture: %s", sig_pipe_name);
5155 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5156 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
5157 sig_pipe_handle, result, avail);
5160 /* pipe ok and no bytes available */
5171 * Editor modelines - http://www.wireshark.org/tools/modelines.html
5176 * indent-tabs-mode: nil
5179 * vi: set shiftwidth=4 tabstop=8 expandtab:
5180 * :indentSize=4:tabSize=8:noTabs=true: