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>
73 #include <wsutil/pint.h>
76 #include "wsutil/wsgetopt.h"
84 # include <sys/prctl.h>
85 # include <sys/capability.h>
88 #include "ringbuffer.h"
89 #include "clopts_common.h"
90 #include "cmdarg_err.h"
91 #include "version_info.h"
93 #include "capture-pcap-util.h"
95 #include "capture-wpcap.h"
101 #include "capture-wpcap.h"
102 #include <wsutil/unicode-utils.h>
109 #ifdef NEED_INET_V6DEFS_H
110 # include "wsutil/inet_v6defs.h"
113 #include <wsutil/privileges.h>
115 #include "sync_pipe.h"
117 #include "capture_opts.h"
118 #include "capture_session.h"
119 #include "capture_ifinfo.h"
120 #include "capture_sync.h"
122 #include "conditions.h"
123 #include "capture_stop_conditions.h"
125 #include "wsutil/tempfile.h"
127 #include "wsutil/file_util.h"
129 #include "ws80211_utils.h"
132 * Get information about libpcap format from "wiretap/libpcap.h".
133 * XXX - can we just use pcap_open_offline() to read the pipe?
135 #include "wiretap/libpcap.h"
137 /**#define DEBUG_DUMPCAP**/
138 /**#define DEBUG_CHILD_DUMPCAP**/
142 #include <conio.h> /* _getch() */
146 #ifdef DEBUG_CHILD_DUMPCAP
147 FILE *debug_log; /* for logging debug messages to */
148 /* a file if DEBUG_CHILD_DUMPCAP */
152 static GAsyncQueue *pcap_queue;
153 static gint64 pcap_queue_bytes;
154 static gint64 pcap_queue_packets;
155 static gint64 pcap_queue_byte_limit = 0;
156 static gint64 pcap_queue_packet_limit = 0;
158 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
160 static gchar *sig_pipe_name = NULL;
161 static HANDLE sig_pipe_handle = NULL;
162 static gboolean signal_pipe_check_running(void);
166 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
167 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
170 /** Stop a low-level capture (stops the capture child). */
171 static void capture_loop_stop(void);
172 /** Close a pipe, or socket if \a from_socket is TRUE */
173 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
177 * Enable kernel BPF JIT compiler if available.
178 * If any calls fail, just drive on - the JIT compiler might not be
179 * enabled, but filtering will still work, and it's not clear what
180 * we could do if the calls fail; should we just report the error
181 * and not continue to capture, should we report it as a warning, or
185 enable_kernel_bpf_jit_compiler(void)
189 static const char file[] = "/proc/sys/net/core/bpf_jit_enable";
191 fd = open(file, O_WRONLY);
195 written = write(fd, "1", strlen("1"));
201 #if !defined (__linux__)
202 #ifndef HAVE_PCAP_BREAKLOOP
204 * We don't have pcap_breakloop(), which is the only way to ensure that
205 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
206 * won't, if the call to read the next packet or batch of packets is
207 * is interrupted by a signal on UN*X, just go back and try again to
210 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
211 * the signal handler, set a flag to stop capturing; however, without
212 * a guarantee of that sort, we can't guarantee that we'll stop capturing
213 * if the read will be retried and won't time out if no packets arrive.
215 * Therefore, on at least some platforms, we work around the lack of
216 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
217 * to wait for packets to arrive, so that we're probably going to be
218 * blocked in the select() when the signal arrives, and can just bail
219 * out of the loop at that point.
221 * However, we don't want to do that on BSD (because "select()" doesn't work
222 * correctly on BPF devices on at least some releases of some flavors of
223 * BSD), and we don't want to do it on Windows (because "select()" is
224 * something for sockets, not for arbitrary handles). (Note that "Windows"
225 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
226 * using WinPcap, not a UNIX libpcap.)
228 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
229 * on BSD times out even if no packets have arrived, so we'll eventually
230 * exit pcap_dispatch() with an indication that no packets have arrived,
231 * and will break out of the capture loop at that point.
233 * On Windows, we can't send a SIGINT to stop capturing, so none of this
234 * applies in any case.
236 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
237 * want to include it if it's not present on this platform, however.
239 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
240 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
242 # define MUST_DO_SELECT
243 # endif /* avoid select */
244 #endif /* HAVE_PCAP_BREAKLOOP */
246 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
247 * in pcap_dispatch(); on the other hand, select() works just fine there.
248 * Hence we use a select for that come what may.
250 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
251 * internally, and, with TPACKET_V3, once that's supported, it'll
252 * support timeouts, at least as I understand the way the code works.
254 #define MUST_DO_SELECT
257 /** init the capture filter */
260 INITFILTER_BAD_FILTER,
261 INITFILTER_OTHER_ERROR
262 } initfilter_status_t;
265 STATE_EXPECT_REC_HDR,
278 typedef struct _pcap_options {
283 #ifdef MUST_DO_SELECT
284 int pcap_fd; /**< pcap file descriptor */
291 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
292 /**< capture pipe (unix only "input file") */
293 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
294 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
295 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
296 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
298 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
300 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
301 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
302 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
304 char * cap_pipe_buf; /**< Pointer to the data buffer we read into */
305 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
306 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
308 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
309 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
311 cap_pipe_state_t cap_pipe_state;
312 cap_pipe_err_t cap_pipe_err;
315 GMutex *cap_pipe_read_mtx;
316 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
320 typedef struct _loop_data {
322 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
323 int err; /**< if non-zero, error seen while capturing */
324 gint packet_count; /**< Number of packets we have already captured */
325 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
326 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
328 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
334 guint64 bytes_written;
335 guint32 autostop_files;
338 typedef struct _pcap_queue_element {
339 pcap_options *pcap_opts;
340 struct pcap_pkthdr phdr;
342 } pcap_queue_element;
345 * Standard secondary message for unexpected errors.
347 static const char please_report[] =
348 "Please report this to the Wireshark developers.\n"
349 "http://bugs.wireshark.org/\n"
350 "(This is not a crash; please do not report it as such.)";
353 * This needs to be static, so that the SIGINT handler can clear the "go"
356 static loop_data global_ld;
360 * Timeout, in milliseconds, for reads from the stream of captured packets
361 * from a capture device.
363 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
364 * 64-bit applications, with sub-second timeouts not to work. The bug is
365 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
367 #if defined(__APPLE__) && defined(__LP64__)
368 static gboolean need_timeout_workaround;
370 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
372 #define CAP_READ_TIMEOUT 250
376 * Timeout, in microseconds, for reads from the stream of captured packets
377 * from a pipe. Pipes don't have the same problem that BPF devices do
378 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
379 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
380 * of the offending versions of Snow Leopard.
382 * On Windows this value is converted to milliseconds and passed to
383 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
384 * will return immediately.
387 #define PIPE_READ_TIMEOUT 100000
389 #define PIPE_READ_TIMEOUT 250000
392 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
395 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
396 const char *message, gpointer user_data _U_);
398 /* capture related options */
399 static capture_options global_capture_opts;
400 static gboolean quiet = FALSE;
401 static gboolean use_threads = FALSE;
402 static guint64 start_time;
404 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
406 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
408 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
409 int err, gboolean is_close);
411 static void WS_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
413 static void report_new_capture_file(const char *filename);
414 static void report_packet_count(unsigned int packet_count);
415 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
416 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
417 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
419 #define MSG_MAX_LENGTH 4096
421 /* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
423 create_timestamp(void) {
433 * Current time, represented as 100-nanosecond intervals since
434 * January 1, 1601, 00:00:00 UTC.
436 * I think DWORD might be signed, so cast both parts of "now"
437 * to guint32 so that the sign bit doesn't get treated specially.
439 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
440 * might want to use instead.
442 GetSystemTimeAsFileTime(&now);
443 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
444 (guint32)now.dwLowDateTime;
447 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
453 * Subtract difference, in microseconds, between January 1, 1601
454 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
456 timestamp -= G_GINT64_CONSTANT(11644473600000000U);
459 * Current time, represented as seconds and microseconds since
460 * January 1, 1970, 00:00:00 UTC.
462 gettimeofday(&now, NULL);
465 * Convert to delta in microseconds.
467 timestamp = (guint64)(now.tv_sec) * 1000000 +
468 (guint64)(now.tv_usec);
474 print_usage(gboolean print_ver)
481 "Dumpcap " VERSION "%s\n"
482 "Capture network packets and dump them into a pcapng file.\n"
483 "See http://www.wireshark.org for more information.\n",
484 wireshark_svnversion);
488 fprintf(output, "\nUsage: dumpcap [options] ...\n");
489 fprintf(output, "\n");
490 fprintf(output, "Capture interface:\n");
491 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
492 " or for remote capturing, use one of these formats:\n"
493 " rpcap://<host>/<interface>\n"
494 " TCP@<host>:<port>\n");
495 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
496 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
497 fprintf(output, " -p don't capture in promiscuous mode\n");
498 #ifdef HAVE_PCAP_CREATE
499 fprintf(output, " -I capture in monitor mode, if available\n");
501 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
502 fprintf(output, " -B <buffer size> size of kernel buffer in MB (def: %dMB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
504 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
505 fprintf(output, " -D print list of interfaces and exit\n");
506 fprintf(output, " -L print list of link-layer types of iface and exit\n");
507 #ifdef HAVE_BPF_IMAGE
508 fprintf(output, " -d print generated BPF code for capture filter\n");
510 fprintf(output, " -k set channel on wifi interface <freq>,[<type>]\n");
511 fprintf(output, " -S print statistics for each interface once per second\n");
512 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
513 fprintf(output, "\n");
514 #ifdef HAVE_PCAP_REMOTE
515 fprintf(output, "RPCAP options:\n");
516 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
517 fprintf(output, " -u use UDP for RPCAP data transfer\n");
518 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
519 #ifdef HAVE_PCAP_SETSAMPLING
520 fprintf(output, " -m <sampling type> use packet sampling\n");
521 fprintf(output, " count:NUM - capture one packet of every NUM\n");
522 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
525 fprintf(output, "Stop conditions:\n");
526 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
527 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
528 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
529 fprintf(output, " files:NUM - stop after NUM files\n");
530 /*fprintf(output, "\n");*/
531 fprintf(output, "Output (files):\n");
532 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
533 fprintf(output, " -g enable group read access on the output file(s)\n");
534 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
535 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
536 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
537 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
538 fprintf(output, " -P use libpcap format instead of pcapng\n");
539 fprintf(output, " --capture-comment <comment>\n");
540 fprintf(output, " add a capture comment to the output file\n");
541 fprintf(output, " (only for pcapng)\n");
542 fprintf(output, "\n");
543 fprintf(output, "Miscellaneous:\n");
544 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
545 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
546 fprintf(output, " within dumpcap\n");
547 fprintf(output, " -t use a separate thread per interface\n");
548 fprintf(output, " -q don't report packet capture counts\n");
549 fprintf(output, " -v print version information and exit\n");
550 fprintf(output, " -h display this help and exit\n");
551 fprintf(output, "\n");
553 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
554 fprintf(output, "You might want to reset it\n");
555 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
556 fprintf(output, "\n");
558 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
559 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
560 fprintf(output, "\n");
561 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
565 show_version(GString *comp_info_str, GString *runtime_info_str)
568 "Dumpcap " VERSION "%s\n"
573 "See http://www.wireshark.org for more information.\n",
574 wireshark_svnversion, get_copyright_info(), comp_info_str->str, runtime_info_str->str);
578 * Report an error in command-line arguments.
581 cmdarg_err(const char *fmt, ...)
587 /* Generate a 'special format' message back to parent */
589 msg = g_strdup_vprintf(fmt, ap);
590 sync_pipe_errmsg_to_parent(2, msg, "");
595 fprintf(stderr, "dumpcap: ");
596 vfprintf(stderr, fmt, ap);
597 fprintf(stderr, "\n");
603 * Report additional information for an error in command-line arguments.
606 cmdarg_err_cont(const char *fmt, ...)
613 msg = g_strdup_vprintf(fmt, ap);
614 sync_pipe_errmsg_to_parent(2, msg, "");
619 vfprintf(stderr, fmt, ap);
620 fprintf(stderr, "\n");
627 #if 0 /* Set to enable capability debugging */
628 /* see 'man cap_to_text()' for explanation of output */
629 /* '=' means 'all= ' ie: no capabilities */
630 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
632 print_caps(const char *pfx) {
633 cap_t caps = cap_get_proc();
634 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
635 "%s: EUID: %d Capabilities: %s", pfx,
636 geteuid(), cap_to_text(caps, NULL));
639 print_caps(const char *pfx _U_) {
644 relinquish_all_capabilities(void)
646 /* Drop any and all capabilities this process may have. */
647 /* Allowed whether or not process has any privileges. */
648 cap_t caps = cap_init(); /* all capabilities initialized to off */
649 print_caps("Pre-clear");
650 if (cap_set_proc(caps)) {
651 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
653 print_caps("Post-clear");
659 open_capture_device(interface_options *interface_opts,
660 char (*open_err_str)[PCAP_ERRBUF_SIZE])
663 #ifdef HAVE_PCAP_CREATE
666 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
667 struct pcap_rmtauth auth;
670 /* Open the network interface to capture from it.
671 Some versions of libpcap may put warnings into the error buffer
672 if they succeed; to tell if that's happened, we have to clear
673 the error buffer, and check if it's still a null string. */
674 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Entering open_capture_device().");
675 (*open_err_str)[0] = '\0';
676 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
678 * If we're opening a remote device, use pcap_open(); that's currently
679 * the only open routine that supports remote devices.
681 if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
682 auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
683 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
684 auth.username = interface_opts->auth_username;
685 auth.password = interface_opts->auth_password;
687 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
688 "Calling pcap_open() using name %s, snaplen %d, promisc_mode %d, datatx_udp %d, nocap_rpcap %d.",
689 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode,
690 interface_opts->datatx_udp, interface_opts->nocap_rpcap);
691 pcap_h = pcap_open(interface_opts->name, interface_opts->snaplen,
693 (interface_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
694 (interface_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
695 (interface_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
696 CAP_READ_TIMEOUT, &auth, *open_err_str);
697 if (pcap_h == NULL) {
698 /* Error - did pcap actually supply an error message? */
699 if ((*open_err_str)[0] == '\0') {
700 /* Work around known WinPcap bug wherein no error message is
701 filled in on a failure to open an rpcap: URL. */
702 g_strlcpy(*open_err_str,
703 "Unknown error (pcap bug; actual error cause not reported)",
704 sizeof *open_err_str);
707 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
708 "pcap_open() returned %p.", (void *)pcap_h);
713 * If we're not opening a remote device, use pcap_create() and
714 * pcap_activate() if we have them, so that we can set the buffer
715 * size, otherwise use pcap_open_live().
717 #ifdef HAVE_PCAP_CREATE
718 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
719 "Calling pcap_create() using %s.", interface_opts->name);
720 pcap_h = pcap_create(interface_opts->name, *open_err_str);
721 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
722 "pcap_create() returned %p.", (void *)pcap_h);
723 if (pcap_h != NULL) {
724 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
725 "Calling pcap_set_snaplen() with snaplen %d.", interface_opts->snaplen);
726 pcap_set_snaplen(pcap_h, interface_opts->snaplen);
727 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
728 "Calling pcap_set_promisc() with promisc_mode %d.", interface_opts->promisc_mode);
729 pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
730 pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
732 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
733 "buffersize %d.", interface_opts->buffer_size);
734 if (interface_opts->buffer_size != 0) {
735 pcap_set_buffer_size(pcap_h, interface_opts->buffer_size * 1024 * 1024);
737 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
738 "monitor_mode %d.", interface_opts->monitor_mode);
739 if (interface_opts->monitor_mode)
740 pcap_set_rfmon(pcap_h, 1);
741 err = pcap_activate(pcap_h);
742 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
743 "pcap_activate() returned %d.", err);
745 /* Failed to activate, set to NULL */
746 if (err == PCAP_ERROR)
747 g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
749 g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
755 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
756 "pcap_open_live() calling using name %s, snaplen %d, promisc_mode %d.",
757 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode);
758 pcap_h = pcap_open_live(interface_opts->name, interface_opts->snaplen,
759 interface_opts->promisc_mode, CAP_READ_TIMEOUT,
761 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
762 "pcap_open_live() returned %p.", (void *)pcap_h);
765 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_capture_device %s : %s", pcap_h ? "SUCCESS" : "FAILURE", interface_opts->name);
770 get_capture_device_open_failure_messages(const char *open_err_str,
772 char *errmsg, size_t errmsg_len,
773 char *secondary_errmsg,
774 size_t secondary_errmsg_len)
777 const char *libpcap_warn;
778 static const char ppamsg[] = "can't find PPA for ";
781 g_snprintf(errmsg, (gulong) errmsg_len,
782 "The capture session could not be initiated on interface '%s' (%s).",
783 iface, open_err_str);
786 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
788 "In order to capture packets, WinPcap must be installed; see\n"
790 " http://www.winpcap.org/\n"
794 " http://www.mirrors.wiretapped.net/security/packet-capture/winpcap/\n"
798 " http://winpcap.cs.pu.edu.tw/\n"
800 "for a downloadable version of WinPcap and for instructions on how to install\n"
803 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
805 "Please check that \"%s\" is the proper interface.\n"
808 "Help can be found at:\n"
810 " http://wiki.wireshark.org/WinPcap\n"
811 " http://wiki.wireshark.org/CaptureSetup\n",
815 /* If we got a "can't find PPA for X" message, warn the user (who
816 is running dumpcap on HP-UX) that they don't have a version of
817 libpcap that properly handles HP-UX (libpcap 0.6.x and later
818 versions, which properly handle HP-UX, say "can't find /dev/dlpi
819 PPA for X" rather than "can't find PPA for X"). */
820 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
823 "You are running (T)Wireshark with a version of the libpcap library\n"
824 "that doesn't handle HP-UX network devices well; this means that\n"
825 "(T)Wireshark may not be able to capture packets.\n"
827 "To fix this, you should install libpcap 0.6.2, or a later version\n"
828 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
829 "packaged binary form from the Software Porting And Archive Centre\n"
830 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
831 "at the URL lists a number of mirror sites.";
835 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
836 "Please check to make sure you have sufficient permissions, and that you have "
837 "the proper interface or pipe specified.%s", libpcap_warn);
841 /* Set the data link type on a pcap. */
843 set_pcap_linktype(pcap_t *pcap_h, int linktype, char *name,
844 char *errmsg, size_t errmsg_len,
845 char *secondary_errmsg, size_t secondary_errmsg_len)
847 char *set_linktype_err_str;
850 return TRUE; /* just use the default */
851 #ifdef HAVE_PCAP_SET_DATALINK
852 if (pcap_set_datalink(pcap_h, linktype) == 0)
853 return TRUE; /* no error */
854 set_linktype_err_str = pcap_geterr(pcap_h);
856 /* Let them set it to the type it is; reject any other request. */
857 if (get_pcap_linktype(pcap_h, name) == linktype)
858 return TRUE; /* no error */
859 set_linktype_err_str =
860 "That DLT isn't one of the DLTs supported by this device";
862 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type on interface '%s' (%s).",
863 name, set_linktype_err_str);
865 * If the error isn't "XXX is not one of the DLTs supported by this device",
866 * tell the user to tell the Wireshark developers about it.
868 if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
869 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
871 secondary_errmsg[0] = '\0';
876 compile_capture_filter(const char *iface, pcap_t *pcap_h,
877 struct bpf_program *fcode, const char *cfilter)
879 bpf_u_int32 netnum, netmask;
880 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
882 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
884 * Well, we can't get the netmask for this interface; it's used
885 * only for filters that check for broadcast IP addresses, so
886 * we just punt and use 0. It might be nice to warn the user,
887 * but that's a pain in a GUI application, as it'd involve popping
888 * up a message box, and it's not clear how often this would make
889 * a difference (only filters that check for IP broadcast addresses
893 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
898 * Sigh. Older versions of libpcap don't properly declare the
899 * third argument to pcap_compile() as a const pointer. Cast
902 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
907 #ifdef HAVE_BPF_IMAGE
909 show_filter_code(capture_options *capture_opts)
911 interface_options interface_opts;
913 gchar open_err_str[PCAP_ERRBUF_SIZE];
914 char errmsg[MSG_MAX_LENGTH+1];
915 char secondary_errmsg[MSG_MAX_LENGTH+1];
916 struct bpf_program fcode;
917 struct bpf_insn *insn;
921 for (j = 0; j < capture_opts->ifaces->len; j++) {
922 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
923 pcap_h = open_capture_device(&interface_opts, &open_err_str);
924 if (pcap_h == NULL) {
925 /* Open failed; get messages */
926 get_capture_device_open_failure_messages(open_err_str,
928 errmsg, sizeof errmsg,
930 sizeof secondary_errmsg);
931 /* And report them */
932 report_capture_error(errmsg, secondary_errmsg);
936 /* Set the link-layer type. */
937 if (!set_pcap_linktype(pcap_h, interface_opts.linktype, interface_opts.name,
938 errmsg, sizeof errmsg,
939 secondary_errmsg, sizeof secondary_errmsg)) {
941 report_capture_error(errmsg, secondary_errmsg);
945 /* OK, try to compile the capture filter. */
946 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
947 interface_opts.cfilter)) {
949 report_cfilter_error(capture_opts, j, errmsg);
954 /* Now print the filter code. */
955 insn = fcode.bf_insns;
957 for (i = 0; i < fcode.bf_len; insn++, i++)
958 printf("%s\n", bpf_image(insn, i));
960 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
961 /* to remove any suid privileges. */
962 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
963 /* (euid/egid have already previously been set to ruid/rgid. */
964 /* (See comment in main() for details) */
966 relinquish_special_privs_perm();
968 relinquish_all_capabilities();
971 /* Let our parent know we succeeded. */
972 pipe_write_block(2, SP_SUCCESS, NULL);
979 * capture_interface_list() is expected to do the right thing to get
980 * a list of interfaces.
982 * In most of the programs in the Wireshark suite, "the right thing"
983 * is to run dumpcap and ask it for the list, because dumpcap may
984 * be the only program in the suite with enough privileges to get
987 * In dumpcap itself, however, we obviously can't run dumpcap to
988 * ask for the list. Therefore, our capture_interface_list() should
989 * just call get_interface_list().
992 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
994 return get_interface_list(err, err_str);
998 * Get the data-link type for a libpcap device.
999 * This works around AIX 5.x's non-standard and incompatible-with-the-
1000 * rest-of-the-universe libpcap.
1003 get_pcap_linktype(pcap_t *pch, const char *devicename
1011 const char *ifacename;
1014 linktype = pcap_datalink(pch);
1018 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
1019 * rather than DLT_ values for link-layer types; the ifType values
1020 * for LAN devices are:
1027 * and the ifType value for a loopback device is 24.
1029 * The AIX names for LAN devices begin with:
1036 * and the AIX names for loopback devices begin with "lo".
1038 * (The difference between "Ethernet" and "802.3" is presumably
1039 * whether packets have an Ethernet header, with a packet type,
1040 * or an 802.3 header, with a packet length, followed by an 802.2
1041 * header and possibly a SNAP header.)
1043 * If the device name matches "linktype" interpreted as an ifType
1044 * value, rather than as a DLT_ value, we will assume this is AIX's
1045 * non-standard, incompatible libpcap, rather than a standard libpcap,
1046 * and will map the link-layer type to the standard DLT_ value for
1047 * that link-layer type, as that's what the rest of Wireshark expects.
1049 * (This means the capture files won't be readable by a tcpdump
1050 * linked with AIX's non-standard libpcap, but so it goes. They
1051 * *will* be readable by standard versions of tcpdump, Wireshark,
1054 * XXX - if we conclude we're using AIX libpcap, should we also
1055 * set a flag to cause us to assume the time stamps are in
1056 * seconds-and-nanoseconds form, and to convert them to
1057 * seconds-and-microseconds form before processing them and
1062 * Find the last component of the device name, which is the
1065 ifacename = strchr(devicename, '/');
1066 if (ifacename == NULL)
1067 ifacename = devicename;
1069 /* See if it matches any of the LAN device names. */
1070 if (strncmp(ifacename, "en", 2) == 0) {
1071 if (linktype == 6) {
1073 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
1077 } else if (strncmp(ifacename, "et", 2) == 0) {
1078 if (linktype == 7) {
1080 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
1081 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
1086 } else if (strncmp(ifacename, "tr", 2) == 0) {
1087 if (linktype == 9) {
1089 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
1090 * DLT_IEEE802, which is what's used for Token Ring.
1094 } else if (strncmp(ifacename, "fi", 2) == 0) {
1095 if (linktype == 15) {
1097 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
1101 } else if (strncmp(ifacename, "lo", 2) == 0) {
1102 if (linktype == 24) {
1104 * That's the RFC 1573 value for "software loopback" devices; map it
1105 * to DLT_NULL, which is what's used for loopback devices on BSD.
1115 static data_link_info_t *
1116 create_data_link_info(int dlt)
1118 data_link_info_t *data_link_info;
1121 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
1122 data_link_info->dlt = dlt;
1123 text = pcap_datalink_val_to_name(dlt);
1125 data_link_info->name = g_strdup(text);
1127 data_link_info->name = g_strdup_printf("DLT %d", dlt);
1128 text = pcap_datalink_val_to_description(dlt);
1130 data_link_info->description = g_strdup(text);
1132 data_link_info->description = NULL;
1133 return data_link_info;
1137 * Get the capabilities of a network device.
1139 static if_capabilities_t *
1140 get_if_capabilities(const char *devicename, gboolean monitor_mode
1141 #ifndef HAVE_PCAP_CREATE
1146 if_capabilities_t *caps;
1147 char errbuf[PCAP_ERRBUF_SIZE];
1149 #ifdef HAVE_PCAP_CREATE
1153 #ifdef HAVE_PCAP_LIST_DATALINKS
1157 data_link_info_t *data_link_info;
1160 * Allocate the interface capabilities structure.
1162 caps = (if_capabilities_t *)g_malloc(sizeof *caps);
1165 * WinPcap 4.1.2, and possibly earlier versions, have a bug
1166 * wherein, when an open with an rpcap: URL fails, the error
1167 * message for the error is not copied to errbuf and whatever
1168 * on-the-stack junk is in errbuf is treated as the error
1171 * To work around that (and any other bugs of that sort, we
1172 * initialize errbuf to an empty string. If we get an error
1173 * and the string is empty, we report it as an unknown error.
1174 * (If we *don't* get an error, and the string is *non*-empty,
1175 * that could be a warning returned, such as "can't turn
1176 * promiscuous mode on"; we currently don't do so.)
1179 #ifdef HAVE_PCAP_OPEN
1180 pch = pcap_open(devicename, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1181 caps->can_set_rfmon = FALSE;
1183 if (err_str != NULL)
1184 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1188 #elif defined(HAVE_PCAP_CREATE)
1189 pch = pcap_create(devicename, errbuf);
1191 if (err_str != NULL)
1192 *err_str = g_strdup(errbuf);
1196 status = pcap_can_set_rfmon(pch);
1199 if (status == PCAP_ERROR)
1200 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1203 *err_str = g_strdup(pcap_statustostr(status));
1209 caps->can_set_rfmon = FALSE;
1210 else if (status == 1) {
1211 caps->can_set_rfmon = TRUE;
1213 pcap_set_rfmon(pch, 1);
1215 if (err_str != NULL) {
1216 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1224 status = pcap_activate(pch);
1226 /* Error. We ignore warnings (status > 0). */
1227 if (err_str != NULL) {
1228 if (status == PCAP_ERROR)
1229 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1232 *err_str = g_strdup(pcap_statustostr(status));
1239 pch = pcap_open_live(devicename, MIN_PACKET_SIZE, 0, 0, errbuf);
1240 caps->can_set_rfmon = FALSE;
1242 if (err_str != NULL)
1243 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1248 deflt = get_pcap_linktype(pch, devicename);
1249 #ifdef HAVE_PCAP_LIST_DATALINKS
1250 nlt = pcap_list_datalinks(pch, &linktypes);
1251 if (nlt == 0 || linktypes == NULL) {
1253 if (err_str != NULL)
1254 *err_str = NULL; /* an empty list doesn't mean an error */
1258 caps->data_link_types = NULL;
1259 for (i = 0; i < nlt; i++) {
1260 data_link_info = create_data_link_info(linktypes[i]);
1263 * XXX - for 802.11, make the most detailed 802.11
1264 * version the default, rather than the one the
1265 * device has as the default?
1267 if (linktypes[i] == deflt)
1268 caps->data_link_types = g_list_prepend(caps->data_link_types,
1271 caps->data_link_types = g_list_append(caps->data_link_types,
1274 #ifdef HAVE_PCAP_FREE_DATALINKS
1275 pcap_free_datalinks(linktypes);
1278 * In Windows, there's no guarantee that if you have a library
1279 * built with one version of the MSVC++ run-time library, and
1280 * it returns a pointer to allocated data, you can free that
1281 * data from a program linked with another version of the
1282 * MSVC++ run-time library.
1284 * This is not an issue on UN*X.
1286 * See the mail threads starting at
1288 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1292 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1295 #define xx_free free /* hack so checkAPIs doesn't complain */
1298 #endif /* HAVE_PCAP_FREE_DATALINKS */
1299 #else /* HAVE_PCAP_LIST_DATALINKS */
1301 data_link_info = create_data_link_info(deflt);
1302 caps->data_link_types = g_list_append(caps->data_link_types,
1304 #endif /* HAVE_PCAP_LIST_DATALINKS */
1308 if (err_str != NULL)
1313 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1315 * Output a machine readable list of the interfaces
1316 * This list is retrieved by the sync_interface_list_open() function
1317 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
1320 print_machine_readable_interfaces(GList *if_list)
1327 char addr_str[ADDRSTRLEN];
1329 if (capture_child) {
1330 /* Let our parent know we succeeded. */
1331 pipe_write_block(2, SP_SUCCESS, NULL);
1334 i = 1; /* Interface id number */
1335 for (if_entry = g_list_first(if_list); if_entry != NULL;
1336 if_entry = g_list_next(if_entry)) {
1337 if_info = (if_info_t *)if_entry->data;
1338 printf("%d. %s\t", i++, if_info->name);
1341 * Print the contents of the if_entry struct in a parseable format.
1342 * Each if_entry element is tab-separated. Addresses are comma-
1345 /* XXX - Make sure our description doesn't contain a tab */
1346 if (if_info->vendor_description != NULL)
1347 printf("%s\t", if_info->vendor_description);
1351 /* XXX - Make sure our friendly name doesn't contain a tab */
1352 if (if_info->friendly_name != NULL)
1353 printf("%s\t", if_info->friendly_name);
1357 printf("%u\t", if_info->type);
1359 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1360 addr = g_slist_next(addr)) {
1361 if (addr != g_slist_nth(if_info->addrs, 0))
1364 if_addr = (if_addr_t *)addr->data;
1365 switch(if_addr->ifat_type) {
1367 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1369 printf("%s", addr_str);
1371 printf("<unknown IPv4>");
1375 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1376 addr_str, ADDRSTRLEN)) {
1377 printf("%s", addr_str);
1379 printf("<unknown IPv6>");
1383 printf("<type unknown %u>", if_addr->ifat_type);
1387 if (if_info->loopback)
1388 printf("\tloopback");
1390 printf("\tnetwork");
1397 * If you change the machine-readable output format of this function,
1398 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1401 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1404 data_link_info_t *data_link_info;
1405 const gchar *desc_str;
1407 if (capture_child) {
1408 /* Let our parent know we succeeded. */
1409 pipe_write_block(2, SP_SUCCESS, NULL);
1412 if (caps->can_set_rfmon)
1416 for (lt_entry = caps->data_link_types; lt_entry != NULL;
1417 lt_entry = g_list_next(lt_entry)) {
1418 data_link_info = (data_link_info_t *)lt_entry->data;
1419 if (data_link_info->description != NULL)
1420 desc_str = data_link_info->description;
1422 desc_str = "(not supported)";
1423 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1433 /* Print the number of packets captured for each interface until we're killed. */
1435 print_statistics_loop(gboolean machine_readable)
1437 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1443 char errbuf[PCAP_ERRBUF_SIZE];
1444 struct pcap_stat ps;
1446 if_list = get_interface_list(&err, &err_str);
1447 if (if_list == NULL) {
1449 case CANT_GET_INTERFACE_LIST:
1450 case DONT_HAVE_PCAP:
1451 cmdarg_err("%s", err_str);
1455 case NO_INTERFACES_FOUND:
1456 cmdarg_err("There are no interfaces on which a capture can be done");
1462 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1463 if_info = (if_info_t *)if_entry->data;
1464 #ifdef HAVE_PCAP_OPEN
1465 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1467 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1471 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1472 if_stat->name = g_strdup(if_info->name);
1474 stat_list = g_list_append(stat_list, if_stat);
1479 cmdarg_err("There are no interfaces on which a capture can be done");
1483 if (capture_child) {
1484 /* Let our parent know we succeeded. */
1485 pipe_write_block(2, SP_SUCCESS, NULL);
1488 if (!machine_readable) {
1489 printf("%-15s %10s %10s\n", "Interface", "Received",
1493 global_ld.go = TRUE;
1494 while (global_ld.go) {
1495 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1496 if_stat = (if_stat_t *)stat_entry->data;
1497 pcap_stats(if_stat->pch, &ps);
1499 if (!machine_readable) {
1500 printf("%-15s %10u %10u\n", if_stat->name,
1501 ps.ps_recv, ps.ps_drop);
1503 printf("%s\t%u\t%u\n", if_stat->name,
1504 ps.ps_recv, ps.ps_drop);
1509 /* If we have a dummy signal pipe check it */
1510 if (!signal_pipe_check_running()) {
1511 global_ld.go = FALSE;
1519 /* XXX - Not reached. Should we look for 'q' in stdin? */
1520 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1521 if_stat = (if_stat_t *)stat_entry->data;
1522 pcap_close(if_stat->pch);
1523 g_free(if_stat->name);
1526 g_list_free(stat_list);
1527 free_interface_list(if_list);
1535 capture_cleanup_handler(DWORD dwCtrlType)
1537 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1538 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1539 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1540 like SIGTERM at least when the machine's shutting down.
1542 For now, if we're running as a command rather than a capture child,
1543 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1544 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1545 in that way on UN*X.
1547 If we're not running as a capture child, we might be running as
1548 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1549 user logs out. (XXX - can we explicitly check whether we're
1550 running as a service?) */
1552 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1553 "Console: Control signal");
1554 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1555 "Console: Control signal, CtrlType: %u", dwCtrlType);
1557 /* Keep capture running if we're a service and a user logs off */
1558 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1559 capture_loop_stop();
1567 capture_cleanup_handler(int signum _U_)
1569 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1570 SIGTERM. We assume that if the user wanted it to keep running
1571 after they logged out, they'd have nohupped it. */
1573 /* Note: don't call g_log() in the signal handler: if we happened to be in
1574 * g_log() in process context when the signal came in, g_log will detect
1575 * the "recursion" and abort.
1578 capture_loop_stop();
1584 report_capture_count(gboolean reportit)
1586 /* Don't print this if we're a capture child. */
1587 if (!capture_child && reportit) {
1588 fprintf(stderr, "\rPackets captured: %u\n", global_ld.packet_count);
1589 /* stderr could be line buffered */
1597 report_counts_for_siginfo(void)
1599 report_capture_count(quiet);
1600 infoprint = FALSE; /* we just reported it */
1604 report_counts_siginfo(int signum _U_)
1606 int sav_errno = errno;
1608 /* If we've been told to delay printing, just set a flag asking
1609 that we print counts (if we're supposed to), otherwise print
1610 the count of packets captured (if we're supposed to). */
1614 report_counts_for_siginfo();
1617 #endif /* SIGINFO */
1620 exit_main(int status)
1623 /* Shutdown windows sockets */
1626 /* can be helpful for debugging */
1627 #ifdef DEBUG_DUMPCAP
1628 printf("Press any key\n");
1639 * If we were linked with libcap (not related to libpcap), make sure we have
1640 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1641 * (See comment in main() for details)
1644 relinquish_privs_except_capture(void)
1646 /* If 'started_with_special_privs' (ie: suid) then enable for
1647 * ourself the NET_ADMIN and NET_RAW capabilities and then
1648 * drop our suid privileges.
1650 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1651 * stuff we don't need (and shouldn't have).
1652 * CAP_NET_RAW: Packet capture (raw sockets).
1655 if (started_with_special_privs()) {
1656 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1657 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1659 cap_t caps = cap_init(); /* all capabilities initialized to off */
1661 print_caps("Pre drop, pre set");
1663 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1664 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1667 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1668 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1670 if (cap_set_proc(caps)) {
1671 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1673 print_caps("Pre drop, post set");
1675 relinquish_special_privs_perm();
1677 print_caps("Post drop, pre set");
1678 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1679 if (cap_set_proc(caps)) {
1680 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1682 print_caps("Post drop, post set");
1688 #endif /* HAVE_LIBCAP */
1690 /* Take care of byte order in the libpcap headers read from pipes.
1691 * (function taken from wiretap/libpcap.c) */
1693 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1696 /* Byte-swap the record header fields. */
1697 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1698 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1699 rechdr->incl_len = BSWAP32(rechdr->incl_len);
1700 rechdr->orig_len = BSWAP32(rechdr->orig_len);
1703 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1704 swapped, in order to match the BPF header layout.
1706 Unfortunately, some files were, according to a comment in the "libpcap"
1707 source, written with version 2.3 in their headers but without the
1708 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1709 would make no sense - we assume that we need to swap them. */
1710 if (hdr->version_major == 2 &&
1711 (hdr->version_minor < 3 ||
1712 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1715 temp = rechdr->orig_len;
1716 rechdr->orig_len = rechdr->incl_len;
1717 rechdr->incl_len = temp;
1721 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1725 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1729 return recv(pipe_fd, buf, (int)sz, 0);
1734 return ws_read(pipe_fd, buf, sz);
1740 * Thread function that reads from a pipe and pushes the data
1741 * to the main application thread.
1744 * XXX Right now we use async queues for basic signaling. The main thread
1745 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1746 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1747 * Iff the read is successful cap_pipe_read pushes an item onto
1748 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1749 * the queues themselves (yet).
1751 * We might want to move some of the cap_pipe_dispatch logic here so that
1752 * we can let cap_thread_read run independently, queuing up multiple reads
1753 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1755 static void *cap_thread_read(void *arg)
1757 pcap_options *pcap_opts;
1760 DWORD b, last_err, bytes_read;
1766 pcap_opts = (pcap_options *)arg;
1767 while (pcap_opts->cap_pipe_err == PIPOK) {
1768 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1769 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1771 while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1772 if ((pcap_opts->from_cap_socket)
1778 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1779 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1782 pcap_opts->cap_pipe_err = PIPEOF;
1786 pcap_opts->cap_pipe_err = PIPERR;
1797 /* If we try to use read() on a named pipe on Windows with partial
1798 * data it appears to return EOF.
1800 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1801 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1806 last_err = GetLastError();
1807 if (last_err == ERROR_MORE_DATA) {
1809 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1810 pcap_opts->cap_pipe_err = PIPEOF;
1814 pcap_opts->cap_pipe_err = PIPERR;
1817 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1818 pcap_opts->cap_pipe_err = PIPEOF;
1825 pcap_opts->cap_pipe_bytes_read = bytes_read;
1826 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1827 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1829 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1835 /* Provide select() functionality for a single file descriptor
1836 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1838 * Returns the same values as select.
1841 cap_pipe_select(int pipe_fd)
1844 struct timeval timeout;
1847 FD_SET(pipe_fd, &rfds);
1849 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1850 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1852 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1855 #define DEF_TCP_PORT 19000
1858 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1860 char *sockname = pipename + 4;
1861 struct sockaddr_in sa;
1868 memset(&sa, 0, sizeof(sa));
1870 p = strchr(sockname, ':');
1872 len = strlen(sockname);
1873 port = DEF_TCP_PORT;
1877 port = strtoul(p + 1, &p, 10);
1878 if (*p || port > 65535) {
1887 strncpy(buf, sockname, len);
1889 if (inet_pton(AF_INET, buf, &sa.sin_addr) <= 0) {
1893 sa.sin_family = AF_INET;
1894 sa.sin_port = htons((u_short)port);
1896 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1897 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1899 LPTSTR errorText = NULL;
1902 lastError = WSAGetLastError();
1903 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1904 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1905 FORMAT_MESSAGE_IGNORE_INSERTS,
1906 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1907 (LPTSTR)&errorText, 0, NULL);
1909 g_snprintf(errmsg, errmsgl,
1910 "The capture session could not be initiated due to the socket error: \n"
1912 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1914 LocalFree(errorText);
1916 " %d: %s", errno, strerror(errno));
1918 pcap_opts->cap_pipe_err = PIPERR;
1921 cap_pipe_close(fd, TRUE);
1925 pcap_opts->from_cap_socket = TRUE;
1929 g_snprintf(errmsg, errmsgl,
1930 "The capture session could not be initiated because\n"
1931 "\"%s\" is not a valid socket specification", pipename);
1932 pcap_opts->cap_pipe_err = PIPERR;
1936 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1940 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1944 closesocket(pipe_fd);
1951 /* Mimic pcap_open_live() for pipe captures
1953 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1954 * open it, and read the header.
1956 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1957 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1959 cap_pipe_open_live(char *pipename,
1960 pcap_options *pcap_opts,
1961 struct pcap_hdr *hdr,
1962 char *errmsg, int errmsgl)
1965 ws_statb64 pipe_stat;
1966 struct sockaddr_un sa;
1976 pcap_opts->cap_pipe_fd = -1;
1978 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1980 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1983 * XXX - this blocks until a pcap per-file header has been written to
1984 * the pipe, so it could block indefinitely.
1986 if (strcmp(pipename, "-") == 0) {
1988 fd = 0; /* read from stdin */
1990 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1992 } else if (!strncmp(pipename, "TCP@", 4)) {
1993 if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
1998 if (ws_stat64(pipename, &pipe_stat) < 0) {
1999 if (errno == ENOENT || errno == ENOTDIR)
2000 pcap_opts->cap_pipe_err = PIPNEXIST;
2002 g_snprintf(errmsg, errmsgl,
2003 "The capture session could not be initiated "
2004 "due to error getting information on pipe/socket: %s", g_strerror(errno));
2005 pcap_opts->cap_pipe_err = PIPERR;
2009 if (S_ISFIFO(pipe_stat.st_mode)) {
2010 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
2012 g_snprintf(errmsg, errmsgl,
2013 "The capture session could not be initiated "
2014 "due to error on pipe open: %s", g_strerror(errno));
2015 pcap_opts->cap_pipe_err = PIPERR;
2018 } else if (S_ISSOCK(pipe_stat.st_mode)) {
2019 fd = socket(AF_UNIX, SOCK_STREAM, 0);
2021 g_snprintf(errmsg, errmsgl,
2022 "The capture session could not be initiated "
2023 "due to error on socket create: %s", g_strerror(errno));
2024 pcap_opts->cap_pipe_err = PIPERR;
2027 sa.sun_family = AF_UNIX;
2029 * The Single UNIX Specification says:
2031 * The size of sun_path has intentionally been left undefined.
2032 * This is because different implementations use different sizes.
2033 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
2034 * of 104. Since most implementations originate from BSD versions,
2035 * the size is typically in the range 92 to 108.
2037 * Applications should not assume a particular length for sun_path
2038 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
2042 * The <sys/un.h> header shall define the sockaddr_un structure,
2043 * which shall include at least the following members:
2045 * sa_family_t sun_family Address family.
2046 * char sun_path[] Socket pathname.
2048 * so we assume that it's an array, with a specified size,
2049 * and that the size reflects the maximum path length.
2051 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
2052 /* Path name too long */
2053 g_snprintf(errmsg, errmsgl,
2054 "The capture session coud not be initiated "
2055 "due to error on socket connect: Path name too long");
2056 pcap_opts->cap_pipe_err = PIPERR;
2060 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
2062 g_snprintf(errmsg, errmsgl,
2063 "The capture session coud not be initiated "
2064 "due to error on socket connect: %s", g_strerror(errno));
2065 pcap_opts->cap_pipe_err = PIPERR;
2070 if (S_ISCHR(pipe_stat.st_mode)) {
2072 * Assume the user specified an interface on a system where
2073 * interfaces are in /dev. Pretend we haven't seen it.
2075 pcap_opts->cap_pipe_err = PIPNEXIST;
2077 g_snprintf(errmsg, errmsgl,
2078 "The capture session could not be initiated because\n"
2079 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
2080 pcap_opts->cap_pipe_err = PIPERR;
2085 #define PIPE_STR "\\pipe\\"
2086 /* Under Windows, named pipes _must_ have the form
2087 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
2089 pncopy = g_strdup(pipename);
2090 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
2091 pos = strchr(pncopy + 3, '\\');
2092 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
2099 g_snprintf(errmsg, errmsgl,
2100 "The capture session could not be initiated because\n"
2101 "\"%s\" is neither an interface nor a pipe", pipename);
2102 pcap_opts->cap_pipe_err = PIPNEXIST;
2106 /* Wait for the pipe to appear */
2108 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
2109 OPEN_EXISTING, 0, NULL);
2111 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
2114 if (GetLastError() != ERROR_PIPE_BUSY) {
2115 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2116 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2117 g_snprintf(errmsg, errmsgl,
2118 "The capture session on \"%s\" could not be started "
2119 "due to error on pipe open: %s (error %d)",
2120 pipename, utf_16to8(err_str), GetLastError());
2122 pcap_opts->cap_pipe_err = PIPERR;
2126 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
2127 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2128 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2129 g_snprintf(errmsg, errmsgl,
2130 "The capture session on \"%s\" timed out during "
2131 "pipe open: %s (error %d)",
2132 pipename, utf_16to8(err_str), GetLastError());
2134 pcap_opts->cap_pipe_err = PIPERR;
2141 pcap_opts->from_cap_pipe = TRUE;
2144 if (pcap_opts->from_cap_socket)
2147 /* read the pcap header */
2149 while (bytes_read < sizeof magic) {
2150 sel_ret = cap_pipe_select(fd);
2152 g_snprintf(errmsg, errmsgl,
2153 "Unexpected error from select: %s", g_strerror(errno));
2155 } else if (sel_ret > 0) {
2156 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
2157 sizeof magic-bytes_read,
2158 pcap_opts->from_cap_socket);
2161 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2163 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2173 #if GLIB_CHECK_VERSION(2,31,0)
2174 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
2176 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
2179 pcap_opts->cap_pipe_buf = (char *) &magic;
2180 pcap_opts->cap_pipe_bytes_read = 0;
2181 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
2182 /* We don't have to worry about cap_pipe_read_mtx here */
2183 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2184 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2185 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2186 if (pcap_opts->cap_pipe_bytes_read == 0)
2187 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2189 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2198 case PCAP_NSEC_MAGIC:
2199 /* Host that wrote it has our byte order, and was running
2200 a program using either standard or ss990417 libpcap. */
2201 pcap_opts->cap_pipe_byte_swapped = FALSE;
2202 pcap_opts->cap_pipe_modified = FALSE;
2203 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
2205 case PCAP_MODIFIED_MAGIC:
2206 /* Host that wrote it has our byte order, but was running
2207 a program using either ss990915 or ss991029 libpcap. */
2208 pcap_opts->cap_pipe_byte_swapped = FALSE;
2209 pcap_opts->cap_pipe_modified = TRUE;
2211 case PCAP_SWAPPED_MAGIC:
2212 case PCAP_SWAPPED_NSEC_MAGIC:
2213 /* Host that wrote it has a byte order opposite to ours,
2214 and was running a program using either standard or
2215 ss990417 libpcap. */
2216 pcap_opts->cap_pipe_byte_swapped = TRUE;
2217 pcap_opts->cap_pipe_modified = FALSE;
2218 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2220 case PCAP_SWAPPED_MODIFIED_MAGIC:
2221 /* Host that wrote it out has a byte order opposite to
2222 ours, and was running a program using either ss990915
2223 or ss991029 libpcap. */
2224 pcap_opts->cap_pipe_byte_swapped = TRUE;
2225 pcap_opts->cap_pipe_modified = TRUE;
2228 /* Not a "libpcap" type we know about. */
2229 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2234 if (pcap_opts->from_cap_socket)
2237 /* Read the rest of the header */
2239 while (bytes_read < sizeof(struct pcap_hdr)) {
2240 sel_ret = cap_pipe_select(fd);
2242 g_snprintf(errmsg, errmsgl,
2243 "Unexpected error from select: %s", g_strerror(errno));
2245 } else if (sel_ret > 0) {
2246 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2247 sizeof(struct pcap_hdr) - bytes_read,
2248 pcap_opts->from_cap_socket);
2251 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2253 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
2263 pcap_opts->cap_pipe_buf = (char *) hdr;
2264 pcap_opts->cap_pipe_bytes_read = 0;
2265 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
2266 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2267 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2268 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2269 if (pcap_opts->cap_pipe_bytes_read == 0)
2270 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2272 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
2279 if (pcap_opts->cap_pipe_byte_swapped) {
2280 /* Byte-swap the header fields about which we care. */
2281 hdr->version_major = BSWAP16(hdr->version_major);
2282 hdr->version_minor = BSWAP16(hdr->version_minor);
2283 hdr->snaplen = BSWAP32(hdr->snaplen);
2284 hdr->network = BSWAP32(hdr->network);
2286 pcap_opts->linktype = hdr->network;
2288 if (hdr->version_major < 2) {
2289 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2293 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2294 pcap_opts->cap_pipe_err = PIPOK;
2295 pcap_opts->cap_pipe_fd = fd;
2299 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2300 pcap_opts->cap_pipe_err = PIPERR;
2301 cap_pipe_close(fd, pcap_opts->from_cap_socket);
2302 pcap_opts->cap_pipe_fd = -1;
2306 /* We read one record from the pipe, take care of byte order in the record
2307 * header, write the record to the capture file, and update capture statistics. */
2309 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2311 struct pcap_pkthdr phdr;
2312 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2315 #if !GLIB_CHECK_VERSION(2,31,18)
2323 #ifdef LOG_CAPTURE_VERBOSE
2324 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2327 switch (pcap_opts->cap_pipe_state) {
2329 case STATE_EXPECT_REC_HDR:
2331 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2334 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2335 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2336 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2337 pcap_opts->cap_pipe_bytes_read = 0;
2340 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2341 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2342 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2347 case STATE_READ_REC_HDR:
2349 if (pcap_opts->from_cap_socket)
2352 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2353 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
2356 result = PD_PIPE_EOF;
2358 result = PD_PIPE_ERR;
2361 pcap_opts->cap_pipe_bytes_read += b;
2365 #if GLIB_CHECK_VERSION(2,31,18)
2366 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2368 g_get_current_time(&wait_time);
2369 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2370 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2372 if (pcap_opts->cap_pipe_err == PIPEOF) {
2373 result = PD_PIPE_EOF;
2375 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2376 result = PD_PIPE_ERR;
2384 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2386 result = PD_REC_HDR_READ;
2389 case STATE_EXPECT_DATA:
2391 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2394 pcap_opts->cap_pipe_state = STATE_READ_DATA;
2395 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2396 pcap_opts->cap_pipe_bytes_read = 0;
2399 pcap_opts->cap_pipe_buf = (char *) data;
2400 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2401 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2406 case STATE_READ_DATA:
2408 if (pcap_opts->from_cap_socket)
2411 b = cap_pipe_read(pcap_opts->cap_pipe_fd,
2412 data+pcap_opts->cap_pipe_bytes_read,
2413 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
2414 pcap_opts->from_cap_socket);
2417 result = PD_PIPE_EOF;
2419 result = PD_PIPE_ERR;
2422 pcap_opts->cap_pipe_bytes_read += b;
2427 #if GLIB_CHECK_VERSION(2,31,18)
2428 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2430 g_get_current_time(&wait_time);
2431 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2432 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2433 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2434 if (pcap_opts->cap_pipe_err == PIPEOF) {
2435 result = PD_PIPE_EOF;
2437 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2438 result = PD_PIPE_ERR;
2446 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2448 result = PD_DATA_READ;
2452 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2455 } /* switch (pcap_opts->cap_pipe_state) */
2458 * We've now read as much data as we were expecting, so process it.
2462 case PD_REC_HDR_READ:
2463 /* We've read the header. Take care of byte order. */
2464 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2465 &pcap_opts->cap_pipe_rechdr.hdr);
2466 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2467 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2468 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2472 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2473 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2476 /* no data to read? fall through */
2479 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2480 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2481 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2482 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2483 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2486 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2488 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2490 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2494 pcap_opts->cap_pipe_err = PIPEOF;
2499 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2500 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2501 g_snprintf(errmsg, errmsgl,
2502 "Error reading from pipe: %s (error %d)",
2503 utf_16to8(err_str), GetLastError());
2506 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2514 pcap_opts->cap_pipe_err = PIPERR;
2515 /* Return here rather than inside the switch to prevent GCC warning */
2520 /** Open the capture input file (pcap or capture pipe).
2521 * Returns TRUE if it succeeds, FALSE otherwise. */
2523 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2524 char *errmsg, size_t errmsg_len,
2525 char *secondary_errmsg, size_t secondary_errmsg_len)
2527 gchar open_err_str[PCAP_ERRBUF_SIZE];
2528 gchar *sync_msg_str;
2529 interface_options interface_opts;
2530 pcap_options *pcap_opts;
2534 gchar *sync_secondary_msg_str;
2535 WORD wVersionRequested;
2539 /* XXX - opening Winsock on tshark? */
2541 /* Initialize Windows Socket if we are in a WIN32 OS
2542 This needs to be done before querying the interface for network/netmask */
2544 /* XXX - do we really require 1.1 or earlier?
2545 Are there any versions that support only 2.0 or higher? */
2546 wVersionRequested = MAKEWORD(1, 1);
2547 err = WSAStartup(wVersionRequested, &wsaData);
2551 case WSASYSNOTREADY:
2552 g_snprintf(errmsg, (gulong) errmsg_len,
2553 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2556 case WSAVERNOTSUPPORTED:
2557 g_snprintf(errmsg, (gulong) errmsg_len,
2558 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2559 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2562 case WSAEINPROGRESS:
2563 g_snprintf(errmsg, (gulong) errmsg_len,
2564 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2568 g_snprintf(errmsg, (gulong) errmsg_len,
2569 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2573 g_snprintf(errmsg, (gulong) errmsg_len,
2574 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2578 g_snprintf(errmsg, (gulong) errmsg_len,
2579 "Couldn't initialize Windows Sockets: error %d", err);
2582 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2586 if ((use_threads == FALSE) &&
2587 (capture_opts->ifaces->len > 1)) {
2588 g_snprintf(errmsg, (gulong) errmsg_len,
2589 "Using threads is required for capturing on multiple interfaces!");
2593 for (i = 0; i < capture_opts->ifaces->len; i++) {
2594 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2595 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2596 if (pcap_opts == NULL) {
2597 g_snprintf(errmsg, (gulong) errmsg_len,
2598 "Could not allocate memory.");
2601 pcap_opts->received = 0;
2602 pcap_opts->dropped = 0;
2603 pcap_opts->flushed = 0;
2604 pcap_opts->pcap_h = NULL;
2605 #ifdef MUST_DO_SELECT
2606 pcap_opts->pcap_fd = -1;
2608 pcap_opts->pcap_err = FALSE;
2609 pcap_opts->interface_id = i;
2610 pcap_opts->tid = NULL;
2611 pcap_opts->snaplen = 0;
2612 pcap_opts->linktype = -1;
2613 pcap_opts->ts_nsec = FALSE;
2614 pcap_opts->from_cap_pipe = FALSE;
2615 pcap_opts->from_cap_socket = FALSE;
2616 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2617 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2619 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2621 pcap_opts->cap_pipe_fd = -1;
2622 pcap_opts->cap_pipe_modified = FALSE;
2623 pcap_opts->cap_pipe_byte_swapped = FALSE;
2625 pcap_opts->cap_pipe_buf = NULL;
2627 pcap_opts->cap_pipe_bytes_to_read = 0;
2628 pcap_opts->cap_pipe_bytes_read = 0;
2629 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2630 pcap_opts->cap_pipe_err = PIPOK;
2632 #if GLIB_CHECK_VERSION(2,31,0)
2633 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2634 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2636 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2638 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2639 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2641 g_array_append_val(ld->pcaps, pcap_opts);
2643 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2644 pcap_opts->pcap_h = open_capture_device(&interface_opts, &open_err_str);
2646 if (pcap_opts->pcap_h != NULL) {
2647 /* we've opened "iface" as a network device */
2649 /* try to set the capture buffer size */
2650 if (interface_opts.buffer_size > 1 &&
2651 pcap_setbuff(pcap_opts->pcap_h, interface_opts.buffer_size * 1024 * 1024) != 0) {
2652 sync_secondary_msg_str = g_strdup_printf(
2653 "The capture buffer size of %dMB seems to be too high for your machine,\n"
2654 "the default of 1MB will be used.\n"
2656 "Nonetheless, the capture is started.\n",
2657 interface_opts.buffer_size);
2658 report_capture_error("Couldn't set the capture buffer size!",
2659 sync_secondary_msg_str);
2660 g_free(sync_secondary_msg_str);
2664 #if defined(HAVE_PCAP_SETSAMPLING)
2665 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2666 struct pcap_samp *samp;
2668 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2669 switch (interface_opts.sampling_method) {
2670 case CAPTURE_SAMP_BY_COUNT:
2671 samp->method = PCAP_SAMP_1_EVERY_N;
2674 case CAPTURE_SAMP_BY_TIMER:
2675 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2679 sync_msg_str = g_strdup_printf(
2680 "Unknown sampling method %d specified,\n"
2681 "continue without packet sampling",
2682 interface_opts.sampling_method);
2683 report_capture_error("Couldn't set the capture "
2684 "sampling", sync_msg_str);
2685 g_free(sync_msg_str);
2687 samp->value = interface_opts.sampling_param;
2689 report_capture_error("Couldn't set the capture sampling",
2690 "Cannot get packet sampling data structure");
2695 /* setting the data link type only works on real interfaces */
2696 if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2698 secondary_errmsg, secondary_errmsg_len)) {
2701 pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2703 /* We couldn't open "iface" as a network device. */
2704 /* Try to open it as a pipe */
2705 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2708 if (pcap_opts->cap_pipe_fd == -1) {
2710 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2712 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2713 /* Pipe doesn't exist, so output message for interface */
2714 get_capture_device_open_failure_messages(open_err_str,
2715 interface_opts.name,
2719 secondary_errmsg_len);
2722 * Else pipe (or file) does exist and cap_pipe_open_live() has
2727 /* cap_pipe_open_live() succeeded; don't want
2728 error message from pcap_open_live() */
2729 open_err_str[0] = '\0';
2733 /* XXX - will this work for tshark? */
2734 #ifdef MUST_DO_SELECT
2735 if (!pcap_opts->from_cap_pipe) {
2736 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2737 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2739 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2744 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2745 returned a warning; print it, but keep capturing. */
2746 if (open_err_str[0] != '\0') {
2747 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2748 report_capture_error(sync_msg_str, "");
2749 g_free(sync_msg_str);
2751 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2752 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2755 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2756 /* to remove any suid privileges. */
2757 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2758 /* (euid/egid have already previously been set to ruid/rgid. */
2759 /* (See comment in main() for details) */
2761 relinquish_special_privs_perm();
2763 relinquish_all_capabilities();
2768 /* close the capture input file (pcap or capture pipe) */
2769 static void capture_loop_close_input(loop_data *ld)
2772 pcap_options *pcap_opts;
2774 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2776 for (i = 0; i < ld->pcaps->len; i++) {
2777 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2778 /* if open, close the capture pipe "input file" */
2779 if (pcap_opts->cap_pipe_fd >= 0) {
2780 g_assert(pcap_opts->from_cap_pipe);
2781 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2782 pcap_opts->cap_pipe_fd = -1;
2785 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2786 CloseHandle(pcap_opts->cap_pipe_h);
2787 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2790 /* if open, close the pcap "input file" */
2791 if (pcap_opts->pcap_h != NULL) {
2792 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2793 pcap_close(pcap_opts->pcap_h);
2794 pcap_opts->pcap_h = NULL;
2801 /* Shut down windows sockets */
2807 /* init the capture filter */
2808 static initfilter_status_t
2809 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2810 const gchar * name, const gchar * cfilter)
2812 struct bpf_program fcode;
2814 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2816 /* capture filters only work on real interfaces */
2817 if (cfilter && !from_cap_pipe) {
2818 /* A capture filter was specified; set it up. */
2819 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2820 /* Treat this specially - our caller might try to compile this
2821 as a display filter and, if that succeeds, warn the user that
2822 the display and capture filter syntaxes are different. */
2823 return INITFILTER_BAD_FILTER;
2825 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2826 #ifdef HAVE_PCAP_FREECODE
2827 pcap_freecode(&fcode);
2829 return INITFILTER_OTHER_ERROR;
2831 #ifdef HAVE_PCAP_FREECODE
2832 pcap_freecode(&fcode);
2836 return INITFILTER_NO_ERROR;
2840 /* set up to write to the already-opened capture output file/files */
2842 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2846 pcap_options *pcap_opts;
2847 interface_options interface_opts;
2848 gboolean successful;
2850 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2852 if ((capture_opts->use_pcapng == FALSE) &&
2853 (capture_opts->ifaces->len > 1)) {
2854 g_snprintf(errmsg, errmsg_len,
2855 "Using PCAPNG is required for capturing on multiple interfaces! Use the -n option.");
2859 /* Set up to write to the capture file. */
2860 if (capture_opts->multi_files_on) {
2861 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2863 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2864 if (ld->pdh == NULL) {
2869 if (capture_opts->use_pcapng) {
2871 GString *os_info_str;
2873 os_info_str = g_string_new("");
2874 get_os_version_info(os_info_str);
2876 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2877 successful = pcapng_write_session_header_block(ld->pdh,
2878 (const char *)capture_opts->capture_comment, /* Comment*/
2880 os_info_str->str, /* OS*/
2882 -1, /* section_length */
2886 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2887 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2888 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2889 if (pcap_opts->from_cap_pipe) {
2890 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2892 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2894 successful = pcapng_write_interface_description_block(global_ld.pdh,
2895 NULL, /* OPT_COMMENT 1 */
2896 interface_opts.name, /* IDB_NAME 2 */
2897 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2898 interface_opts.cfilter, /* IDB_FILTER 11 */
2899 os_info_str->str, /* IDB_OS 12 */
2900 pcap_opts->linktype,
2902 &(global_ld.bytes_written),
2903 0, /* IDB_IF_SPEED 8 */
2904 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2908 g_string_free(os_info_str, TRUE);
2911 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2912 if (pcap_opts->from_cap_pipe) {
2913 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2915 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2917 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2918 pcap_opts->ts_nsec, &ld->bytes_written, &err);
2926 if (ld->pdh == NULL) {
2927 /* We couldn't set up to write to the capture file. */
2928 /* XXX - use cf_open_error_message from tshark instead? */
2933 g_snprintf(errmsg, errmsg_len,
2934 "The file to which the capture would be"
2935 " saved (\"%s\") could not be opened: Error %d.",
2936 capture_opts->save_file, err);
2938 g_snprintf(errmsg, errmsg_len,
2939 "The file to which the capture would be"
2940 " saved (\"%s\") could not be opened: %s.",
2941 capture_opts->save_file, g_strerror(err));
2953 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2957 pcap_options *pcap_opts;
2958 guint64 end_time = create_timestamp();
2960 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2962 if (capture_opts->multi_files_on) {
2963 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2965 if (capture_opts->use_pcapng) {
2966 for (i = 0; i < global_ld.pcaps->len; i++) {
2967 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2968 if (!pcap_opts->from_cap_pipe) {
2969 guint64 isb_ifrecv, isb_ifdrop;
2970 struct pcap_stat stats;
2972 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
2973 isb_ifrecv = pcap_opts->received;
2974 isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
2976 isb_ifrecv = G_MAXUINT64;
2977 isb_ifdrop = G_MAXUINT64;
2979 pcapng_write_interface_statistics_block(ld->pdh,
2982 "Counters provided by dumpcap",
2991 if (fclose(ld->pdh) == EOF) {
2992 if (err_close != NULL) {
3002 /* dispatch incoming packets (pcap or capture pipe)
3004 * Waits for incoming packets to be available, and calls pcap_dispatch()
3005 * to cause them to be processed.
3007 * Returns the number of packets which were processed.
3009 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3010 * packet-batching behaviour does not cause packets to get held back
3014 capture_loop_dispatch(loop_data *ld,
3015 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
3018 gint packet_count_before;
3019 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
3024 packet_count_before = ld->packet_count;
3025 if (pcap_opts->from_cap_pipe) {
3026 /* dispatch from capture pipe */
3027 #ifdef LOG_CAPTURE_VERBOSE
3028 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3031 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
3033 if (sel_ret < 0 && errno != EINTR) {
3034 g_snprintf(errmsg, errmsg_len,
3035 "Unexpected error from select: %s", g_strerror(errno));
3036 report_capture_error(errmsg, please_report);
3041 * "select()" says we can read from the pipe without blocking
3044 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
3054 /* dispatch from pcap */
3055 #ifdef MUST_DO_SELECT
3057 * If we have "pcap_get_selectable_fd()", we use it to get the
3058 * descriptor on which to select; if that's -1, it means there
3059 * is no descriptor on which you can do a "select()" (perhaps
3060 * because you're capturing on a special device, and that device's
3061 * driver unfortunately doesn't support "select()", in which case
3062 * we don't do the select - which means it might not be possible
3063 * to stop a capture until a packet arrives. If that's unacceptable,
3064 * plead with whoever supplies the software for that device to add
3065 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3066 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3067 * later, so it can use pcap_breakloop().
3069 #ifdef LOG_CAPTURE_VERBOSE
3070 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3072 if (pcap_opts->pcap_fd != -1) {
3073 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
3076 * "select()" says we can read from it without blocking; go for
3079 * We don't have pcap_breakloop(), so we only process one packet
3080 * per pcap_dispatch() call, to allow a signal to stop the
3081 * processing immediately, rather than processing all packets
3082 * in a batch before quitting.
3085 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3087 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3091 /* Error, rather than pcap_breakloop(). */
3092 pcap_opts->pcap_err = TRUE;
3094 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3097 if (sel_ret < 0 && errno != EINTR) {
3098 g_snprintf(errmsg, errmsg_len,
3099 "Unexpected error from select: %s", g_strerror(errno));
3100 report_capture_error(errmsg, please_report);
3106 #endif /* MUST_DO_SELECT */
3108 /* dispatch from pcap without select */
3110 #ifdef LOG_CAPTURE_VERBOSE
3111 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3115 * On Windows, we don't support asynchronously telling a process to
3116 * stop capturing; instead, we check for an indication on a pipe
3117 * after processing packets. We therefore process only one packet
3118 * at a time, so that we can check the pipe after every packet.
3121 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3123 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3127 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3129 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3134 /* Error, rather than pcap_breakloop(). */
3135 pcap_opts->pcap_err = TRUE;
3137 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3139 #else /* pcap_next_ex */
3140 #ifdef LOG_CAPTURE_VERBOSE
3141 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3143 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3146 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3147 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
3148 * This should be fixed in the WinPcap 4.0 alpha release.
3150 * For reference, an example remote interface:
3151 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3154 /* emulate dispatch from pcap */
3157 struct pcap_pkthdr *pkt_header;
3162 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
3164 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3166 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3171 pcap_opts->pcap_err = TRUE;
3175 #endif /* pcap_next_ex */
3179 #ifdef LOG_CAPTURE_VERBOSE
3180 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3183 return ld->packet_count - packet_count_before;
3187 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3188 * want to grab only the characters between the '{' and '}' delimiters.
3190 * Returns a GString that must be freed with g_string_free(). */
3192 isolate_uuid(const char *iface)
3197 ptr = strchr(iface, '{');
3199 return g_string_new(iface);
3200 gstr = g_string_new(ptr + 1);
3202 ptr = strchr(gstr->str, '}');
3206 gstr = g_string_truncate(gstr, ptr - gstr->str);
3211 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3212 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3214 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3215 char *errmsg, int errmsg_len)
3218 gchar *capfile_name;
3220 gboolean is_tempfile;
3222 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3223 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3225 if (capture_opts->save_file != NULL) {
3226 /* We return to the caller while the capture is in progress.
3227 * Therefore we need to take a copy of save_file in
3228 * case the caller destroys it after we return.
3230 capfile_name = g_strdup(capture_opts->save_file);
3232 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3233 if (capture_opts->multi_files_on) {
3234 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3235 g_snprintf(errmsg, errmsg_len,
3236 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3237 g_free(capfile_name);
3240 if (strcmp(capfile_name, "-") == 0) {
3241 /* write to stdout */
3244 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3245 _setmode(1, O_BINARY);
3248 } /* if (...output_to_pipe ... */
3251 if (capture_opts->multi_files_on) {
3252 /* ringbuffer is enabled */
3253 *save_file_fd = ringbuf_init(capfile_name,
3254 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3255 capture_opts->group_read_access);
3257 /* we need the ringbuf name */
3258 if (*save_file_fd != -1) {
3259 g_free(capfile_name);
3260 capfile_name = g_strdup(ringbuf_current_filename());
3263 /* Try to open/create the specified file for use as a capture buffer. */
3264 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
3265 (capture_opts->group_read_access) ? 0640 : 0600);
3268 is_tempfile = FALSE;
3270 /* Choose a random name for the temporary capture buffer */
3271 if (global_capture_opts.ifaces->len > 1) {
3272 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3275 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
3277 /* use the generic portion of the interface guid to form the basis of the filename */
3278 if (strncmp("NPF_{", basename, 5)==0)
3280 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3282 iface = isolate_uuid(basename);
3284 basename = g_strdup(iface->str);
3285 g_string_free(iface, TRUE);
3288 /* generate the temp file name prefix...
3289 * It would be nice if we could specify a pcapng/pcap filename suffix,
3290 * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
3291 if (capture_opts->use_pcapng) {
3292 prefix = g_strconcat("wireshark_pcapng_", basename, NULL);
3294 prefix = g_strconcat("wireshark_pcap_", basename, NULL);
3298 *save_file_fd = create_tempfile(&tmpname, prefix);
3300 capfile_name = g_strdup(tmpname);
3304 /* did we fail to open the output file? */
3305 if (*save_file_fd == -1) {
3307 g_snprintf(errmsg, errmsg_len,
3308 "The temporary file to which the capture would be saved (\"%s\") "
3309 "could not be opened: %s.", capfile_name, g_strerror(errno));
3311 if (capture_opts->multi_files_on) {
3312 ringbuf_error_cleanup();
3315 g_snprintf(errmsg, errmsg_len,
3316 "The file to which the capture would be saved (\"%s\") "
3317 "could not be opened: %s.", capfile_name,
3320 g_free(capfile_name);
3324 if (capture_opts->save_file != NULL) {
3325 g_free(capture_opts->save_file);
3327 capture_opts->save_file = capfile_name;
3328 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3329 "g_free(capfile_name)". */
3335 /* Do the work of handling either the file size or file duration capture
3336 conditions being reached, and switching files or stopping. */
3338 do_file_switch_or_stop(capture_options *capture_opts,
3339 condition *cnd_autostop_files,
3340 condition *cnd_autostop_size,
3341 condition *cnd_file_duration)
3344 pcap_options *pcap_opts;
3345 interface_options interface_opts;
3346 gboolean successful;
3348 if (capture_opts->multi_files_on) {
3349 if (cnd_autostop_files != NULL &&
3350 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
3351 /* no files left: stop here */
3352 global_ld.go = FALSE;
3356 /* Switch to the next ringbuffer file */
3357 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3358 &global_ld.save_file_fd, &global_ld.err)) {
3360 /* File switch succeeded: reset the conditions */
3361 global_ld.bytes_written = 0;
3362 if (capture_opts->use_pcapng) {
3364 GString *os_info_str;
3366 os_info_str = g_string_new("");
3367 get_os_version_info(os_info_str);
3369 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
3370 successful = pcapng_write_session_header_block(global_ld.pdh,
3373 os_info_str->str, /* OS */
3375 -1, /* section_length */
3376 &(global_ld.bytes_written),
3379 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3380 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3381 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3382 successful = pcapng_write_interface_description_block(global_ld.pdh,
3383 NULL, /* OPT_COMMENT 1 */
3384 interface_opts.name, /* IDB_NAME 2 */
3385 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3386 interface_opts.cfilter, /* IDB_FILTER 11 */
3387 os_info_str->str, /* IDB_OS 12 */
3388 pcap_opts->linktype,
3390 &(global_ld.bytes_written),
3391 0, /* IDB_IF_SPEED 8 */
3392 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3396 g_string_free(os_info_str, TRUE);
3399 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3400 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3401 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3404 fclose(global_ld.pdh);
3405 global_ld.pdh = NULL;
3406 global_ld.go = FALSE;
3409 if (cnd_autostop_size)
3410 cnd_reset(cnd_autostop_size);
3411 if (cnd_file_duration)
3412 cnd_reset(cnd_file_duration);
3413 fflush(global_ld.pdh);
3415 report_packet_count(global_ld.inpkts_to_sync_pipe);
3416 global_ld.inpkts_to_sync_pipe = 0;
3417 report_new_capture_file(capture_opts->save_file);
3419 /* File switch failed: stop here */
3420 global_ld.go = FALSE;
3424 /* single file, stop now */
3425 global_ld.go = FALSE;
3432 pcap_read_handler(void* arg)
3434 pcap_options *pcap_opts;
3435 char errmsg[MSG_MAX_LENGTH+1];
3437 pcap_opts = (pcap_options *)arg;
3439 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3440 pcap_opts->interface_id);
3442 while (global_ld.go) {
3443 /* dispatch incoming packets */
3444 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3446 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3447 pcap_opts->interface_id);
3448 g_thread_exit(NULL);
3452 /* Do the low-level work of a capture.
3453 Returns TRUE if it succeeds, FALSE otherwise. */
3455 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3458 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3460 struct timeval upd_time, cur_time;
3464 condition *cnd_file_duration = NULL;
3465 condition *cnd_autostop_files = NULL;
3466 condition *cnd_autostop_size = NULL;
3467 condition *cnd_autostop_duration = NULL;
3470 gboolean cfilter_error = FALSE;
3471 char errmsg[MSG_MAX_LENGTH+1];
3472 char secondary_errmsg[MSG_MAX_LENGTH+1];
3473 pcap_options *pcap_opts;
3474 interface_options interface_opts;
3475 guint i, error_index = 0;
3478 *secondary_errmsg = '\0';
3480 /* init the loop data */
3481 global_ld.go = TRUE;
3482 global_ld.packet_count = 0;
3484 global_ld.report_packet_count = FALSE;
3486 if (capture_opts->has_autostop_packets)
3487 global_ld.packet_max = capture_opts->autostop_packets;
3489 global_ld.packet_max = 0; /* no limit */
3490 global_ld.inpkts_to_sync_pipe = 0;
3491 global_ld.err = 0; /* no error seen yet */
3492 global_ld.pdh = NULL;
3493 global_ld.autostop_files = 0;
3494 global_ld.save_file_fd = -1;
3496 /* We haven't yet gotten the capture statistics. */
3497 *stats_known = FALSE;
3499 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3500 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3502 /* open the "input file" from network interface or capture pipe */
3503 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3504 secondary_errmsg, sizeof(secondary_errmsg))) {
3507 for (i = 0; i < capture_opts->ifaces->len; i++) {
3508 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3509 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3510 /* init the input filter from the network interface (capture pipe will do nothing) */
3512 * When remote capturing WinPCap crashes when the capture filter
3513 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3516 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3517 interface_opts.name,
3518 interface_opts.cfilter?interface_opts.cfilter:"")) {
3520 case INITFILTER_NO_ERROR:
3523 case INITFILTER_BAD_FILTER:
3524 cfilter_error = TRUE;
3526 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3529 case INITFILTER_OTHER_ERROR:
3530 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3531 pcap_geterr(pcap_opts->pcap_h));
3532 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3537 /* If we're supposed to write to a capture file, open it for output
3538 (temporary/specified name/ringbuffer) */
3539 if (capture_opts->saving_to_file) {
3540 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3541 errmsg, sizeof(errmsg))) {
3545 /* set up to write to the already-opened capture output file/files */
3546 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3551 /* XXX - capture SIGTERM and close the capture, in case we're on a
3552 Linux 2.0[.x] system and you have to explicitly close the capture
3553 stream in order to turn promiscuous mode off? We need to do that
3554 in other places as well - and I don't think that works all the
3555 time in any case, due to libpcap bugs. */
3557 /* Well, we should be able to start capturing.
3559 Sync out the capture file, so the header makes it to the file system,
3560 and send a "capture started successfully and capture file created"
3561 message to our parent so that they'll open the capture file and
3562 update its windows to indicate that we have a live capture in
3564 fflush(global_ld.pdh);
3565 report_new_capture_file(capture_opts->save_file);
3568 /* initialize capture stop (and alike) conditions */
3569 init_capture_stop_conditions();
3570 /* create stop conditions */
3571 if (capture_opts->has_autostop_filesize) {
3572 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1024)) {
3573 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1024;
3576 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1024);
3578 if (capture_opts->has_autostop_duration)
3579 cnd_autostop_duration =
3580 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3582 if (capture_opts->multi_files_on) {
3583 if (capture_opts->has_file_duration)
3585 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3587 if (capture_opts->has_autostop_files)
3588 cnd_autostop_files =
3589 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3592 /* init the time values */
3594 upd_time = GetTickCount();
3596 gettimeofday(&upd_time, NULL);
3598 start_time = create_timestamp();
3599 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
3601 /* WOW, everything is prepared! */
3602 /* please fasten your seat belts, we will enter now the actual capture loop */
3604 pcap_queue = g_async_queue_new();
3605 pcap_queue_bytes = 0;
3606 pcap_queue_packets = 0;
3607 for (i = 0; i < global_ld.pcaps->len; i++) {
3608 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3609 #if GLIB_CHECK_VERSION(2,31,0)
3610 /* XXX - Add an interface name here? */
3611 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3613 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3617 while (global_ld.go) {
3618 /* dispatch incoming packets */
3620 pcap_queue_element *queue_element;
3621 #if GLIB_CHECK_VERSION(2,31,18)
3623 g_async_queue_lock(pcap_queue);
3624 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3626 GTimeVal write_thread_time;
3628 g_get_current_time(&write_thread_time);
3629 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3630 g_async_queue_lock(pcap_queue);
3631 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3633 if (queue_element) {
3634 pcap_queue_bytes -= queue_element->phdr.caplen;
3635 pcap_queue_packets -= 1;
3637 g_async_queue_unlock(pcap_queue);
3638 if (queue_element) {
3639 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3640 "Dequeued a packet of length %d captured on interface %d.",
3641 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3643 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3644 &queue_element->phdr,
3646 g_free(queue_element->pd);
3647 g_free(queue_element);
3653 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3654 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3655 sizeof(errmsg), pcap_opts);
3658 /* Were we asked to print packet counts by the SIGINFO handler? */
3659 if (global_ld.report_packet_count) {
3660 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3661 plurality(global_ld.packet_count, "", "s"));
3662 global_ld.report_packet_count = FALSE;
3667 /* any news from our parent (signal pipe)? -> just stop the capture */
3668 if (!signal_pipe_check_running()) {
3669 global_ld.go = FALSE;
3674 global_ld.inpkts_to_sync_pipe += inpkts;
3676 /* check capture size condition */
3677 if (cnd_autostop_size != NULL &&
3678 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3679 /* Capture size limit reached, do we have another file? */
3680 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3681 cnd_autostop_size, cnd_file_duration))
3683 } /* cnd_autostop_size */
3684 if (capture_opts->output_to_pipe) {
3685 fflush(global_ld.pdh);
3689 /* Only update once every 500ms so as not to overload slow displays.
3690 * This also prevents too much context-switching between the dumpcap
3691 * and wireshark processes.
3693 #define DUMPCAP_UPD_TIME 500
3696 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3697 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3699 gettimeofday(&cur_time, NULL);
3700 if ((cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3701 (upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3704 upd_time = cur_time;
3707 if (pcap_stats(pch, stats) >= 0) {
3708 *stats_known = TRUE;
3711 /* Let the parent process know. */
3712 if (global_ld.inpkts_to_sync_pipe) {
3714 fflush(global_ld.pdh);
3716 /* Send our parent a message saying we've written out
3717 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3719 report_packet_count(global_ld.inpkts_to_sync_pipe);
3721 global_ld.inpkts_to_sync_pipe = 0;
3724 /* check capture duration condition */
3725 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3726 /* The maximum capture time has elapsed; stop the capture. */
3727 global_ld.go = FALSE;
3731 /* check capture file duration condition */
3732 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3733 /* duration limit reached, do we have another file? */
3734 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3735 cnd_autostop_size, cnd_file_duration))
3737 } /* cnd_file_duration */
3741 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3743 pcap_queue_element *queue_element;
3745 for (i = 0; i < global_ld.pcaps->len; i++) {
3746 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3747 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3748 pcap_opts->interface_id);
3749 g_thread_join(pcap_opts->tid);
3750 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3751 pcap_opts->interface_id);
3754 g_async_queue_lock(pcap_queue);
3755 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3756 if (queue_element) {
3757 pcap_queue_bytes -= queue_element->phdr.caplen;
3758 pcap_queue_packets -= 1;
3760 g_async_queue_unlock(pcap_queue);
3761 if (queue_element == NULL) {
3764 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3765 "Dequeued a packet of length %d captured on interface %d.",
3766 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3767 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3768 &queue_element->phdr,
3770 g_free(queue_element->pd);
3771 g_free(queue_element);
3772 global_ld.inpkts_to_sync_pipe += 1;
3773 if (capture_opts->output_to_pipe) {
3774 fflush(global_ld.pdh);
3780 /* delete stop conditions */
3781 if (cnd_file_duration != NULL)
3782 cnd_delete(cnd_file_duration);
3783 if (cnd_autostop_files != NULL)
3784 cnd_delete(cnd_autostop_files);
3785 if (cnd_autostop_size != NULL)
3786 cnd_delete(cnd_autostop_size);
3787 if (cnd_autostop_duration != NULL)
3788 cnd_delete(cnd_autostop_duration);
3790 /* did we have a pcap (input) error? */
3791 for (i = 0; i < capture_opts->ifaces->len; i++) {
3792 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3793 if (pcap_opts->pcap_err) {
3794 /* On Linux, if an interface goes down while you're capturing on it,
3795 you'll get a "recvfrom: Network is down" or
3796 "The interface went down" error (ENETDOWN).
3797 (At least you will if g_strerror() doesn't show a local translation
3800 On FreeBSD and OS X, if a network adapter disappears while
3801 you're capturing on it, you'll get a "read: Device not configured"
3802 error (ENXIO). (See previous parenthetical note.)
3804 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3806 These should *not* be reported to the Wireshark developers. */
3809 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3810 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3811 strcmp(cap_err_str, "The interface went down") == 0 ||
3812 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3813 strcmp(cap_err_str, "read: I/O error") == 0 ||
3814 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3815 report_capture_error("The network adapter on which the capture was being done "
3816 "is no longer running; the capture has stopped.",
3819 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3821 report_capture_error(errmsg, please_report);
3824 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3825 report_capture_error(errmsg, "");
3829 /* did we have an output error while capturing? */
3830 if (global_ld.err == 0) {
3833 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3834 global_ld.err, FALSE);
3835 report_capture_error(errmsg, please_report);
3839 if (capture_opts->saving_to_file) {
3840 /* close the output file */
3841 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3845 /* there might be packets not yet notified to the parent */
3846 /* (do this after closing the file, so all packets are already flushed) */
3847 if (global_ld.inpkts_to_sync_pipe) {
3849 report_packet_count(global_ld.inpkts_to_sync_pipe);
3850 global_ld.inpkts_to_sync_pipe = 0;
3853 /* If we've displayed a message about a write error, there's no point
3854 in displaying another message about an error on close. */
3855 if (!close_ok && write_ok) {
3856 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3858 report_capture_error(errmsg, "");
3862 * XXX We exhibit different behaviour between normal mode and sync mode
3863 * when the pipe is stdin and not already at EOF. If we're a child, the
3864 * parent's stdin isn't closed, so if the user starts another capture,
3865 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3866 * will say "Unrecognized libpcap format". On the other hand, in normal
3867 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3870 report_capture_count(TRUE);
3872 /* get packet drop statistics from pcap */
3873 for (i = 0; i < capture_opts->ifaces->len; i++) {
3875 guint32 pcap_dropped = 0;
3877 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3878 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3879 received = pcap_opts->received;
3880 if (pcap_opts->pcap_h != NULL) {
3881 g_assert(!pcap_opts->from_cap_pipe);
3882 /* Get the capture statistics, so we know how many packets were dropped. */
3884 * Older versions of libpcap didn't set ps_ifdrop on some
3885 * platforms; initialize it to 0 to handle that.
3887 stats->ps_ifdrop = 0;
3888 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3889 *stats_known = TRUE;
3890 /* Let the parent process know. */
3891 pcap_dropped += stats->ps_drop;
3893 g_snprintf(errmsg, sizeof(errmsg),
3894 "Can't get packet-drop statistics: %s",
3895 pcap_geterr(pcap_opts->pcap_h));
3896 report_capture_error(errmsg, please_report);
3899 report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
3902 /* close the input file (pcap or capture pipe) */
3903 capture_loop_close_input(&global_ld);
3905 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3907 /* ok, if the write and the close were successful. */
3908 return write_ok && close_ok;
3911 if (capture_opts->multi_files_on) {
3912 /* cleanup ringbuffer */
3913 ringbuf_error_cleanup();
3915 /* We can't use the save file, and we have no FILE * for the stream
3916 to close in order to close it, so close the FD directly. */
3917 if (global_ld.save_file_fd != -1) {
3918 ws_close(global_ld.save_file_fd);
3921 /* We couldn't even start the capture, so get rid of the capture
3923 if (capture_opts->save_file != NULL) {
3924 ws_unlink(capture_opts->save_file);
3925 g_free(capture_opts->save_file);
3928 capture_opts->save_file = NULL;
3930 report_cfilter_error(capture_opts, error_index, errmsg);
3932 report_capture_error(errmsg, secondary_errmsg);
3934 /* close the input file (pcap or cap_pipe) */
3935 capture_loop_close_input(&global_ld);
3937 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3944 capture_loop_stop(void)
3946 #ifdef HAVE_PCAP_BREAKLOOP
3948 pcap_options *pcap_opts;
3950 for (i = 0; i < global_ld.pcaps->len; i++) {
3951 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3952 if (pcap_opts->pcap_h != NULL)
3953 pcap_breakloop(pcap_opts->pcap_h);
3956 global_ld.go = FALSE;
3961 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3962 int err, gboolean is_close)
3967 g_snprintf(errmsg, errmsglen,
3968 "Not all the packets could be written to the file"
3969 " to which the capture was being saved\n"
3970 "(\"%s\") because there is no space left on the file system\n"
3971 "on which that file resides.",
3977 g_snprintf(errmsg, errmsglen,
3978 "Not all the packets could be written to the file"
3979 " to which the capture was being saved\n"
3980 "(\"%s\") because you are too close to, or over,"
3981 " your disk quota\n"
3982 "on the file system on which that file resides.",
3989 g_snprintf(errmsg, errmsglen,
3990 "The file to which the capture was being saved\n"
3991 "(\"%s\") could not be closed: %s.",
3992 fname, g_strerror(err));
3994 g_snprintf(errmsg, errmsglen,
3995 "An error occurred while writing to the file"
3996 " to which the capture was being saved\n"
3998 fname, g_strerror(err));
4005 /* one packet was captured, process it */
4007 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4010 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4012 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
4014 /* We may be called multiple times from pcap_dispatch(); if we've set
4015 the "stop capturing" flag, ignore this packet, as we're not
4016 supposed to be saving any more packets. */
4017 if (!global_ld.go) {
4018 pcap_opts->flushed++;
4022 if (global_ld.pdh) {
4023 gboolean successful;
4025 /* We're supposed to write the packet to a file; do so.
4026 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4027 "ld->err" to the error. */
4028 if (global_capture_opts.use_pcapng) {
4029 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4031 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4032 phdr->caplen, phdr->len,
4033 pcap_opts->interface_id,
4036 &global_ld.bytes_written, &err);
4038 successful = libpcap_write_packet(global_ld.pdh,
4039 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4040 phdr->caplen, phdr->len,
4042 &global_ld.bytes_written, &err);
4045 global_ld.go = FALSE;
4046 global_ld.err = err;
4047 pcap_opts->dropped++;
4049 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4050 "Wrote a packet of length %d captured on interface %u.",
4051 phdr->caplen, pcap_opts->interface_id);
4052 global_ld.packet_count++;
4053 pcap_opts->received++;
4054 /* if the user told us to stop after x packets, do we already have enough? */
4055 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4056 global_ld.go = FALSE;
4062 /* one packet was captured, queue it */
4064 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4067 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4068 pcap_queue_element *queue_element;
4069 gboolean limit_reached;
4071 /* We may be called multiple times from pcap_dispatch(); if we've set
4072 the "stop capturing" flag, ignore this packet, as we're not
4073 supposed to be saving any more packets. */
4074 if (!global_ld.go) {
4075 pcap_opts->flushed++;
4079 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4080 if (queue_element == NULL) {
4081 pcap_opts->dropped++;
4084 queue_element->pcap_opts = pcap_opts;
4085 queue_element->phdr = *phdr;
4086 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4087 if (queue_element->pd == NULL) {
4088 pcap_opts->dropped++;
4089 g_free(queue_element);
4092 memcpy(queue_element->pd, pd, phdr->caplen);
4093 g_async_queue_lock(pcap_queue);
4094 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4095 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4096 limit_reached = FALSE;
4097 g_async_queue_push_unlocked(pcap_queue, queue_element);
4098 pcap_queue_bytes += phdr->caplen;
4099 pcap_queue_packets += 1;
4101 limit_reached = TRUE;
4103 g_async_queue_unlock(pcap_queue);
4104 if (limit_reached) {
4105 pcap_opts->dropped++;
4106 g_free(queue_element->pd);
4107 g_free(queue_element);
4108 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4109 "Dropped a packet of length %d captured on interface %u.",
4110 phdr->caplen, pcap_opts->interface_id);
4112 pcap_opts->received++;
4113 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4114 "Queued a packet of length %d captured on interface %u.",
4115 phdr->caplen, pcap_opts->interface_id);
4117 /* I don't want to hold the mutex over the debug output. So the
4118 output may be wrong */
4119 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4120 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4121 pcap_queue_bytes, pcap_queue_packets);
4125 set_80211_channel(const char *iface, const char *opt)
4127 int freq = 0, type, ret;
4128 gchar **options = NULL;
4130 options = g_strsplit_set(opt, ",", 2);
4133 freq = atoi(options[0]);
4136 type = ws80211_str_to_chan_type(options[1]);
4145 ret = ws80211_init();
4147 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4151 ret = ws80211_set_freq(iface, freq, type);
4154 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4160 pipe_write_block(2, SP_SUCCESS, NULL);
4164 g_strfreev(options);
4168 /* And now our feature presentation... [ fade to music ] */
4170 main(int argc, char *argv[])
4172 GString *comp_info_str;
4173 GString *runtime_info_str;
4175 struct option long_options[] = {
4176 {(char *)"capture-comment", required_argument, NULL, LONGOPT_NUM_CAP_COMMENT },
4180 gboolean arg_error = FALSE;
4185 struct sigaction action, oldaction;
4188 gboolean start_capture = TRUE;
4189 gboolean stats_known;
4190 struct pcap_stat stats;
4191 GLogLevelFlags log_flags;
4192 gboolean list_interfaces = FALSE;
4193 gboolean list_link_layer_types = FALSE;
4194 #ifdef HAVE_BPF_IMAGE
4195 gboolean print_bpf_code = FALSE;
4197 gboolean set_chan = FALSE;
4198 gchar *set_chan_arg = NULL;
4199 gboolean machine_readable = FALSE;
4200 gboolean print_statistics = FALSE;
4201 int status, run_once_args = 0;
4204 #if defined(__APPLE__) && defined(__LP64__)
4205 struct utsname osinfo;
4209 /* Assemble the compile-time version information string */
4210 comp_info_str = g_string_new("Compiled ");
4211 get_compiled_version_info(comp_info_str, NULL, NULL);
4213 /* Assemble the run-time version information string */
4214 runtime_info_str = g_string_new("Running ");
4215 get_runtime_version_info(runtime_info_str, NULL);
4217 /* Add it to the information to be reported on a crash. */
4218 ws_add_crash_info("Dumpcap " VERSION "%s\n"
4223 wireshark_svnversion, comp_info_str->str, runtime_info_str->str);
4226 arg_list_utf_16to8(argc, argv);
4227 create_app_running_mutex();
4230 * Initialize our DLL search path. MUST be called before LoadLibrary
4233 ws_init_dll_search_path();
4236 #ifdef HAVE_PCAP_REMOTE
4237 #define OPTSTRING_A "A:"
4238 #define OPTSTRING_r "r"
4239 #define OPTSTRING_u "u"
4241 #define OPTSTRING_A ""
4242 #define OPTSTRING_r ""
4243 #define OPTSTRING_u ""
4246 #ifdef HAVE_PCAP_SETSAMPLING
4247 #define OPTSTRING_m "m:"
4249 #define OPTSTRING_m ""
4252 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4253 #define OPTSTRING_B "B:"
4255 #define OPTSTRING_B ""
4256 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4258 #ifdef HAVE_PCAP_CREATE
4259 #define OPTSTRING_I "I"
4261 #define OPTSTRING_I ""
4264 #ifdef HAVE_BPF_IMAGE
4265 #define OPTSTRING_d "d"
4267 #define OPTSTRING_d ""
4270 #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:"
4272 #ifdef DEBUG_CHILD_DUMPCAP
4273 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4274 fprintf (stderr, "Unable to open debug log file !\n");
4279 #if defined(__APPLE__) && defined(__LP64__)
4281 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4282 * a bug workaround - timeouts less than 1 second don't work with libpcap
4283 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4284 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4285 * The problem is extremely unlikely to be reintroduced in a future
4288 if (uname(&osinfo) == 0) {
4290 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
4291 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4292 * number of 10.0.0, not 10.1.0 - go figure).
4294 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4295 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4296 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4297 need_timeout_workaround = TRUE;
4302 * Determine if dumpcap is being requested to run in a special
4303 * capture_child mode by going thru the command line args to see if
4304 * a -Z is present. (-Z is a hidden option).
4306 * The primary result of running in capture_child mode is that
4307 * all messages sent out on stderr are in a special type/len/string
4308 * format to allow message processing by type. These messages include
4309 * error messages if dumpcap fails to start the operation it was
4310 * requested to do, as well as various "status" messages which are sent
4311 * when an actual capture is in progress, and a "success" message sent
4312 * if dumpcap was requested to perform an operation other than a
4315 * Capture_child mode would normally be requested by a parent process
4316 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4317 * to which dumpcap stderr has been redirected. It might also have
4318 * another pipe to obtain dumpcap stdout output; for operations other
4319 * than a capture, that information is formatted specially for easier
4320 * parsing by the parent process.
4322 * Capture_child mode needs to be determined immediately upon
4323 * startup so that any messages generated by dumpcap in this mode
4324 * (eg: during initialization) will be formatted properly.
4327 for (i=1; i<argc; i++) {
4328 if (strcmp("-Z", argv[i]) == 0) {
4329 capture_child = TRUE;
4330 machine_readable = TRUE; /* request machine-readable output */
4332 /* set output pipe to binary mode, to avoid ugly text conversions */
4333 _setmode(2, O_BINARY);
4338 /* The default_log_handler will use stdout, which makes trouble in */
4339 /* capture child mode, as it uses stdout for its sync_pipe. */
4340 /* So: the filtering is done in the console_log_handler and not here.*/
4341 /* We set the log handlers right up front to make sure that any log */
4342 /* messages when running as child will be sent back to the parent */
4343 /* with the correct format. */
4348 G_LOG_LEVEL_CRITICAL|
4349 G_LOG_LEVEL_WARNING|
4350 G_LOG_LEVEL_MESSAGE|
4354 G_LOG_FLAG_RECURSION);
4356 g_log_set_handler(NULL,
4358 console_log_handler, NULL /* user_data */);
4359 g_log_set_handler(LOG_DOMAIN_MAIN,
4361 console_log_handler, NULL /* user_data */);
4362 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4364 console_log_handler, NULL /* user_data */);
4365 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4367 console_log_handler, NULL /* user_data */);
4369 /* Initialize the pcaps list */
4370 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
4372 #if !GLIB_CHECK_VERSION(2,31,0)
4373 /* Initialize the thread system */
4374 g_thread_init(NULL);
4378 /* Load wpcap if possible. Do this before collecting the run-time version information */
4381 /* ... and also load the packet.dll from wpcap */
4382 /* XXX - currently not required, may change later. */
4383 /*wpcap_packet_load();*/
4385 /* Start windows sockets */
4386 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4388 /* Set handler for Ctrl+C key */
4389 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4391 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4392 and exit. Do the same with SIGPIPE, in case, for example,
4393 we're writing to our standard output and it's a pipe.
4394 Do the same with SIGHUP if it's not being ignored (if we're
4395 being run under nohup, it might be ignored, in which case we
4396 should leave it ignored).
4398 XXX - apparently, Coverity complained that part of action
4399 wasn't initialized. Perhaps it's running on Linux, where
4400 struct sigaction has an ignored "sa_restorer" element and
4401 where "sa_handler" and "sa_sigaction" might not be two
4402 members of a union. */
4403 memset(&action, 0, sizeof(action));
4404 action.sa_handler = capture_cleanup_handler;
4406 * Arrange that system calls not get restarted, because when
4407 * our signal handler returns we don't want to restart
4408 * a call that was waiting for packets to arrive.
4410 action.sa_flags = 0;
4411 sigemptyset(&action.sa_mask);
4412 sigaction(SIGTERM, &action, NULL);
4413 sigaction(SIGINT, &action, NULL);
4414 sigaction(SIGPIPE, &action, NULL);
4415 sigaction(SIGHUP, NULL, &oldaction);
4416 if (oldaction.sa_handler == SIG_DFL)
4417 sigaction(SIGHUP, &action, NULL);
4420 /* Catch SIGINFO and, if we get it and we're capturing in
4421 quiet mode, report the number of packets we've captured. */
4422 action.sa_handler = report_counts_siginfo;
4423 action.sa_flags = SA_RESTART;
4424 sigemptyset(&action.sa_mask);
4425 sigaction(SIGINFO, &action, NULL);
4426 #endif /* SIGINFO */
4430 enable_kernel_bpf_jit_compiler();
4433 /* ----------------------------------------------------------------- */
4434 /* Privilege and capability handling */
4436 /* 1. Running not as root or suid root; no special capabilities. */
4439 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4442 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4444 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4445 /* capabilities; Drop all other capabilities; */
4446 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4447 /* else: after pcap_open_live() in capture_loop_open_input() */
4448 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4449 /* (Note: this means that the process, although logged in */
4450 /* as root, does not have various permissions such as the */
4451 /* ability to bypass file access permissions). */
4452 /* XXX: Should we just leave capabilities alone in this case */
4453 /* so that user gets expected effect that root can do */
4456 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4458 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4459 /* else: after pcap_open_live() in capture_loop_open_input() */
4460 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4461 /* pcap_open_live). */
4463 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4465 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4466 /* capabilities; Drop all other capabilities; */
4467 /* Drop suid privileges (euid=ruid); */
4468 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4469 /* else: after pcap_open_live() in capture_loop_open_input() */
4470 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4472 /* XXX: For some Linux versions/distros with capabilities */
4473 /* a 'normal' process with any capabilities cannot be */
4474 /* 'killed' (signaled) from another (same uid) non-privileged */
4476 /* For example: If (non-suid) Wireshark forks a */
4477 /* child suid dumpcap which acts as described here (case 5), */
4478 /* Wireshark will be unable to kill (signal) the child */
4479 /* dumpcap process until the capabilities have been dropped */
4480 /* (after pcap_open_live()). */
4481 /* This behaviour will apparently be changed in the kernel */
4482 /* to allow the kill (signal) in this case. */
4483 /* See the following for details: */
4484 /* http://www.mail-archive.com/ [wrapped] */
4485 /* linux-security-module@vger.kernel.org/msg02913.html */
4487 /* It is therefore conceivable that if dumpcap somehow hangs */
4488 /* in pcap_open_live or before that wireshark will not */
4489 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4490 /* In this case, exiting wireshark will kill the child */
4491 /* dumpcap process. */
4493 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4494 /* capabilities; Using libcap. Note: capset cmd (which see) */
4495 /* used to assign capabilities to file. */
4497 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4498 /* else: after pcap_open_live() in capture_loop_open_input() */
4499 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4501 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4502 /* longer required (similar to capture). */
4504 /* ----------------------------------------------------------------- */
4506 init_process_policies();
4509 /* If 'started with special privileges' (and using libcap) */
4510 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4511 /* Set euid/egid = ruid/rgid to remove suid privileges */
4512 relinquish_privs_except_capture();
4515 /* Set the initial values in the capture options. This might be overwritten
4516 by the command line parameters. */
4517 capture_opts_init(&global_capture_opts);
4519 /* We always save to a file - if no file was specified, we save to a
4521 global_capture_opts.saving_to_file = TRUE;
4522 global_capture_opts.has_ring_num_files = TRUE;
4524 /* Pass on capture_child mode for capture_opts */
4525 global_capture_opts.capture_child = capture_child;
4527 /* Now get our args */
4528 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4530 case 'h': /* Print help and exit */
4534 case 'v': /* Show version and exit */
4536 show_version(comp_info_str, runtime_info_str);
4537 g_string_free(comp_info_str, TRUE);
4538 g_string_free(runtime_info_str, TRUE);
4542 /*** capture option specific ***/
4543 case 'a': /* autostop criteria */
4544 case 'b': /* Ringbuffer option */
4545 case 'c': /* Capture x packets */
4546 case 'f': /* capture filter */
4547 case 'g': /* enable group read access on file(s) */
4548 case 'i': /* Use interface x */
4549 case 'n': /* Use pcapng format */
4550 case 'p': /* Don't capture in promiscuous mode */
4551 case 'P': /* Use pcap format */
4552 case 's': /* Set the snapshot (capture) length */
4553 case 'w': /* Write to capture file x */
4554 case 'y': /* Set the pcap data link type */
4555 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4556 #ifdef HAVE_PCAP_REMOTE
4557 case 'u': /* Use UDP for data transfer */
4558 case 'r': /* Capture own RPCAP traffic too */
4559 case 'A': /* Authentication */
4561 #ifdef HAVE_PCAP_SETSAMPLING
4562 case 'm': /* Sampling */
4564 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4565 case 'B': /* Buffer size */
4566 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4567 #ifdef HAVE_PCAP_CREATE
4568 case 'I': /* Monitor mode */
4570 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4575 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4577 capture_child = TRUE;
4579 /* set output pipe to binary mode, to avoid ugly text conversions */
4580 _setmode(2, O_BINARY);
4582 * optarg = the control ID, aka the PPID, currently used for the
4585 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4586 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4587 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4588 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4590 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4591 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4592 "Signal pipe: Unable to open %s. Dead parent?",
4600 case 'q': /* Quiet */
4606 /*** all non capture option specific ***/
4607 case 'D': /* Print a list of capture devices and exit */
4608 list_interfaces = TRUE;
4611 case 'L': /* Print list of link-layer types and exit */
4612 list_link_layer_types = TRUE;
4615 #ifdef HAVE_BPF_IMAGE
4616 case 'd': /* Print BPF code for capture filter and exit */
4617 print_bpf_code = TRUE;
4621 case 'S': /* Print interface statistics once a second */
4622 print_statistics = TRUE;
4625 case 'k': /* Set wireless channel */
4627 set_chan_arg = optarg;
4630 case 'M': /* For -D, -L, and -S, print machine-readable output */
4631 machine_readable = TRUE;
4634 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4637 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4640 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4642 case '?': /* Bad flag - print usage message */
4651 /* user specified file name as regular command-line argument */
4652 /* XXX - use it as the capture file name (or something else)? */
4658 * Extra command line arguments were specified; complain.
4659 * XXX - interpret as capture filter, as tcpdump and tshark do?
4661 cmdarg_err("Invalid argument: %s", argv[0]);
4666 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4669 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4670 /* Use some default if the user hasn't specified some */
4671 /* XXX: Are these defaults good enough? */
4672 pcap_queue_byte_limit = 1000 * 1000;
4673 pcap_queue_packet_limit = 1000;
4680 if (run_once_args > 1) {
4681 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4683 } else if (run_once_args == 1) {
4684 /* We're supposed to print some information, rather than
4685 to capture traffic; did they specify a ring buffer option? */
4686 if (global_capture_opts.multi_files_on) {
4687 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4691 /* We're supposed to capture traffic; */
4693 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4694 if (global_capture_opts.ifaces->len > 1) {
4696 global_capture_opts.use_pcapng = TRUE;
4699 if (global_capture_opts.capture_comment &&
4700 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4701 /* XXX - for ringbuffer, should we apply the comment to each file? */
4702 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4706 /* Was the ring buffer option specified and, if so, does it make sense? */
4707 if (global_capture_opts.multi_files_on) {
4708 /* Ring buffer works only under certain conditions:
4709 a) ring buffer does not work with temporary files;
4710 b) it makes no sense to enable the ring buffer if the maximum
4711 file size is set to "infinite". */
4712 if (global_capture_opts.save_file == NULL) {
4713 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4714 global_capture_opts.multi_files_on = FALSE;
4716 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4717 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4719 /* XXX - this must be redesigned as the conditions changed */
4720 global_capture_opts.multi_files_on = FALSE;
4727 * "-D" requires no interface to be selected; it's supposed to list
4730 if (list_interfaces) {
4731 /* Get the list of interfaces */
4736 if_list = capture_interface_list(&err, &err_str,NULL);
4737 if (if_list == NULL) {
4739 case CANT_GET_INTERFACE_LIST:
4740 case DONT_HAVE_PCAP:
4741 cmdarg_err("%s", err_str);
4746 case NO_INTERFACES_FOUND:
4748 * If we're being run by another program, just give them
4749 * an empty list of interfaces, don't report this as
4750 * an error; that lets them decide whether to report
4751 * this as an error or not.
4753 if (!machine_readable) {
4754 cmdarg_err("There are no interfaces on which a capture can be done");
4761 if (machine_readable) /* tab-separated values to stdout */
4762 print_machine_readable_interfaces(if_list);
4764 capture_opts_print_interfaces(if_list);
4765 free_interface_list(if_list);
4770 * "-S" requires no interface to be selected; it gives statistics
4771 * for all interfaces.
4773 if (print_statistics) {
4774 status = print_statistics_loop(machine_readable);
4779 interface_options interface_opts;
4781 if (global_capture_opts.ifaces->len != 1) {
4782 cmdarg_err("Need one interface");
4786 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4787 status = set_80211_channel(interface_opts.name, set_chan_arg);
4792 * "-L", "-d", and capturing act on a particular interface, so we have to
4793 * have an interface; if none was specified, pick a default.
4795 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4797 /* cmdarg_err() already called .... */
4801 /* Let the user know what interfaces were chosen. */
4802 if (capture_child) {
4803 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4804 interface_options interface_opts;
4806 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4807 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4808 interface_opts.name);
4811 str = g_string_new("");
4813 if (global_capture_opts.ifaces->len < 2)
4815 if (global_capture_opts.ifaces->len < 4)
4818 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4819 interface_options interface_opts;
4821 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4823 if (global_capture_opts.ifaces->len > 2) {
4824 g_string_append_printf(str, ",");
4826 g_string_append_printf(str, " ");
4827 if (j == global_capture_opts.ifaces->len - 1) {
4828 g_string_append_printf(str, "and ");
4831 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4834 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4836 fprintf(stderr, "Capturing on %s\n", str->str);
4837 g_string_free(str, TRUE);
4840 if (list_link_layer_types) {
4841 /* Get the list of link-layer types for the capture device. */
4842 if_capabilities_t *caps;
4846 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4847 interface_options interface_opts;
4849 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4850 caps = get_if_capabilities(interface_opts.name,
4851 interface_opts.monitor_mode, &err_str);
4853 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4854 "Please check to make sure you have sufficient permissions, and that\n"
4855 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4859 if (caps->data_link_types == NULL) {
4860 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4863 if (machine_readable) /* tab-separated values to stdout */
4864 /* XXX: We need to change the format and adopt consumers */
4865 print_machine_readable_if_capabilities(caps);
4867 /* XXX: We might want to print also the interface name */
4868 capture_opts_print_if_capabilities(caps, interface_opts.name,
4869 interface_opts.monitor_mode);
4870 free_if_capabilities(caps);
4875 /* We're supposed to do a capture, or print the BPF code for a filter.
4876 Process the snapshot length, as that affects the generated BPF code. */
4877 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4879 #ifdef HAVE_BPF_IMAGE
4880 if (print_bpf_code) {
4881 show_filter_code(&global_capture_opts);
4886 /* We're supposed to do a capture. Process the ring buffer arguments. */
4887 capture_opts_trim_ring_num_files(&global_capture_opts);
4889 /* flush stderr prior to starting the main capture loop */
4892 /* Now start the capture. */
4894 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4898 /* capture failed */
4901 return 0; /* never here, make compiler happy */
4906 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4907 const char *message, gpointer user_data _U_)
4914 /* ignore log message, if log_level isn't interesting */
4915 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4916 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4921 /* create a "timestamp" */
4923 today = localtime(&curr);
4925 switch(log_level & G_LOG_LEVEL_MASK) {
4926 case G_LOG_LEVEL_ERROR:
4929 case G_LOG_LEVEL_CRITICAL:
4932 case G_LOG_LEVEL_WARNING:
4935 case G_LOG_LEVEL_MESSAGE:
4938 case G_LOG_LEVEL_INFO:
4941 case G_LOG_LEVEL_DEBUG:
4945 fprintf(stderr, "unknown log_level %u\n", log_level);
4947 g_assert_not_reached();
4950 /* Generate the output message */
4951 if (log_level & G_LOG_LEVEL_MESSAGE) {
4952 /* normal user messages without additional infos */
4953 msg = g_strdup_printf("%s\n", message);
4955 /* info/debug messages with additional infos */
4956 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4957 today->tm_hour, today->tm_min, today->tm_sec,
4958 log_domain != NULL ? log_domain : "",
4962 /* DEBUG & INFO msgs (if we're debugging today) */
4963 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4964 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4965 #ifdef DEBUG_DUMPCAP
4966 fprintf(stderr, "%s", msg);
4969 #ifdef DEBUG_CHILD_DUMPCAP
4970 fprintf(debug_log, "%s", msg);
4978 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4979 /* to parent especially formatted if dumpcap running as child. */
4980 if (capture_child) {
4981 sync_pipe_errmsg_to_parent(2, msg, "");
4983 fprintf(stderr, "%s", msg);
4990 /****************************************************************************************************************/
4991 /* indication report routines */
4995 report_packet_count(unsigned int packet_count)
4997 char tmp[SP_DECISIZE+1+1];
4998 static unsigned int count = 0;
5000 if (capture_child) {
5001 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
5002 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
5003 pipe_write_block(2, SP_PACKET_COUNT, tmp);
5005 count += packet_count;
5006 fprintf(stderr, "\rPackets: %u ", count);
5007 /* stderr could be line buffered */
5013 report_new_capture_file(const char *filename)
5015 if (capture_child) {
5016 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
5017 pipe_write_block(2, SP_FILE, filename);
5021 * Prevent a SIGINFO handler from writing to the standard error
5022 * while we're doing so; instead, have it just set a flag telling
5023 * us to print that information when we're done.
5026 #endif /* SIGINFO */
5027 fprintf(stderr, "File: %s\n", filename);
5028 /* stderr could be line buffered */
5033 * Allow SIGINFO handlers to write.
5038 * If a SIGINFO handler asked us to write out capture counts, do so.
5041 report_counts_for_siginfo();
5042 #endif /* SIGINFO */
5047 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5049 interface_options interface_opts;
5050 char tmp[MSG_MAX_LENGTH+1+6];
5052 if (i < capture_opts->ifaces->len) {
5053 if (capture_child) {
5054 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5055 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5056 pipe_write_block(2, SP_BAD_FILTER, tmp);
5059 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5060 * the error message below.
5062 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
5064 "Invalid capture filter \"%s\" for interface '%s'!\n"
5066 "That string isn't a valid capture filter (%s).\n"
5067 "See the User's Guide for a description of the capture filter syntax.",
5068 interface_opts.cfilter, interface_opts.name, errmsg);
5074 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5076 if (capture_child) {
5077 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5078 "Primary Error: %s", error_msg);
5079 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5080 "Secondary Error: %s", secondary_error_msg);
5081 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5083 cmdarg_err("%s", error_msg);
5084 if (secondary_error_msg[0] != '\0')
5085 cmdarg_err_cont("%s", secondary_error_msg);
5090 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
5092 char tmp[SP_DECISIZE+1+1];
5093 guint32 total_drops = pcap_drops + drops + flushed;
5095 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5097 if (capture_child) {
5098 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5099 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5100 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
5101 /* XXX: Need to provide interface id, changes to consumers required. */
5102 pipe_write_block(2, SP_DROPS, tmp);
5105 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5106 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
5107 received ? 100.0 * received / (received + total_drops) : 0.0);
5108 /* stderr could be line buffered */
5114 /************************************************************************************************/
5115 /* signal_pipe handling */
5120 signal_pipe_check_running(void)
5122 /* any news from our parent? -> just stop the capture */
5126 /* if we are running standalone, no check required */
5127 if (!capture_child) {
5131 if (!sig_pipe_name || !sig_pipe_handle) {
5132 /* This shouldn't happen */
5133 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5134 "Signal pipe: No name or handle");
5139 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5140 * at this point. Should we check to see if the parent is still alive,
5141 * e.g. by using OpenProcess?
5144 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5146 if (!result || avail > 0) {
5147 /* peek failed or some bytes really available */
5148 /* (if not piping from stdin this would fail) */
5149 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5150 "Signal pipe: Stop capture: %s", sig_pipe_name);
5151 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5152 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
5153 sig_pipe_handle, result, avail);
5156 /* pipe ok and no bytes available */
5167 * Editor modelines - http://www.wireshark.org/tools/modelines.html
5172 * indent-tabs-mode: nil
5175 * vi: set shiftwidth=4 tabstop=8 expandtab:
5176 * :indentSize=4:tabSize=8:noTabs=true: