3 * Wireshark - Network traffic analyzer
4 * By Gerald Combs <gerald@wireshark.org>
5 * Copyright 1998 Gerald Combs
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include <stdlib.h> /* for exit() */
30 #ifdef HAVE_SYS_TYPES_H
31 # include <sys/types.h>
34 #ifdef HAVE_SYS_SOCKET_H
35 #include <sys/socket.h>
38 #ifdef HAVE_NETINET_IN_H
39 #include <netinet/in.h>
46 #ifdef HAVE_ARPA_INET_H
47 #include <arpa/inet.h>
50 #if defined(__APPLE__) && defined(__LP64__)
51 #include <sys/utsname.h>
58 #include <zlib.h> /* to get the libz version number */
61 #include <wsutil/cmdarg_err.h>
62 #include <wsutil/crash_info.h>
63 #include <wsutil/ws_diag_control.h>
64 #include <wsutil/ws_version_info.h>
66 #ifndef HAVE_GETOPT_LONG
67 #include "wsutil/wsgetopt.h"
75 # include <sys/prctl.h>
76 # include <sys/capability.h>
79 #include "ringbuffer.h"
81 #include "caputils/capture_ifinfo.h"
82 #include "caputils/capture-pcap-util.h"
83 #include "caputils/capture-pcap-util-int.h"
85 #include "caputils/capture-wpcap.h"
91 #include <wsutil/unicode-utils.h>
98 #ifdef NEED_INET_V6DEFS_H
99 # include "wsutil/inet_v6defs.h"
102 #include <wsutil/clopts_common.h>
103 #include <wsutil/privileges.h>
105 #include "sync_pipe.h"
107 #include "capture_opts.h"
108 #include <capchild/capture_session.h>
109 #include <capchild/capture_sync.h>
111 #include "conditions.h"
112 #include "capture_stop_conditions.h"
114 #include "wsutil/tempfile.h"
116 #include "wsutil/file_util.h"
117 #include "wsutil/os_version_info.h"
118 #include "wsutil/str_util.h"
120 #include "caputils/ws80211_utils.h"
127 * Get information about libpcap format from "wiretap/libpcap.h".
128 * XXX - can we just use pcap_open_offline() to read the pipe?
130 #include "wiretap/libpcap.h"
132 /**#define DEBUG_DUMPCAP**/
133 /**#define DEBUG_CHILD_DUMPCAP**/
137 #include <conio.h> /* _getch() */
141 #ifdef DEBUG_CHILD_DUMPCAP
142 FILE *debug_log; /* for logging debug messages to */
143 /* a file if DEBUG_CHILD_DUMPCAP */
147 static GAsyncQueue *pcap_queue;
148 static gint64 pcap_queue_bytes;
149 static gint64 pcap_queue_packets;
150 static gint64 pcap_queue_byte_limit = 0;
151 static gint64 pcap_queue_packet_limit = 0;
153 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
155 static gchar *sig_pipe_name = NULL;
156 static HANDLE sig_pipe_handle = NULL;
157 static gboolean signal_pipe_check_running(void);
161 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
162 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
165 /** Stop a low-level capture (stops the capture child). */
166 static void capture_loop_stop(void);
167 /** Close a pipe, or socket if \a from_socket is TRUE */
168 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
172 * Enable kernel BPF JIT compiler if available.
173 * If any calls fail, just drive on - the JIT compiler might not be
174 * enabled, but filtering will still work, and it's not clear what
175 * we could do if the calls fail; should we just report the error
176 * and not continue to capture, should we report it as a warning, or
180 enable_kernel_bpf_jit_compiler(void)
184 static const char file[] = "/proc/sys/net/core/bpf_jit_enable";
186 fd = ws_open(file, O_WRONLY);
190 written = ws_write(fd, "1", strlen("1"));
196 #if !defined (__linux__)
197 #ifndef HAVE_PCAP_BREAKLOOP
199 * We don't have pcap_breakloop(), which is the only way to ensure that
200 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
201 * won't, if the call to read the next packet or batch of packets is
202 * is interrupted by a signal on UN*X, just go back and try again to
205 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
206 * the signal handler, set a flag to stop capturing; however, without
207 * a guarantee of that sort, we can't guarantee that we'll stop capturing
208 * if the read will be retried and won't time out if no packets arrive.
210 * Therefore, on at least some platforms, we work around the lack of
211 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
212 * to wait for packets to arrive, so that we're probably going to be
213 * blocked in the select() when the signal arrives, and can just bail
214 * out of the loop at that point.
216 * However, we don't want to do that on BSD (because "select()" doesn't work
217 * correctly on BPF devices on at least some releases of some flavors of
218 * BSD), and we don't want to do it on Windows (because "select()" is
219 * something for sockets, not for arbitrary handles). (Note that "Windows"
220 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
221 * using WinPcap, not a UNIX libpcap.)
223 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
224 * on BSD times out even if no packets have arrived, so we'll eventually
225 * exit pcap_dispatch() with an indication that no packets have arrived,
226 * and will break out of the capture loop at that point.
228 * On Windows, we can't send a SIGINT to stop capturing, so none of this
229 * applies in any case.
231 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
232 * want to include it if it's not present on this platform, however.
234 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
235 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
237 # define MUST_DO_SELECT
238 # endif /* avoid select */
239 #endif /* HAVE_PCAP_BREAKLOOP */
241 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
242 * in pcap_dispatch(); on the other hand, select() works just fine there.
243 * Hence we use a select for that come what may.
245 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
246 * internally, and, with TPACKET_V3, once that's supported, it'll
247 * support timeouts, at least as I understand the way the code works.
249 #define MUST_DO_SELECT
252 /** init the capture filter */
255 INITFILTER_BAD_FILTER,
256 INITFILTER_OTHER_ERROR
257 } initfilter_status_t;
260 STATE_EXPECT_REC_HDR,
273 typedef struct _pcap_options {
278 #ifdef MUST_DO_SELECT
279 int pcap_fd; /**< pcap file descriptor */
286 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
287 /**< capture pipe (unix only "input file") */
288 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
289 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
290 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
291 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
293 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
295 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
296 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
297 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
299 char * cap_pipe_buf; /**< Pointer to the data buffer we read into */
300 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
301 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
303 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
304 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
306 cap_pipe_state_t cap_pipe_state;
307 cap_pipe_err_t cap_pipe_err;
310 GMutex *cap_pipe_read_mtx;
311 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
315 typedef struct _loop_data {
317 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
318 int err; /**< if non-zero, error seen while capturing */
319 gint packet_count; /**< Number of packets we have already captured */
320 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
321 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
323 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
329 guint64 bytes_written;
330 guint32 autostop_files;
333 typedef struct _pcap_queue_element {
334 pcap_options *pcap_opts;
335 struct pcap_pkthdr phdr;
337 } pcap_queue_element;
340 * Standard secondary message for unexpected errors.
342 static const char please_report[] =
343 "Please report this to the Wireshark developers.\n"
344 "https://bugs.wireshark.org/\n"
345 "(This is not a crash; please do not report it as such.)";
348 * This needs to be static, so that the SIGINT handler can clear the "go"
351 static loop_data global_ld;
354 * Timeout, in milliseconds, for reads from the stream of captured packets
355 * from a capture device.
357 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
358 * 64-bit applications, with sub-second timeouts not to work. The bug is
359 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
361 #if defined(__APPLE__) && defined(__LP64__)
362 static gboolean need_timeout_workaround;
364 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
366 #define CAP_READ_TIMEOUT 250
370 * Timeout, in microseconds, for reads from the stream of captured packets
371 * from a pipe. Pipes don't have the same problem that BPF devices do
372 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
373 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
374 * of the offending versions of Snow Leopard.
376 * On Windows this value is converted to milliseconds and passed to
377 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
378 * will return immediately.
381 #define PIPE_READ_TIMEOUT 100000
383 #define PIPE_READ_TIMEOUT 250000
386 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
389 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
390 const char *message, gpointer user_data _U_);
392 /* capture related options */
393 static capture_options global_capture_opts;
394 static gboolean quiet = FALSE;
395 static gboolean use_threads = FALSE;
396 static guint64 start_time;
398 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
400 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
402 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
403 int err, gboolean is_close);
405 static void WS_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
407 static void report_new_capture_file(const char *filename);
408 static void report_packet_count(unsigned int packet_count);
409 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
410 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
411 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
413 #define MSG_MAX_LENGTH 4096
415 /* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
417 create_timestamp(void) {
427 * Current time, represented as 100-nanosecond intervals since
428 * January 1, 1601, 00:00:00 UTC.
430 * I think DWORD might be signed, so cast both parts of "now"
431 * to guint32 so that the sign bit doesn't get treated specially.
433 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
434 * might want to use instead.
436 GetSystemTimeAsFileTime(&now);
437 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
438 (guint32)now.dwLowDateTime;
441 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
447 * Subtract difference, in microseconds, between January 1, 1601
448 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
450 timestamp -= G_GUINT64_CONSTANT(11644473600000000);
453 * Current time, represented as seconds and microseconds since
454 * January 1, 1970, 00:00:00 UTC.
456 gettimeofday(&now, NULL);
459 * Convert to delta in microseconds.
461 timestamp = (guint64)(now.tv_sec) * 1000000 +
462 (guint64)(now.tv_usec);
468 print_usage(FILE *output)
470 fprintf(output, "\nUsage: dumpcap [options] ...\n");
471 fprintf(output, "\n");
472 fprintf(output, "Capture interface:\n");
473 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
474 " or for remote capturing, use one of these formats:\n"
475 " rpcap://<host>/<interface>\n"
476 " TCP@<host>:<port>\n");
477 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
478 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
479 fprintf(output, " -p don't capture in promiscuous mode\n");
480 #ifdef HAVE_PCAP_CREATE
481 fprintf(output, " -I capture in monitor mode, if available\n");
483 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
484 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
486 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
487 fprintf(output, " -D print list of interfaces and exit\n");
488 fprintf(output, " -L print list of link-layer types of iface and exit\n");
489 #ifdef HAVE_BPF_IMAGE
490 fprintf(output, " -d print generated BPF code for capture filter\n");
492 fprintf(output, " -k set channel on wifi interface <freq>,[<type>]\n");
493 fprintf(output, " -S print statistics for each interface once per second\n");
494 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
495 fprintf(output, "\n");
496 #ifdef HAVE_PCAP_REMOTE
497 fprintf(output, "RPCAP options:\n");
498 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
499 fprintf(output, " -u use UDP for RPCAP data transfer\n");
500 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
501 #ifdef HAVE_PCAP_SETSAMPLING
502 fprintf(output, " -m <sampling type> use packet sampling\n");
503 fprintf(output, " count:NUM - capture one packet of every NUM\n");
504 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
507 fprintf(output, "Stop conditions:\n");
508 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
509 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
510 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
511 fprintf(output, " files:NUM - stop after NUM files\n");
512 /*fprintf(output, "\n");*/
513 fprintf(output, "Output (files):\n");
514 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
515 fprintf(output, " -g enable group read access on the output file(s)\n");
516 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
517 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
518 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
519 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
520 fprintf(output, " -P use libpcap format instead of pcapng\n");
521 fprintf(output, " --capture-comment <comment>\n");
522 fprintf(output, " add a capture comment to the output file\n");
523 fprintf(output, " (only for pcapng)\n");
524 fprintf(output, "\n");
525 fprintf(output, "Miscellaneous:\n");
526 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
527 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
528 fprintf(output, " within dumpcap\n");
529 fprintf(output, " -t use a separate thread per interface\n");
530 fprintf(output, " -q don't report packet capture counts\n");
531 fprintf(output, " -v print version information and exit\n");
532 fprintf(output, " -h display this help and exit\n");
533 fprintf(output, "\n");
535 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
536 fprintf(output, "You might want to reset it\n");
537 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
538 fprintf(output, "\n");
540 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
541 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
542 fprintf(output, "\n");
543 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
547 * Report an error in command-line arguments.
548 * If we're a capture child, send a message back to the parent, otherwise
552 dumpcap_cmdarg_err(const char *fmt, va_list ap)
556 /* Generate a 'special format' message back to parent */
557 msg = g_strdup_vprintf(fmt, ap);
558 sync_pipe_errmsg_to_parent(2, msg, "");
561 fprintf(stderr, "dumpcap: ");
562 vfprintf(stderr, fmt, ap);
563 fprintf(stderr, "\n");
568 * Report additional information for an error in command-line arguments.
569 * If we're a capture child, send a message back to the parent, otherwise
573 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
577 msg = g_strdup_vprintf(fmt, ap);
578 sync_pipe_errmsg_to_parent(2, msg, "");
581 vfprintf(stderr, fmt, ap);
582 fprintf(stderr, "\n");
588 #if 0 /* Set to enable capability debugging */
589 /* see 'man cap_to_text()' for explanation of output */
590 /* '=' means 'all= ' ie: no capabilities */
591 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
593 print_caps(const char *pfx) {
594 cap_t caps = cap_get_proc();
595 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
596 "%s: EUID: %d Capabilities: %s", pfx,
597 geteuid(), cap_to_text(caps, NULL));
600 print_caps(const char *pfx _U_) {
605 relinquish_all_capabilities(void)
607 /* Drop any and all capabilities this process may have. */
608 /* Allowed whether or not process has any privileges. */
609 cap_t caps = cap_init(); /* all capabilities initialized to off */
610 print_caps("Pre-clear");
611 if (cap_set_proc(caps)) {
612 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
614 print_caps("Post-clear");
620 get_capture_device_open_failure_messages(const char *open_err_str,
622 char *errmsg, size_t errmsg_len,
623 char *secondary_errmsg,
624 size_t secondary_errmsg_len)
627 const char *libpcap_warn;
628 static const char ppamsg[] = "can't find PPA for ";
631 g_snprintf(errmsg, (gulong) errmsg_len,
632 "The capture session could not be initiated on interface '%s' (%s).",
633 iface, open_err_str);
636 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
638 "In order to capture packets, WinPcap must be installed; see\n"
640 " https://www.winpcap.org/\n"
642 "for a downloadable version of WinPcap and for instructions on how to install\n"
645 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
647 "Please check that \"%s\" is the proper interface.\n"
650 "Help can be found at:\n"
652 " https://wiki.wireshark.org/WinPcap\n"
653 " https://wiki.wireshark.org/CaptureSetup\n",
657 /* If we got a "can't find PPA for X" message, warn the user (who
658 is running dumpcap on HP-UX) that they don't have a version of
659 libpcap that properly handles HP-UX (libpcap 0.6.x and later
660 versions, which properly handle HP-UX, say "can't find /dev/dlpi
661 PPA for X" rather than "can't find PPA for X"). */
662 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
665 "You are running (T)Wireshark with a version of the libpcap library\n"
666 "that doesn't handle HP-UX network devices well; this means that\n"
667 "(T)Wireshark may not be able to capture packets.\n"
669 "To fix this, you should install libpcap 0.6.2, or a later version\n"
670 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
671 "packaged binary form from the Software Porting And Archive Centre\n"
672 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
673 "at the URL lists a number of mirror sites.";
677 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
678 "Please check to make sure you have sufficient permissions, and that you have "
679 "the proper interface or pipe specified.%s", libpcap_warn);
684 compile_capture_filter(const char *iface, pcap_t *pcap_h,
685 struct bpf_program *fcode, const char *cfilter)
687 bpf_u_int32 netnum, netmask;
688 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
690 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
692 * Well, we can't get the netmask for this interface; it's used
693 * only for filters that check for broadcast IP addresses, so
694 * we just punt and use 0. It might be nice to warn the user,
695 * but that's a pain in a GUI application, as it'd involve popping
696 * up a message box, and it's not clear how often this would make
697 * a difference (only filters that check for IP broadcast addresses
701 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
706 * Sigh. Older versions of libpcap don't properly declare the
707 * third argument to pcap_compile() as a const pointer. Cast
711 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
717 #ifdef HAVE_BPF_IMAGE
719 show_filter_code(capture_options *capture_opts)
721 interface_options interface_opts;
723 gchar open_err_str[PCAP_ERRBUF_SIZE];
724 char errmsg[MSG_MAX_LENGTH+1];
725 char secondary_errmsg[MSG_MAX_LENGTH+1];
726 struct bpf_program fcode;
727 struct bpf_insn *insn;
731 for (j = 0; j < capture_opts->ifaces->len; j++) {
732 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
733 pcap_h = open_capture_device(capture_opts, &interface_opts,
734 CAP_READ_TIMEOUT, &open_err_str);
735 if (pcap_h == NULL) {
736 /* Open failed; get messages */
737 get_capture_device_open_failure_messages(open_err_str,
739 errmsg, sizeof errmsg,
741 sizeof secondary_errmsg);
742 /* And report them */
743 report_capture_error(errmsg, secondary_errmsg);
747 /* Set the link-layer type. */
748 if (!set_pcap_datalink(pcap_h, interface_opts.linktype, interface_opts.name,
749 errmsg, sizeof errmsg,
750 secondary_errmsg, sizeof secondary_errmsg)) {
752 report_capture_error(errmsg, secondary_errmsg);
756 /* OK, try to compile the capture filter. */
757 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
758 interface_opts.cfilter)) {
760 report_cfilter_error(capture_opts, j, errmsg);
765 /* Now print the filter code. */
766 insn = fcode.bf_insns;
768 for (i = 0; i < fcode.bf_len; insn++, i++)
769 printf("%s\n", bpf_image(insn, i));
771 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
772 /* to remove any suid privileges. */
773 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
774 /* (euid/egid have already previously been set to ruid/rgid. */
775 /* (See comment in main() for details) */
777 relinquish_special_privs_perm();
779 relinquish_all_capabilities();
782 /* Let our parent know we succeeded. */
783 pipe_write_block(2, SP_SUCCESS, NULL);
790 * capture_interface_list() is expected to do the right thing to get
791 * a list of interfaces.
793 * In most of the programs in the Wireshark suite, "the right thing"
794 * is to run dumpcap and ask it for the list, because dumpcap may
795 * be the only program in the suite with enough privileges to get
798 * In dumpcap itself, however, we obviously can't run dumpcap to
799 * ask for the list. Therefore, our capture_interface_list() should
800 * just call get_interface_list().
803 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
805 return get_interface_list(err, err_str);
808 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
810 * Output a machine readable list of the interfaces
811 * This list is retrieved by the sync_interface_list_open() function
812 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
815 print_machine_readable_interfaces(GList *if_list)
822 char addr_str[ADDRSTRLEN];
825 /* Let our parent know we succeeded. */
826 pipe_write_block(2, SP_SUCCESS, NULL);
829 i = 1; /* Interface id number */
830 for (if_entry = g_list_first(if_list); if_entry != NULL;
831 if_entry = g_list_next(if_entry)) {
832 if_info = (if_info_t *)if_entry->data;
833 printf("%d. %s\t", i++, if_info->name);
836 * Print the contents of the if_entry struct in a parseable format.
837 * Each if_entry element is tab-separated. Addresses are comma-
840 /* XXX - Make sure our description doesn't contain a tab */
841 if (if_info->vendor_description != NULL)
842 printf("%s\t", if_info->vendor_description);
846 /* XXX - Make sure our friendly name doesn't contain a tab */
847 if (if_info->friendly_name != NULL)
848 printf("%s\t", if_info->friendly_name);
852 printf("%i\t", if_info->type);
854 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
855 addr = g_slist_next(addr)) {
856 if (addr != g_slist_nth(if_info->addrs, 0))
859 if_addr = (if_addr_t *)addr->data;
860 switch(if_addr->ifat_type) {
862 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
864 printf("%s", addr_str);
866 printf("<unknown IPv4>");
870 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
871 addr_str, ADDRSTRLEN)) {
872 printf("%s", addr_str);
874 printf("<unknown IPv6>");
878 printf("<type unknown %i>", if_addr->ifat_type);
882 if (if_info->loopback)
883 printf("\tloopback");
887 printf("\t%s", if_info->extcap);
894 * If you change the machine-readable output format of this function,
895 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
898 print_machine_readable_if_capabilities(if_capabilities_t *caps)
901 data_link_info_t *data_link_info;
902 const gchar *desc_str;
905 /* Let our parent know we succeeded. */
906 pipe_write_block(2, SP_SUCCESS, NULL);
909 if (caps->can_set_rfmon)
913 for (lt_entry = caps->data_link_types; lt_entry != NULL;
914 lt_entry = g_list_next(lt_entry)) {
915 data_link_info = (data_link_info_t *)lt_entry->data;
916 if (data_link_info->description != NULL)
917 desc_str = data_link_info->description;
919 desc_str = "(not supported)";
920 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
930 /* Print the number of packets captured for each interface until we're killed. */
932 print_statistics_loop(gboolean machine_readable)
934 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
940 char errbuf[PCAP_ERRBUF_SIZE];
943 if_list = get_interface_list(&err, &err_str);
944 if (if_list == NULL) {
946 cmdarg_err("There are no interfaces on which a capture can be done");
948 cmdarg_err("%s", err_str);
954 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
955 if_info = (if_info_t *)if_entry->data;
958 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
959 * connections. We avoid collecting stats on them.
961 if (!strncmp(if_info->name, "nf", 2)) {
962 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
968 #ifdef HAVE_PCAP_OPEN
969 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
971 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
975 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
976 if_stat->name = g_strdup(if_info->name);
978 stat_list = g_list_append(stat_list, if_stat);
983 cmdarg_err("There are no interfaces on which a capture can be done");
988 /* Let our parent know we succeeded. */
989 pipe_write_block(2, SP_SUCCESS, NULL);
992 if (!machine_readable) {
993 printf("%-15s %10s %10s\n", "Interface", "Received",
998 while (global_ld.go) {
999 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1000 if_stat = (if_stat_t *)stat_entry->data;
1001 pcap_stats(if_stat->pch, &ps);
1003 if (!machine_readable) {
1004 printf("%-15s %10u %10u\n", if_stat->name,
1005 ps.ps_recv, ps.ps_drop);
1007 printf("%s\t%u\t%u\n", if_stat->name,
1008 ps.ps_recv, ps.ps_drop);
1013 /* If we have a dummy signal pipe check it */
1014 if (!signal_pipe_check_running()) {
1015 global_ld.go = FALSE;
1023 /* XXX - Not reached. Should we look for 'q' in stdin? */
1024 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1025 if_stat = (if_stat_t *)stat_entry->data;
1026 pcap_close(if_stat->pch);
1027 g_free(if_stat->name);
1030 g_list_free(stat_list);
1031 free_interface_list(if_list);
1039 capture_cleanup_handler(DWORD dwCtrlType)
1041 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1042 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1043 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1044 like SIGTERM at least when the machine's shutting down.
1046 For now, if we're running as a command rather than a capture child,
1047 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1048 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1049 in that way on UN*X.
1051 If we're not running as a capture child, we might be running as
1052 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1053 user logs out. (XXX - can we explicitly check whether we're
1054 running as a service?) */
1056 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1057 "Console: Control signal");
1058 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1059 "Console: Control signal, CtrlType: %u", dwCtrlType);
1061 /* Keep capture running if we're a service and a user logs off */
1062 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1063 capture_loop_stop();
1071 capture_cleanup_handler(int signum _U_)
1073 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1074 SIGTERM. We assume that if the user wanted it to keep running
1075 after they logged out, they'd have nohupped it. */
1077 /* Note: don't call g_log() in the signal handler: if we happened to be in
1078 * g_log() in process context when the signal came in, g_log will detect
1079 * the "recursion" and abort.
1082 capture_loop_stop();
1088 report_capture_count(gboolean reportit)
1090 /* Don't print this if we're a capture child. */
1091 if (!capture_child && reportit) {
1092 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packet_count);
1093 /* stderr could be line buffered */
1101 report_counts_for_siginfo(void)
1103 report_capture_count(quiet);
1104 infoprint = FALSE; /* we just reported it */
1108 report_counts_siginfo(int signum _U_)
1110 int sav_errno = errno;
1112 /* If we've been told to delay printing, just set a flag asking
1113 that we print counts (if we're supposed to), otherwise print
1114 the count of packets captured (if we're supposed to). */
1118 report_counts_for_siginfo();
1121 #endif /* SIGINFO */
1124 exit_main(int status)
1127 /* Shutdown windows sockets */
1130 /* can be helpful for debugging */
1131 #ifdef DEBUG_DUMPCAP
1132 printf("Press any key\n");
1143 * If we were linked with libcap (not related to libpcap), make sure we have
1144 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1145 * (See comment in main() for details)
1148 relinquish_privs_except_capture(void)
1150 /* If 'started_with_special_privs' (ie: suid) then enable for
1151 * ourself the NET_ADMIN and NET_RAW capabilities and then
1152 * drop our suid privileges.
1154 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1155 * stuff we don't need (and shouldn't have).
1156 * CAP_NET_RAW: Packet capture (raw sockets).
1159 if (started_with_special_privs()) {
1160 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1161 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1163 cap_t caps = cap_init(); /* all capabilities initialized to off */
1165 print_caps("Pre drop, pre set");
1167 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1168 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1171 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1172 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1174 if (cap_set_proc(caps)) {
1175 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1177 print_caps("Pre drop, post set");
1179 relinquish_special_privs_perm();
1181 print_caps("Post drop, pre set");
1182 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1183 if (cap_set_proc(caps)) {
1184 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1186 print_caps("Post drop, post set");
1192 #endif /* HAVE_LIBCAP */
1194 /* Take care of byte order in the libpcap headers read from pipes.
1195 * (function taken from wiretap/libpcap.c) */
1197 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1200 /* Byte-swap the record header fields. */
1201 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1202 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1203 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1204 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1207 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1208 swapped, in order to match the BPF header layout.
1210 Unfortunately, some files were, according to a comment in the "libpcap"
1211 source, written with version 2.3 in their headers but without the
1212 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1213 would make no sense - we assume that we need to swap them. */
1214 if (hdr->version_major == 2 &&
1215 (hdr->version_minor < 3 ||
1216 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1219 temp = rechdr->orig_len;
1220 rechdr->orig_len = rechdr->incl_len;
1221 rechdr->incl_len = temp;
1225 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1229 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1233 return recv(pipe_fd, buf, (int)sz, 0);
1238 return ws_read(pipe_fd, buf, sz);
1244 * Thread function that reads from a pipe and pushes the data
1245 * to the main application thread.
1248 * XXX Right now we use async queues for basic signaling. The main thread
1249 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1250 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1251 * Iff the read is successful cap_pipe_read pushes an item onto
1252 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1253 * the queues themselves (yet).
1255 * We might want to move some of the cap_pipe_dispatch logic here so that
1256 * we can let cap_thread_read run independently, queuing up multiple reads
1257 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1259 static void *cap_thread_read(void *arg)
1261 pcap_options *pcap_opts;
1264 DWORD b, last_err, bytes_read;
1270 pcap_opts = (pcap_options *)arg;
1271 while (pcap_opts->cap_pipe_err == PIPOK) {
1272 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1273 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1275 while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1276 if ((pcap_opts->from_cap_socket)
1282 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1283 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1286 pcap_opts->cap_pipe_err = PIPEOF;
1290 pcap_opts->cap_pipe_err = PIPERR;
1301 /* If we try to use read() on a named pipe on Windows with partial
1302 * data it appears to return EOF.
1304 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1305 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1310 last_err = GetLastError();
1311 if (last_err == ERROR_MORE_DATA) {
1313 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1314 pcap_opts->cap_pipe_err = PIPEOF;
1318 pcap_opts->cap_pipe_err = PIPERR;
1321 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1322 pcap_opts->cap_pipe_err = PIPEOF;
1329 pcap_opts->cap_pipe_bytes_read = bytes_read;
1330 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1331 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1333 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1339 /* Provide select() functionality for a single file descriptor
1340 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1342 * Returns the same values as select.
1345 cap_pipe_select(int pipe_fd)
1348 struct timeval timeout;
1351 FD_SET(pipe_fd, &rfds);
1353 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1354 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1356 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1359 #define DEF_TCP_PORT 19000
1362 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1364 char *sockname = pipename + 4;
1365 struct sockaddr_in sa;
1372 memset(&sa, 0, sizeof(sa));
1374 p = strchr(sockname, ':');
1376 len = strlen(sockname);
1377 port = DEF_TCP_PORT;
1381 port = strtoul(p + 1, &p, 10);
1382 if (*p || port > 65535) {
1391 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1393 if (inet_pton(AF_INET, buf, &sa.sin_addr) <= 0) {
1397 sa.sin_family = AF_INET;
1398 sa.sin_port = g_htons((u_short)port);
1400 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1401 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1403 LPTSTR errorText = NULL;
1406 lastError = WSAGetLastError();
1407 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1408 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1409 FORMAT_MESSAGE_IGNORE_INSERTS,
1410 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1411 (LPTSTR)&errorText, 0, NULL);
1413 g_snprintf(errmsg, errmsgl,
1414 "The capture session could not be initiated due to the socket error: \n"
1416 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1418 LocalFree(errorText);
1420 " %d: %s", errno, g_strerror(errno));
1422 pcap_opts->cap_pipe_err = PIPERR;
1425 cap_pipe_close(fd, TRUE);
1429 pcap_opts->from_cap_socket = TRUE;
1433 g_snprintf(errmsg, errmsgl,
1434 "The capture session could not be initiated because\n"
1435 "\"%s\" is not a valid socket specification", pipename);
1436 pcap_opts->cap_pipe_err = PIPERR;
1440 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1444 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1448 closesocket(pipe_fd);
1455 /* Mimic pcap_open_live() for pipe captures
1457 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1458 * open it, and read the header.
1460 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1461 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1463 cap_pipe_open_live(char *pipename,
1464 pcap_options *pcap_opts,
1465 struct pcap_hdr *hdr,
1466 char *errmsg, int errmsgl)
1469 ws_statb64 pipe_stat;
1470 struct sockaddr_un sa;
1474 interface_options interface_opts;
1476 char* extcap_pipe_name;
1477 gboolean extcap_pipe;
1481 int fd = -1, sel_ret;
1484 pcap_opts->cap_pipe_fd = -1;
1486 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1489 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1492 * XXX - this blocks until a pcap per-file header has been written to
1493 * the pipe, so it could block indefinitely.
1495 if (strcmp(pipename, "-") == 0) {
1497 fd = 0; /* read from stdin */
1499 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1501 } else if (!strncmp(pipename, "TCP@", 4)) {
1502 if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
1507 if (ws_stat64(pipename, &pipe_stat) < 0) {
1508 if (errno == ENOENT || errno == ENOTDIR)
1509 pcap_opts->cap_pipe_err = PIPNEXIST;
1511 g_snprintf(errmsg, errmsgl,
1512 "The capture session could not be initiated "
1513 "due to error getting information on pipe/socket: %s", g_strerror(errno));
1514 pcap_opts->cap_pipe_err = PIPERR;
1518 if (S_ISFIFO(pipe_stat.st_mode)) {
1519 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1521 g_snprintf(errmsg, errmsgl,
1522 "The capture session could not be initiated "
1523 "due to error on pipe open: %s", g_strerror(errno));
1524 pcap_opts->cap_pipe_err = PIPERR;
1527 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1528 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1530 g_snprintf(errmsg, errmsgl,
1531 "The capture session could not be initiated "
1532 "due to error on socket create: %s", g_strerror(errno));
1533 pcap_opts->cap_pipe_err = PIPERR;
1536 sa.sun_family = AF_UNIX;
1538 * The Single UNIX Specification says:
1540 * The size of sun_path has intentionally been left undefined.
1541 * This is because different implementations use different sizes.
1542 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1543 * of 104. Since most implementations originate from BSD versions,
1544 * the size is typically in the range 92 to 108.
1546 * Applications should not assume a particular length for sun_path
1547 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1551 * The <sys/un.h> header shall define the sockaddr_un structure,
1552 * which shall include at least the following members:
1554 * sa_family_t sun_family Address family.
1555 * char sun_path[] Socket pathname.
1557 * so we assume that it's an array, with a specified size,
1558 * and that the size reflects the maximum path length.
1560 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1561 /* Path name too long */
1562 g_snprintf(errmsg, errmsgl,
1563 "The capture session coud not be initiated "
1564 "due to error on socket connect: Path name too long");
1565 pcap_opts->cap_pipe_err = PIPERR;
1569 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1571 g_snprintf(errmsg, errmsgl,
1572 "The capture session coud not be initiated "
1573 "due to error on socket connect: %s", g_strerror(errno));
1574 pcap_opts->cap_pipe_err = PIPERR;
1579 if (S_ISCHR(pipe_stat.st_mode)) {
1581 * Assume the user specified an interface on a system where
1582 * interfaces are in /dev. Pretend we haven't seen it.
1584 pcap_opts->cap_pipe_err = PIPNEXIST;
1586 g_snprintf(errmsg, errmsgl,
1587 "The capture session could not be initiated because\n"
1588 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
1589 pcap_opts->cap_pipe_err = PIPERR;
1594 #define PIPE_STR "\\pipe\\"
1595 /* Under Windows, named pipes _must_ have the form
1596 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1598 pncopy = g_strdup(pipename);
1599 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1600 pos = strchr(pncopy + 3, '\\');
1601 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1608 g_snprintf(errmsg, errmsgl,
1609 "The capture session could not be initiated because\n"
1610 "\"%s\" is neither an interface nor a pipe", pipename);
1611 pcap_opts->cap_pipe_err = PIPNEXIST;
1615 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
1617 extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
1618 extcap_pipe = strstr(interface_opts.name, extcap_pipe_name) ? TRUE : FALSE;
1619 g_free(extcap_pipe_name);
1622 /* Wait for the pipe to appear */
1627 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1630 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1631 OPEN_EXISTING, 0, NULL);
1633 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
1636 if (GetLastError() != ERROR_PIPE_BUSY) {
1637 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1638 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1639 g_snprintf(errmsg, errmsgl,
1640 "The capture session on \"%s\" could not be started "
1641 "due to error on pipe open: %s (error %d)",
1642 pipename, utf_16to8(err_str), GetLastError());
1644 pcap_opts->cap_pipe_err = PIPERR;
1648 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1649 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1650 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1651 g_snprintf(errmsg, errmsgl,
1652 "The capture session on \"%s\" timed out during "
1653 "pipe open: %s (error %d)",
1654 pipename, utf_16to8(err_str), GetLastError());
1656 pcap_opts->cap_pipe_err = PIPERR;
1663 pcap_opts->from_cap_pipe = TRUE;
1666 if (pcap_opts->from_cap_socket)
1669 /* read the pcap header */
1671 while (bytes_read < sizeof magic) {
1673 g_snprintf(errmsg, errmsgl, "Invalid file descriptor");
1677 sel_ret = cap_pipe_select(fd);
1679 g_snprintf(errmsg, errmsgl,
1680 "Unexpected error from select: %s", g_strerror(errno));
1682 } else if (sel_ret > 0) {
1683 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1684 sizeof magic-bytes_read,
1685 pcap_opts->from_cap_socket);
1688 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1690 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1700 #if GLIB_CHECK_VERSION(2,31,0)
1701 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
1703 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
1706 pcap_opts->cap_pipe_buf = (char *) &magic;
1707 pcap_opts->cap_pipe_bytes_read = 0;
1708 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
1709 /* We don't have to worry about cap_pipe_read_mtx here */
1710 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1711 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
1712 if (pcap_opts->cap_pipe_bytes_read <= 0) {
1713 if (pcap_opts->cap_pipe_bytes_read == 0)
1714 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1716 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1725 case PCAP_NSEC_MAGIC:
1726 /* Host that wrote it has our byte order, and was running
1727 a program using either standard or ss990417 libpcap. */
1728 pcap_opts->cap_pipe_byte_swapped = FALSE;
1729 pcap_opts->cap_pipe_modified = FALSE;
1730 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
1732 case PCAP_MODIFIED_MAGIC:
1733 /* Host that wrote it has our byte order, but was running
1734 a program using either ss990915 or ss991029 libpcap. */
1735 pcap_opts->cap_pipe_byte_swapped = FALSE;
1736 pcap_opts->cap_pipe_modified = TRUE;
1738 case PCAP_SWAPPED_MAGIC:
1739 case PCAP_SWAPPED_NSEC_MAGIC:
1740 /* Host that wrote it has a byte order opposite to ours,
1741 and was running a program using either standard or
1742 ss990417 libpcap. */
1743 pcap_opts->cap_pipe_byte_swapped = TRUE;
1744 pcap_opts->cap_pipe_modified = FALSE;
1745 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
1747 case PCAP_SWAPPED_MODIFIED_MAGIC:
1748 /* Host that wrote it out has a byte order opposite to
1749 ours, and was running a program using either ss990915
1750 or ss991029 libpcap. */
1751 pcap_opts->cap_pipe_byte_swapped = TRUE;
1752 pcap_opts->cap_pipe_modified = TRUE;
1755 /* Not a "libpcap" type we know about. */
1756 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1761 if (pcap_opts->from_cap_socket)
1764 /* Read the rest of the header */
1766 while (bytes_read < sizeof(struct pcap_hdr)) {
1767 sel_ret = cap_pipe_select(fd);
1769 g_snprintf(errmsg, errmsgl,
1770 "Unexpected error from select: %s", g_strerror(errno));
1772 } else if (sel_ret > 0) {
1773 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
1774 sizeof(struct pcap_hdr) - bytes_read,
1775 pcap_opts->from_cap_socket);
1778 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1780 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
1790 pcap_opts->cap_pipe_buf = (char *) hdr;
1791 pcap_opts->cap_pipe_bytes_read = 0;
1792 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1793 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1794 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
1795 if (pcap_opts->cap_pipe_bytes_read <= 0) {
1796 if (pcap_opts->cap_pipe_bytes_read == 0)
1797 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1799 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
1806 if (pcap_opts->cap_pipe_byte_swapped) {
1807 /* Byte-swap the header fields about which we care. */
1808 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
1809 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
1810 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
1811 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
1813 pcap_opts->linktype = hdr->network;
1815 if (hdr->version_major < 2) {
1816 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1820 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
1821 pcap_opts->cap_pipe_err = PIPOK;
1822 pcap_opts->cap_pipe_fd = fd;
1826 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1827 pcap_opts->cap_pipe_err = PIPERR;
1828 cap_pipe_close(fd, pcap_opts->from_cap_socket);
1829 pcap_opts->cap_pipe_fd = -1;
1833 /* We read one record from the pipe, take care of byte order in the record
1834 * header, write the record to the capture file, and update capture statistics. */
1836 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
1838 struct pcap_pkthdr phdr;
1839 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1842 #if !GLIB_CHECK_VERSION(2,31,18)
1850 #ifdef LOG_CAPTURE_VERBOSE
1851 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1854 switch (pcap_opts->cap_pipe_state) {
1856 case STATE_EXPECT_REC_HDR:
1858 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
1861 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
1862 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
1863 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1864 pcap_opts->cap_pipe_bytes_read = 0;
1867 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
1868 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1869 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1874 case STATE_READ_REC_HDR:
1876 if (pcap_opts->from_cap_socket)
1879 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
1880 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
1883 result = PD_PIPE_EOF;
1885 result = PD_PIPE_ERR;
1888 pcap_opts->cap_pipe_bytes_read += b;
1892 #if GLIB_CHECK_VERSION(2,31,18)
1893 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
1895 g_get_current_time(&wait_time);
1896 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
1897 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
1899 if (pcap_opts->cap_pipe_err == PIPEOF) {
1900 result = PD_PIPE_EOF;
1902 } else if (pcap_opts->cap_pipe_err == PIPERR) {
1903 result = PD_PIPE_ERR;
1911 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
1913 result = PD_REC_HDR_READ;
1916 case STATE_EXPECT_DATA:
1918 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
1921 pcap_opts->cap_pipe_state = STATE_READ_DATA;
1922 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
1923 pcap_opts->cap_pipe_bytes_read = 0;
1926 pcap_opts->cap_pipe_buf = (char *) data;
1927 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1928 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1933 case STATE_READ_DATA:
1935 if (pcap_opts->from_cap_socket)
1938 b = cap_pipe_read(pcap_opts->cap_pipe_fd,
1939 data+pcap_opts->cap_pipe_bytes_read,
1940 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
1941 pcap_opts->from_cap_socket);
1944 result = PD_PIPE_EOF;
1946 result = PD_PIPE_ERR;
1949 pcap_opts->cap_pipe_bytes_read += b;
1954 #if GLIB_CHECK_VERSION(2,31,18)
1955 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
1957 g_get_current_time(&wait_time);
1958 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
1959 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
1960 #endif /* GLIB_CHECK_VERSION(2,31,18) */
1961 if (pcap_opts->cap_pipe_err == PIPEOF) {
1962 result = PD_PIPE_EOF;
1964 } else if (pcap_opts->cap_pipe_err == PIPERR) {
1965 result = PD_PIPE_ERR;
1973 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
1975 result = PD_DATA_READ;
1979 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
1982 } /* switch (pcap_opts->cap_pipe_state) */
1985 * We've now read as much data as we were expecting, so process it.
1989 case PD_REC_HDR_READ:
1990 /* We've read the header. Take care of byte order. */
1991 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
1992 &pcap_opts->cap_pipe_rechdr.hdr);
1993 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1994 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1995 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
1999 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2000 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2003 /* no data to read? fall through */
2006 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2007 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2008 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2009 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2010 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2013 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2015 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2017 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2021 pcap_opts->cap_pipe_err = PIPEOF;
2026 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2027 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2028 g_snprintf(errmsg, errmsgl,
2029 "Error reading from pipe: %s (error %d)",
2030 utf_16to8(err_str), GetLastError());
2033 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2041 pcap_opts->cap_pipe_err = PIPERR;
2042 /* Return here rather than inside the switch to prevent GCC warning */
2047 /** Open the capture input file (pcap or capture pipe).
2048 * Returns TRUE if it succeeds, FALSE otherwise. */
2050 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2051 char *errmsg, size_t errmsg_len,
2052 char *secondary_errmsg, size_t secondary_errmsg_len)
2054 gchar open_err_str[PCAP_ERRBUF_SIZE];
2055 gchar *sync_msg_str;
2056 interface_options interface_opts;
2057 pcap_options *pcap_opts;
2061 WORD wVersionRequested;
2065 /* XXX - opening Winsock on tshark? */
2067 /* Initialize Windows Socket if we are in a Win32 OS
2068 This needs to be done before querying the interface for network/netmask */
2070 /* XXX - do we really require 1.1 or earlier?
2071 Are there any versions that support only 2.0 or higher? */
2072 wVersionRequested = MAKEWORD(1, 1);
2073 err = WSAStartup(wVersionRequested, &wsaData);
2077 case WSASYSNOTREADY:
2078 g_snprintf(errmsg, (gulong) errmsg_len,
2079 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2082 case WSAVERNOTSUPPORTED:
2083 g_snprintf(errmsg, (gulong) errmsg_len,
2084 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2085 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2088 case WSAEINPROGRESS:
2089 g_snprintf(errmsg, (gulong) errmsg_len,
2090 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2094 g_snprintf(errmsg, (gulong) errmsg_len,
2095 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2099 g_snprintf(errmsg, (gulong) errmsg_len,
2100 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2104 g_snprintf(errmsg, (gulong) errmsg_len,
2105 "Couldn't initialize Windows Sockets: error %d", err);
2108 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2112 if ((use_threads == FALSE) &&
2113 (capture_opts->ifaces->len > 1)) {
2114 g_snprintf(errmsg, (gulong) errmsg_len,
2115 "Using threads is required for capturing on multiple interfaces.");
2119 for (i = 0; i < capture_opts->ifaces->len; i++) {
2120 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2121 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2122 if (pcap_opts == NULL) {
2123 g_snprintf(errmsg, (gulong) errmsg_len,
2124 "Could not allocate memory.");
2127 pcap_opts->received = 0;
2128 pcap_opts->dropped = 0;
2129 pcap_opts->flushed = 0;
2130 pcap_opts->pcap_h = NULL;
2131 #ifdef MUST_DO_SELECT
2132 pcap_opts->pcap_fd = -1;
2134 pcap_opts->pcap_err = FALSE;
2135 pcap_opts->interface_id = i;
2136 pcap_opts->tid = NULL;
2137 pcap_opts->snaplen = 0;
2138 pcap_opts->linktype = -1;
2139 pcap_opts->ts_nsec = FALSE;
2140 pcap_opts->from_cap_pipe = FALSE;
2141 pcap_opts->from_cap_socket = FALSE;
2142 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2143 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2145 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2147 pcap_opts->cap_pipe_fd = -1;
2148 pcap_opts->cap_pipe_modified = FALSE;
2149 pcap_opts->cap_pipe_byte_swapped = FALSE;
2151 pcap_opts->cap_pipe_buf = NULL;
2153 pcap_opts->cap_pipe_bytes_to_read = 0;
2154 pcap_opts->cap_pipe_bytes_read = 0;
2155 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2156 pcap_opts->cap_pipe_err = PIPOK;
2158 #if GLIB_CHECK_VERSION(2,31,0)
2159 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2160 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2162 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2164 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2165 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2167 g_array_append_val(ld->pcaps, pcap_opts);
2169 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2170 pcap_opts->pcap_h = open_capture_device(capture_opts, &interface_opts,
2171 CAP_READ_TIMEOUT, &open_err_str);
2173 if (pcap_opts->pcap_h != NULL) {
2174 /* we've opened "iface" as a network device */
2176 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2177 /* Find out if we're getting nanosecond-precision time stamps */
2178 pcap_opts->ts_nsec = have_high_resolution_timestamp(pcap_opts->pcap_h);
2181 #if defined(HAVE_PCAP_SETSAMPLING)
2182 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2183 struct pcap_samp *samp;
2185 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2186 switch (interface_opts.sampling_method) {
2187 case CAPTURE_SAMP_BY_COUNT:
2188 samp->method = PCAP_SAMP_1_EVERY_N;
2191 case CAPTURE_SAMP_BY_TIMER:
2192 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2196 sync_msg_str = g_strdup_printf(
2197 "Unknown sampling method %d specified,\n"
2198 "continue without packet sampling",
2199 interface_opts.sampling_method);
2200 report_capture_error("Couldn't set the capture "
2201 "sampling", sync_msg_str);
2202 g_free(sync_msg_str);
2204 samp->value = interface_opts.sampling_param;
2206 report_capture_error("Couldn't set the capture sampling",
2207 "Cannot get packet sampling data structure");
2212 /* setting the data link type only works on real interfaces */
2213 if (!set_pcap_datalink(pcap_opts->pcap_h, interface_opts.linktype,
2214 interface_opts.name,
2216 secondary_errmsg, secondary_errmsg_len)) {
2219 pcap_opts->linktype = get_pcap_datalink(pcap_opts->pcap_h, interface_opts.name);
2221 /* We couldn't open "iface" as a network device. */
2222 /* Try to open it as a pipe */
2223 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2226 if (pcap_opts->cap_pipe_fd == -1) {
2228 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2230 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2232 * We tried opening as an interface, and that failed,
2233 * so we tried to open it as a pipe, but the pipe
2234 * doesn't exist. Report the error message for
2237 get_capture_device_open_failure_messages(open_err_str,
2238 interface_opts.name,
2242 secondary_errmsg_len);
2245 * Else pipe (or file) does exist and cap_pipe_open_live() has
2250 /* cap_pipe_open_live() succeeded; don't want
2251 error message from pcap_open_live() */
2252 open_err_str[0] = '\0';
2256 /* XXX - will this work for tshark? */
2257 #ifdef MUST_DO_SELECT
2258 if (!pcap_opts->from_cap_pipe) {
2259 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2260 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2262 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2267 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2268 returned a warning; print it, but keep capturing. */
2269 if (open_err_str[0] != '\0') {
2270 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2271 report_capture_error(sync_msg_str, "");
2272 g_free(sync_msg_str);
2274 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2275 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2278 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2279 /* to remove any suid privileges. */
2280 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2281 /* (euid/egid have already previously been set to ruid/rgid. */
2282 /* (See comment in main() for details) */
2284 relinquish_special_privs_perm();
2286 relinquish_all_capabilities();
2291 /* close the capture input file (pcap or capture pipe) */
2292 static void capture_loop_close_input(loop_data *ld)
2295 pcap_options *pcap_opts;
2297 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2299 for (i = 0; i < ld->pcaps->len; i++) {
2300 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2301 /* if open, close the capture pipe "input file" */
2302 if (pcap_opts->cap_pipe_fd >= 0) {
2303 g_assert(pcap_opts->from_cap_pipe);
2304 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2305 pcap_opts->cap_pipe_fd = -1;
2308 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2309 CloseHandle(pcap_opts->cap_pipe_h);
2310 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2313 /* if open, close the pcap "input file" */
2314 if (pcap_opts->pcap_h != NULL) {
2315 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2316 pcap_close(pcap_opts->pcap_h);
2317 pcap_opts->pcap_h = NULL;
2324 /* Shut down windows sockets */
2330 /* init the capture filter */
2331 static initfilter_status_t
2332 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2333 const gchar * name, const gchar * cfilter)
2335 struct bpf_program fcode;
2337 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2339 /* capture filters only work on real interfaces */
2340 if (cfilter && !from_cap_pipe) {
2341 /* A capture filter was specified; set it up. */
2342 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2343 /* Treat this specially - our caller might try to compile this
2344 as a display filter and, if that succeeds, warn the user that
2345 the display and capture filter syntaxes are different. */
2346 return INITFILTER_BAD_FILTER;
2348 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2349 #ifdef HAVE_PCAP_FREECODE
2350 pcap_freecode(&fcode);
2352 return INITFILTER_OTHER_ERROR;
2354 #ifdef HAVE_PCAP_FREECODE
2355 pcap_freecode(&fcode);
2359 return INITFILTER_NO_ERROR;
2363 /* set up to write to the already-opened capture output file/files */
2365 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2369 pcap_options *pcap_opts;
2370 interface_options interface_opts;
2371 gboolean successful;
2373 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2375 if ((capture_opts->use_pcapng == FALSE) &&
2376 (capture_opts->ifaces->len > 1)) {
2377 g_snprintf(errmsg, errmsg_len,
2378 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
2382 /* Set up to write to the capture file. */
2383 if (capture_opts->multi_files_on) {
2384 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2386 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2387 if (ld->pdh == NULL) {
2392 if (capture_opts->use_pcapng) {
2394 GString *os_info_str;
2396 os_info_str = g_string_new("");
2397 get_os_version_info(os_info_str);
2399 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2400 successful = pcapng_write_session_header_block(ld->pdh,
2401 (const char *)capture_opts->capture_comment, /* Comment*/
2403 os_info_str->str, /* OS*/
2405 -1, /* section_length */
2410 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2411 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2412 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2413 if (pcap_opts->from_cap_pipe) {
2414 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2416 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2418 successful = pcapng_write_interface_description_block(global_ld.pdh,
2419 NULL, /* OPT_COMMENT 1 */
2420 interface_opts.name, /* IDB_NAME 2 */
2421 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2422 interface_opts.cfilter, /* IDB_FILTER 11 */
2423 os_info_str->str, /* IDB_OS 12 */
2424 pcap_opts->linktype,
2426 &(global_ld.bytes_written),
2427 0, /* IDB_IF_SPEED 8 */
2428 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2432 g_string_free(os_info_str, TRUE);
2435 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2436 if (pcap_opts->from_cap_pipe) {
2437 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2439 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2441 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2442 pcap_opts->ts_nsec, &ld->bytes_written, &err);
2450 if (ld->pdh == NULL) {
2451 /* We couldn't set up to write to the capture file. */
2452 /* XXX - use cf_open_error_message from tshark instead? */
2457 g_snprintf(errmsg, errmsg_len,
2458 "The file to which the capture would be"
2459 " saved (\"%s\") could not be opened: Error %d.",
2460 capture_opts->save_file, err);
2462 g_snprintf(errmsg, errmsg_len,
2463 "The file to which the capture would be"
2464 " saved (\"%s\") could not be opened: %s.",
2465 capture_opts->save_file, g_strerror(err));
2477 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2481 pcap_options *pcap_opts;
2482 guint64 end_time = create_timestamp();
2484 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2486 if (capture_opts->multi_files_on) {
2487 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2489 if (capture_opts->use_pcapng) {
2490 for (i = 0; i < global_ld.pcaps->len; i++) {
2491 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2492 if (!pcap_opts->from_cap_pipe) {
2493 guint64 isb_ifrecv, isb_ifdrop;
2494 struct pcap_stat stats;
2496 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
2497 isb_ifrecv = pcap_opts->received;
2498 isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
2500 isb_ifrecv = G_MAXUINT64;
2501 isb_ifdrop = G_MAXUINT64;
2503 pcapng_write_interface_statistics_block(ld->pdh,
2506 "Counters provided by dumpcap",
2515 if (fclose(ld->pdh) == EOF) {
2516 if (err_close != NULL) {
2526 /* dispatch incoming packets (pcap or capture pipe)
2528 * Waits for incoming packets to be available, and calls pcap_dispatch()
2529 * to cause them to be processed.
2531 * Returns the number of packets which were processed.
2533 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2534 * packet-batching behaviour does not cause packets to get held back
2538 capture_loop_dispatch(loop_data *ld,
2539 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
2542 gint packet_count_before;
2543 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2548 packet_count_before = ld->packet_count;
2549 if (pcap_opts->from_cap_pipe) {
2550 /* dispatch from capture pipe */
2551 #ifdef LOG_CAPTURE_VERBOSE
2552 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2555 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
2557 if (sel_ret < 0 && errno != EINTR) {
2558 g_snprintf(errmsg, errmsg_len,
2559 "Unexpected error from select: %s", g_strerror(errno));
2560 report_capture_error(errmsg, please_report);
2565 * "select()" says we can read from the pipe without blocking
2568 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
2578 /* dispatch from pcap */
2579 #ifdef MUST_DO_SELECT
2581 * If we have "pcap_get_selectable_fd()", we use it to get the
2582 * descriptor on which to select; if that's -1, it means there
2583 * is no descriptor on which you can do a "select()" (perhaps
2584 * because you're capturing on a special device, and that device's
2585 * driver unfortunately doesn't support "select()", in which case
2586 * we don't do the select - which means it might not be possible
2587 * to stop a capture until a packet arrives. If that's unacceptable,
2588 * plead with whoever supplies the software for that device to add
2589 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2590 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2591 * later, so it can use pcap_breakloop().
2593 #ifdef LOG_CAPTURE_VERBOSE
2594 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2596 if (pcap_opts->pcap_fd != -1) {
2597 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
2600 * "select()" says we can read from it without blocking; go for
2603 * We don't have pcap_breakloop(), so we only process one packet
2604 * per pcap_dispatch() call, to allow a signal to stop the
2605 * processing immediately, rather than processing all packets
2606 * in a batch before quitting.
2609 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2611 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2615 /* Error, rather than pcap_breakloop(). */
2616 pcap_opts->pcap_err = TRUE;
2618 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2621 if (sel_ret < 0 && errno != EINTR) {
2622 g_snprintf(errmsg, errmsg_len,
2623 "Unexpected error from select: %s", g_strerror(errno));
2624 report_capture_error(errmsg, please_report);
2630 #endif /* MUST_DO_SELECT */
2632 /* dispatch from pcap without select */
2634 #ifdef LOG_CAPTURE_VERBOSE
2635 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2639 * On Windows, we don't support asynchronously telling a process to
2640 * stop capturing; instead, we check for an indication on a pipe
2641 * after processing packets. We therefore process only one packet
2642 * at a time, so that we can check the pipe after every packet.
2645 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2647 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2651 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2653 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2658 /* Error, rather than pcap_breakloop(). */
2659 pcap_opts->pcap_err = TRUE;
2661 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2663 #else /* pcap_next_ex */
2664 #ifdef LOG_CAPTURE_VERBOSE
2665 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2667 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2670 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2671 * see https://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
2672 * This should be fixed in the WinPcap 4.0 alpha release.
2674 * For reference, an example remote interface:
2675 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2678 /* emulate dispatch from pcap */
2681 struct pcap_pkthdr *pkt_header;
2686 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
2688 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2690 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2695 pcap_opts->pcap_err = TRUE;
2699 #endif /* pcap_next_ex */
2703 #ifdef LOG_CAPTURE_VERBOSE
2704 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2707 return ld->packet_count - packet_count_before;
2711 /* Isolate the Universally Unique Identifier from the interface. Basically, we
2712 * want to grab only the characters between the '{' and '}' delimiters.
2714 * Returns a GString that must be freed with g_string_free(). */
2716 isolate_uuid(const char *iface)
2721 ptr = strchr(iface, '{');
2723 return g_string_new(iface);
2724 gstr = g_string_new(ptr + 1);
2726 ptr = strchr(gstr->str, '}');
2730 gstr = g_string_truncate(gstr, ptr - gstr->str);
2735 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2736 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2738 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2739 char *errmsg, int errmsg_len)
2742 gchar *capfile_name;
2744 gboolean is_tempfile;
2746 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2747 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
2749 if (capture_opts->save_file != NULL) {
2750 /* We return to the caller while the capture is in progress.
2751 * Therefore we need to take a copy of save_file in
2752 * case the caller destroys it after we return.
2754 capfile_name = g_strdup(capture_opts->save_file);
2756 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2757 if (capture_opts->multi_files_on) {
2758 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2759 g_snprintf(errmsg, errmsg_len,
2760 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2761 g_free(capfile_name);
2764 if (strcmp(capfile_name, "-") == 0) {
2765 /* write to stdout */
2768 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2769 _setmode(1, O_BINARY);
2772 } /* if (...output_to_pipe ... */
2775 if (capture_opts->multi_files_on) {
2776 /* ringbuffer is enabled */
2777 *save_file_fd = ringbuf_init(capfile_name,
2778 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
2779 capture_opts->group_read_access);
2781 /* we need the ringbuf name */
2782 if (*save_file_fd != -1) {
2783 g_free(capfile_name);
2784 capfile_name = g_strdup(ringbuf_current_filename());
2787 /* Try to open/create the specified file for use as a capture buffer. */
2788 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2789 (capture_opts->group_read_access) ? 0640 : 0600);
2792 is_tempfile = FALSE;
2794 /* Choose a random name for the temporary capture buffer */
2795 if (global_capture_opts.ifaces->len > 1) {
2796 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
2799 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
2801 /* use the generic portion of the interface guid to form the basis of the filename */
2802 if (strncmp("NPF_{", basename, 5)==0)
2804 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
2806 iface = isolate_uuid(basename);
2808 basename = g_strdup(iface->str);
2809 g_string_free(iface, TRUE);
2812 /* generate the temp file name prefix...
2813 * It would be nice if we could specify a pcapng/pcap filename suffix,
2814 * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
2815 if (capture_opts->use_pcapng) {
2816 prefix = g_strconcat("wireshark_pcapng_", basename, NULL);
2818 prefix = g_strconcat("wireshark_pcap_", basename, NULL);
2822 *save_file_fd = create_tempfile(&tmpname, prefix);
2824 capfile_name = g_strdup(tmpname);
2828 /* did we fail to open the output file? */
2829 if (*save_file_fd == -1) {
2831 g_snprintf(errmsg, errmsg_len,
2832 "The temporary file to which the capture would be saved (\"%s\") "
2833 "could not be opened: %s.", capfile_name, g_strerror(errno));
2835 if (capture_opts->multi_files_on) {
2836 ringbuf_error_cleanup();
2839 g_snprintf(errmsg, errmsg_len,
2840 "The file to which the capture would be saved (\"%s\") "
2841 "could not be opened: %s.", capfile_name,
2844 g_free(capfile_name);
2848 if (capture_opts->save_file != NULL) {
2849 g_free(capture_opts->save_file);
2851 capture_opts->save_file = capfile_name;
2852 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2853 "g_free(capfile_name)". */
2859 /* Do the work of handling either the file size or file duration capture
2860 conditions being reached, and switching files or stopping. */
2862 do_file_switch_or_stop(capture_options *capture_opts,
2863 condition *cnd_autostop_files,
2864 condition *cnd_autostop_size,
2865 condition *cnd_file_duration)
2868 pcap_options *pcap_opts;
2869 interface_options interface_opts;
2870 gboolean successful;
2872 if (capture_opts->multi_files_on) {
2873 if (cnd_autostop_files != NULL &&
2874 cnd_eval(cnd_autostop_files, (guint64)++global_ld.autostop_files)) {
2875 /* no files left: stop here */
2876 global_ld.go = FALSE;
2880 /* Switch to the next ringbuffer file */
2881 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2882 &global_ld.save_file_fd, &global_ld.err)) {
2884 /* File switch succeeded: reset the conditions */
2885 global_ld.bytes_written = 0;
2886 if (capture_opts->use_pcapng) {
2888 GString *os_info_str;
2890 os_info_str = g_string_new("");
2891 get_os_version_info(os_info_str);
2893 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2894 successful = pcapng_write_session_header_block(global_ld.pdh,
2897 os_info_str->str, /* OS */
2899 -1, /* section_length */
2900 &(global_ld.bytes_written),
2904 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2905 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2906 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2907 successful = pcapng_write_interface_description_block(global_ld.pdh,
2908 NULL, /* OPT_COMMENT 1 */
2909 interface_opts.name, /* IDB_NAME 2 */
2910 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2911 interface_opts.cfilter, /* IDB_FILTER 11 */
2912 os_info_str->str, /* IDB_OS 12 */
2913 pcap_opts->linktype,
2915 &(global_ld.bytes_written),
2916 0, /* IDB_IF_SPEED 8 */
2917 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2921 g_string_free(os_info_str, TRUE);
2924 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
2925 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
2926 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
2929 fclose(global_ld.pdh);
2930 global_ld.pdh = NULL;
2931 global_ld.go = FALSE;
2934 if (cnd_autostop_size)
2935 cnd_reset(cnd_autostop_size);
2936 if (cnd_file_duration)
2937 cnd_reset(cnd_file_duration);
2938 fflush(global_ld.pdh);
2940 report_packet_count(global_ld.inpkts_to_sync_pipe);
2941 global_ld.inpkts_to_sync_pipe = 0;
2942 report_new_capture_file(capture_opts->save_file);
2944 /* File switch failed: stop here */
2945 global_ld.go = FALSE;
2949 /* single file, stop now */
2950 global_ld.go = FALSE;
2957 pcap_read_handler(void* arg)
2959 pcap_options *pcap_opts;
2960 char errmsg[MSG_MAX_LENGTH+1];
2962 pcap_opts = (pcap_options *)arg;
2964 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
2965 pcap_opts->interface_id);
2967 while (global_ld.go) {
2968 /* dispatch incoming packets */
2969 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
2971 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
2972 pcap_opts->interface_id);
2973 g_thread_exit(NULL);
2977 /* Do the low-level work of a capture.
2978 Returns TRUE if it succeeds, FALSE otherwise. */
2980 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
2983 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
2985 struct timeval upd_time, cur_time;
2989 condition *cnd_file_duration = NULL;
2990 condition *cnd_autostop_files = NULL;
2991 condition *cnd_autostop_size = NULL;
2992 condition *cnd_autostop_duration = NULL;
2995 gboolean cfilter_error = FALSE;
2996 char errmsg[MSG_MAX_LENGTH+1];
2997 char secondary_errmsg[MSG_MAX_LENGTH+1];
2998 pcap_options *pcap_opts;
2999 interface_options interface_opts;
3000 guint i, error_index = 0;
3003 *secondary_errmsg = '\0';
3005 /* init the loop data */
3006 global_ld.go = TRUE;
3007 global_ld.packet_count = 0;
3009 global_ld.report_packet_count = FALSE;
3011 if (capture_opts->has_autostop_packets)
3012 global_ld.packet_max = capture_opts->autostop_packets;
3014 global_ld.packet_max = 0; /* no limit */
3015 global_ld.inpkts_to_sync_pipe = 0;
3016 global_ld.err = 0; /* no error seen yet */
3017 global_ld.pdh = NULL;
3018 global_ld.autostop_files = 0;
3019 global_ld.save_file_fd = -1;
3021 /* We haven't yet gotten the capture statistics. */
3022 *stats_known = FALSE;
3024 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3025 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3027 /* open the "input file" from network interface or capture pipe */
3028 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3029 secondary_errmsg, sizeof(secondary_errmsg))) {
3032 for (i = 0; i < capture_opts->ifaces->len; i++) {
3033 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3034 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3035 /* init the input filter from the network interface (capture pipe will do nothing) */
3037 * When remote capturing WinPCap crashes when the capture filter
3038 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3041 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3042 interface_opts.name,
3043 interface_opts.cfilter?interface_opts.cfilter:"")) {
3045 case INITFILTER_NO_ERROR:
3048 case INITFILTER_BAD_FILTER:
3049 cfilter_error = TRUE;
3051 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3054 case INITFILTER_OTHER_ERROR:
3055 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3056 pcap_geterr(pcap_opts->pcap_h));
3057 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3062 /* If we're supposed to write to a capture file, open it for output
3063 (temporary/specified name/ringbuffer) */
3064 if (capture_opts->saving_to_file) {
3065 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3066 errmsg, sizeof(errmsg))) {
3070 /* set up to write to the already-opened capture output file/files */
3071 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3076 /* XXX - capture SIGTERM and close the capture, in case we're on a
3077 Linux 2.0[.x] system and you have to explicitly close the capture
3078 stream in order to turn promiscuous mode off? We need to do that
3079 in other places as well - and I don't think that works all the
3080 time in any case, due to libpcap bugs. */
3082 /* Well, we should be able to start capturing.
3084 Sync out the capture file, so the header makes it to the file system,
3085 and send a "capture started successfully and capture file created"
3086 message to our parent so that they'll open the capture file and
3087 update its windows to indicate that we have a live capture in
3089 fflush(global_ld.pdh);
3090 report_new_capture_file(capture_opts->save_file);
3093 /* initialize capture stop (and alike) conditions */
3094 init_capture_stop_conditions();
3095 /* create stop conditions */
3096 if (capture_opts->has_autostop_filesize) {
3097 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3098 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3101 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3103 if (capture_opts->has_autostop_duration)
3104 cnd_autostop_duration =
3105 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3107 if (capture_opts->multi_files_on) {
3108 if (capture_opts->has_file_duration)
3110 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3112 if (capture_opts->has_autostop_files)
3113 cnd_autostop_files =
3114 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_files);
3117 /* init the time values */
3119 upd_time = GetTickCount();
3121 gettimeofday(&upd_time, NULL);
3123 start_time = create_timestamp();
3124 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3126 /* WOW, everything is prepared! */
3127 /* please fasten your seat belts, we will enter now the actual capture loop */
3129 pcap_queue = g_async_queue_new();
3130 pcap_queue_bytes = 0;
3131 pcap_queue_packets = 0;
3132 for (i = 0; i < global_ld.pcaps->len; i++) {
3133 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3134 #if GLIB_CHECK_VERSION(2,31,0)
3135 /* XXX - Add an interface name here? */
3136 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3138 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3142 while (global_ld.go) {
3143 /* dispatch incoming packets */
3145 pcap_queue_element *queue_element;
3146 #if GLIB_CHECK_VERSION(2,31,18)
3148 g_async_queue_lock(pcap_queue);
3149 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3151 GTimeVal write_thread_time;
3153 g_get_current_time(&write_thread_time);
3154 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3155 g_async_queue_lock(pcap_queue);
3156 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3158 if (queue_element) {
3159 pcap_queue_bytes -= queue_element->phdr.caplen;
3160 pcap_queue_packets -= 1;
3162 g_async_queue_unlock(pcap_queue);
3163 if (queue_element) {
3164 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3165 "Dequeued a packet of length %d captured on interface %d.",
3166 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3168 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3169 &queue_element->phdr,
3171 g_free(queue_element->pd);
3172 g_free(queue_element);
3178 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3179 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3180 sizeof(errmsg), pcap_opts);
3183 /* Were we asked to print packet counts by the SIGINFO handler? */
3184 if (global_ld.report_packet_count) {
3185 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3186 plurality(global_ld.packet_count, "", "s"));
3187 global_ld.report_packet_count = FALSE;
3192 /* any news from our parent (signal pipe)? -> just stop the capture */
3193 if (!signal_pipe_check_running()) {
3194 global_ld.go = FALSE;
3199 global_ld.inpkts_to_sync_pipe += inpkts;
3201 /* check capture size condition */
3202 if (cnd_autostop_size != NULL &&
3203 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3204 /* Capture size limit reached, do we have another file? */
3205 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3206 cnd_autostop_size, cnd_file_duration))
3208 } /* cnd_autostop_size */
3209 if (capture_opts->output_to_pipe) {
3210 fflush(global_ld.pdh);
3214 /* Only update once every 500ms so as not to overload slow displays.
3215 * This also prevents too much context-switching between the dumpcap
3216 * and wireshark processes.
3218 #define DUMPCAP_UPD_TIME 500
3221 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3222 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3224 gettimeofday(&cur_time, NULL);
3225 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3226 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3229 upd_time = cur_time;
3232 if (pcap_stats(pch, stats) >= 0) {
3233 *stats_known = TRUE;
3236 /* Let the parent process know. */
3237 if (global_ld.inpkts_to_sync_pipe) {
3239 fflush(global_ld.pdh);
3241 /* Send our parent a message saying we've written out
3242 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3244 report_packet_count(global_ld.inpkts_to_sync_pipe);
3246 global_ld.inpkts_to_sync_pipe = 0;
3249 /* check capture duration condition */
3250 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3251 /* The maximum capture time has elapsed; stop the capture. */
3252 global_ld.go = FALSE;
3256 /* check capture file duration condition */
3257 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3258 /* duration limit reached, do we have another file? */
3259 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3260 cnd_autostop_size, cnd_file_duration))
3262 } /* cnd_file_duration */
3266 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3268 pcap_queue_element *queue_element;
3270 for (i = 0; i < global_ld.pcaps->len; i++) {
3271 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3272 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3273 pcap_opts->interface_id);
3274 g_thread_join(pcap_opts->tid);
3275 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3276 pcap_opts->interface_id);
3279 g_async_queue_lock(pcap_queue);
3280 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3281 if (queue_element) {
3282 pcap_queue_bytes -= queue_element->phdr.caplen;
3283 pcap_queue_packets -= 1;
3285 g_async_queue_unlock(pcap_queue);
3286 if (queue_element == NULL) {
3289 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3290 "Dequeued a packet of length %d captured on interface %d.",
3291 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3292 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3293 &queue_element->phdr,
3295 g_free(queue_element->pd);
3296 g_free(queue_element);
3297 global_ld.inpkts_to_sync_pipe += 1;
3298 if (capture_opts->output_to_pipe) {
3299 fflush(global_ld.pdh);
3305 /* delete stop conditions */
3306 if (cnd_file_duration != NULL)
3307 cnd_delete(cnd_file_duration);
3308 if (cnd_autostop_files != NULL)
3309 cnd_delete(cnd_autostop_files);
3310 if (cnd_autostop_size != NULL)
3311 cnd_delete(cnd_autostop_size);
3312 if (cnd_autostop_duration != NULL)
3313 cnd_delete(cnd_autostop_duration);
3315 /* did we have a pcap (input) error? */
3316 for (i = 0; i < capture_opts->ifaces->len; i++) {
3317 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3318 if (pcap_opts->pcap_err) {
3319 /* On Linux, if an interface goes down while you're capturing on it,
3320 you'll get a "recvfrom: Network is down" or
3321 "The interface went down" error (ENETDOWN).
3322 (At least you will if g_strerror() doesn't show a local translation
3325 On FreeBSD and OS X, if a network adapter disappears while
3326 you're capturing on it, you'll get a "read: Device not configured"
3327 error (ENXIO). (See previous parenthetical note.)
3329 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3331 These should *not* be reported to the Wireshark developers. */
3334 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3335 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3336 strcmp(cap_err_str, "The interface went down") == 0 ||
3337 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3338 strcmp(cap_err_str, "read: I/O error") == 0 ||
3339 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3340 report_capture_error("The network adapter on which the capture was being done "
3341 "is no longer running; the capture has stopped.",
3344 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3346 report_capture_error(errmsg, please_report);
3349 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3350 report_capture_error(errmsg, "");
3354 /* did we have an output error while capturing? */
3355 if (global_ld.err == 0) {
3358 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3359 global_ld.err, FALSE);
3360 report_capture_error(errmsg, please_report);
3364 if (capture_opts->saving_to_file) {
3365 /* close the output file */
3366 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3370 /* there might be packets not yet notified to the parent */
3371 /* (do this after closing the file, so all packets are already flushed) */
3372 if (global_ld.inpkts_to_sync_pipe) {
3374 report_packet_count(global_ld.inpkts_to_sync_pipe);
3375 global_ld.inpkts_to_sync_pipe = 0;
3378 /* If we've displayed a message about a write error, there's no point
3379 in displaying another message about an error on close. */
3380 if (!close_ok && write_ok) {
3381 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3383 report_capture_error(errmsg, "");
3387 * XXX We exhibit different behaviour between normal mode and sync mode
3388 * when the pipe is stdin and not already at EOF. If we're a child, the
3389 * parent's stdin isn't closed, so if the user starts another capture,
3390 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3391 * will say "Unrecognized libpcap format". On the other hand, in normal
3392 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3395 report_capture_count(TRUE);
3397 /* get packet drop statistics from pcap */
3398 for (i = 0; i < capture_opts->ifaces->len; i++) {
3400 guint32 pcap_dropped = 0;
3402 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3403 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3404 received = pcap_opts->received;
3405 if (pcap_opts->pcap_h != NULL) {
3406 g_assert(!pcap_opts->from_cap_pipe);
3407 /* Get the capture statistics, so we know how many packets were dropped. */
3409 * Older versions of libpcap didn't set ps_ifdrop on some
3410 * platforms; initialize it to 0 to handle that.
3412 stats->ps_ifdrop = 0;
3413 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3414 *stats_known = TRUE;
3415 /* Let the parent process know. */
3416 pcap_dropped += stats->ps_drop;
3418 g_snprintf(errmsg, sizeof(errmsg),
3419 "Can't get packet-drop statistics: %s",
3420 pcap_geterr(pcap_opts->pcap_h));
3421 report_capture_error(errmsg, please_report);
3424 report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
3427 /* close the input file (pcap or capture pipe) */
3428 capture_loop_close_input(&global_ld);
3430 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
3432 /* ok, if the write and the close were successful. */
3433 return write_ok && close_ok;
3436 if (capture_opts->multi_files_on) {
3437 /* cleanup ringbuffer */
3438 ringbuf_error_cleanup();
3440 /* We can't use the save file, and we have no FILE * for the stream
3441 to close in order to close it, so close the FD directly. */
3442 if (global_ld.save_file_fd != -1) {
3443 ws_close(global_ld.save_file_fd);
3446 /* We couldn't even start the capture, so get rid of the capture
3448 if (capture_opts->save_file != NULL) {
3449 ws_unlink(capture_opts->save_file);
3450 g_free(capture_opts->save_file);
3453 capture_opts->save_file = NULL;
3455 report_cfilter_error(capture_opts, error_index, errmsg);
3457 report_capture_error(errmsg, secondary_errmsg);
3459 /* close the input file (pcap or cap_pipe) */
3460 capture_loop_close_input(&global_ld);
3462 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3469 capture_loop_stop(void)
3471 #ifdef HAVE_PCAP_BREAKLOOP
3473 pcap_options *pcap_opts;
3475 for (i = 0; i < global_ld.pcaps->len; i++) {
3476 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3477 if (pcap_opts->pcap_h != NULL)
3478 pcap_breakloop(pcap_opts->pcap_h);
3481 global_ld.go = FALSE;
3486 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3487 int err, gboolean is_close)
3492 g_snprintf(errmsg, errmsglen,
3493 "Not all the packets could be written to the file"
3494 " to which the capture was being saved\n"
3495 "(\"%s\") because there is no space left on the file system\n"
3496 "on which that file resides.",
3502 g_snprintf(errmsg, errmsglen,
3503 "Not all the packets could be written to the file"
3504 " to which the capture was being saved\n"
3505 "(\"%s\") because you are too close to, or over,"
3506 " your disk quota\n"
3507 "on the file system on which that file resides.",
3514 g_snprintf(errmsg, errmsglen,
3515 "The file to which the capture was being saved\n"
3516 "(\"%s\") could not be closed: %s.",
3517 fname, g_strerror(err));
3519 g_snprintf(errmsg, errmsglen,
3520 "An error occurred while writing to the file"
3521 " to which the capture was being saved\n"
3523 fname, g_strerror(err));
3530 /* one packet was captured, process it */
3532 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3535 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3537 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
3539 /* We may be called multiple times from pcap_dispatch(); if we've set
3540 the "stop capturing" flag, ignore this packet, as we're not
3541 supposed to be saving any more packets. */
3542 if (!global_ld.go) {
3543 pcap_opts->flushed++;
3547 if (global_ld.pdh) {
3548 gboolean successful;
3550 /* We're supposed to write the packet to a file; do so.
3551 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3552 "ld->err" to the error. */
3553 if (global_capture_opts.use_pcapng) {
3554 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
3556 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3557 phdr->caplen, phdr->len,
3558 pcap_opts->interface_id,
3561 &global_ld.bytes_written, &err);
3563 successful = libpcap_write_packet(global_ld.pdh,
3564 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3565 phdr->caplen, phdr->len,
3567 &global_ld.bytes_written, &err);
3570 global_ld.go = FALSE;
3571 global_ld.err = err;
3572 pcap_opts->dropped++;
3574 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3575 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3576 "Wrote a packet of length %d captured on interface %u.",
3577 phdr->caplen, pcap_opts->interface_id);
3579 global_ld.packet_count++;
3580 pcap_opts->received++;
3581 /* if the user told us to stop after x packets, do we already have enough? */
3582 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
3583 global_ld.go = FALSE;
3589 /* one packet was captured, queue it */
3591 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3594 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3595 pcap_queue_element *queue_element;
3596 gboolean limit_reached;
3598 /* We may be called multiple times from pcap_dispatch(); if we've set
3599 the "stop capturing" flag, ignore this packet, as we're not
3600 supposed to be saving any more packets. */
3601 if (!global_ld.go) {
3602 pcap_opts->flushed++;
3606 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
3607 if (queue_element == NULL) {
3608 pcap_opts->dropped++;
3611 queue_element->pcap_opts = pcap_opts;
3612 queue_element->phdr = *phdr;
3613 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
3614 if (queue_element->pd == NULL) {
3615 pcap_opts->dropped++;
3616 g_free(queue_element);
3619 memcpy(queue_element->pd, pd, phdr->caplen);
3620 g_async_queue_lock(pcap_queue);
3621 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
3622 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
3623 limit_reached = FALSE;
3624 g_async_queue_push_unlocked(pcap_queue, queue_element);
3625 pcap_queue_bytes += phdr->caplen;
3626 pcap_queue_packets += 1;
3628 limit_reached = TRUE;
3630 g_async_queue_unlock(pcap_queue);
3631 if (limit_reached) {
3632 pcap_opts->dropped++;
3633 g_free(queue_element->pd);
3634 g_free(queue_element);
3635 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3636 "Dropped a packet of length %d captured on interface %u.",
3637 phdr->caplen, pcap_opts->interface_id);
3639 pcap_opts->received++;
3640 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3641 "Queued a packet of length %d captured on interface %u.",
3642 phdr->caplen, pcap_opts->interface_id);
3644 /* I don't want to hold the mutex over the debug output. So the
3645 output may be wrong */
3646 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3647 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
3648 pcap_queue_bytes, pcap_queue_packets);
3652 set_80211_channel(const char *iface, const char *opt)
3654 int freq = 0, type, ret;
3655 gchar **options = NULL;
3657 options = g_strsplit_set(opt, ",", 2);
3660 freq = atoi(options[0]);
3663 type = ws80211_str_to_chan_type(options[1]);
3672 ret = ws80211_init();
3674 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
3678 ret = ws80211_set_freq(iface, freq, type);
3681 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
3687 pipe_write_block(2, SP_SUCCESS, NULL);
3691 g_strfreev(options);
3696 get_dumpcap_compiled_info(GString *str)
3698 /* Capture libraries */
3699 g_string_append(str, ", ");
3700 get_compiled_caplibs_version(str);
3703 g_string_append(str, ", ");
3705 g_string_append(str, "with libz ");
3707 g_string_append(str, ZLIB_VERSION);
3708 #else /* ZLIB_VERSION */
3709 g_string_append(str, "(version unknown)");
3710 #endif /* ZLIB_VERSION */
3711 #else /* HAVE_LIBZ */
3712 g_string_append(str, "without libz");
3713 #endif /* HAVE_LIBZ */
3717 get_dumpcap_runtime_info(GString *str)
3719 /* Capture libraries */
3720 g_string_append(str, ", ");
3721 get_runtime_caplibs_version(str);
3724 #if defined(HAVE_LIBZ) && !defined(_WIN32)
3725 g_string_append_printf(str, ", with libz %s", zlibVersion());
3729 /* And now our feature presentation... [ fade to music ] */
3731 main(int argc, char *argv[])
3733 GString *comp_info_str;
3734 GString *runtime_info_str;
3736 static const struct option long_options[] = {
3737 {"help", no_argument, NULL, 'h'},
3738 {"version", no_argument, NULL, 'v'},
3739 LONGOPT_CAPTURE_COMMON
3743 gboolean arg_error = FALSE;
3748 struct sigaction action, oldaction;
3751 gboolean start_capture = TRUE;
3752 gboolean stats_known;
3753 struct pcap_stat stats;
3754 GLogLevelFlags log_flags;
3755 gboolean list_interfaces = FALSE;
3756 gboolean list_link_layer_types = FALSE;
3757 #ifdef HAVE_BPF_IMAGE
3758 gboolean print_bpf_code = FALSE;
3760 gboolean set_chan = FALSE;
3761 gchar *set_chan_arg = NULL;
3762 gboolean machine_readable = FALSE;
3763 gboolean print_statistics = FALSE;
3764 int status, run_once_args = 0;
3767 #if defined(__APPLE__) && defined(__LP64__)
3768 struct utsname osinfo;
3772 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
3774 /* Get the compile-time version information string */
3775 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
3777 /* Get the run-time version information string */
3778 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
3780 /* Add it to the information to be reported on a crash. */
3781 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
3786 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
3789 arg_list_utf_16to8(argc, argv);
3790 create_app_running_mutex();
3793 * Initialize our DLL search path. MUST be called before LoadLibrary
3796 ws_init_dll_search_path();
3799 #ifdef HAVE_BPF_IMAGE
3800 #define OPTSTRING_d "d"
3802 #define OPTSTRING_d ""
3805 #ifdef HAVE_PCAP_REMOTE
3806 #define OPTSTRING_r "r"
3807 #define OPTSTRING_u "u"
3809 #define OPTSTRING_r ""
3810 #define OPTSTRING_u ""
3813 #ifdef HAVE_PCAP_SETSAMPLING
3814 #define OPTSTRING_m "m:"
3816 #define OPTSTRING_m ""
3819 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
3821 #ifdef DEBUG_CHILD_DUMPCAP
3822 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3823 fprintf (stderr, "Unable to open debug log file .\n");
3828 #if defined(__APPLE__) && defined(__LP64__)
3830 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
3831 * a bug workaround - timeouts less than 1 second don't work with libpcap
3832 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3833 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
3834 * The problem is extremely unlikely to be reintroduced in a future
3837 if (uname(&osinfo) == 0) {
3839 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
3840 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3841 * number of 10.0.0, not 10.1.0 - go figure).
3843 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
3844 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
3845 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
3846 need_timeout_workaround = TRUE;
3851 * Determine if dumpcap is being requested to run in a special
3852 * capture_child mode by going thru the command line args to see if
3853 * a -Z is present. (-Z is a hidden option).
3855 * The primary result of running in capture_child mode is that
3856 * all messages sent out on stderr are in a special type/len/string
3857 * format to allow message processing by type. These messages include
3858 * error messages if dumpcap fails to start the operation it was
3859 * requested to do, as well as various "status" messages which are sent
3860 * when an actual capture is in progress, and a "success" message sent
3861 * if dumpcap was requested to perform an operation other than a
3864 * Capture_child mode would normally be requested by a parent process
3865 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3866 * to which dumpcap stderr has been redirected. It might also have
3867 * another pipe to obtain dumpcap stdout output; for operations other
3868 * than a capture, that information is formatted specially for easier
3869 * parsing by the parent process.
3871 * Capture_child mode needs to be determined immediately upon
3872 * startup so that any messages generated by dumpcap in this mode
3873 * (eg: during initialization) will be formatted properly.
3876 for (i=1; i<argc; i++) {
3877 if (strcmp("-Z", argv[i]) == 0) {
3878 capture_child = TRUE;
3879 machine_readable = TRUE; /* request machine-readable output */
3881 /* set output pipe to binary mode, to avoid ugly text conversions */
3882 _setmode(2, O_BINARY);
3887 /* The default_log_handler will use stdout, which makes trouble in */
3888 /* capture child mode, as it uses stdout for its sync_pipe. */
3889 /* So: the filtering is done in the console_log_handler and not here.*/
3890 /* We set the log handlers right up front to make sure that any log */
3891 /* messages when running as child will be sent back to the parent */
3892 /* with the correct format. */
3897 G_LOG_LEVEL_CRITICAL|
3898 G_LOG_LEVEL_WARNING|
3899 G_LOG_LEVEL_MESSAGE|
3903 G_LOG_FLAG_RECURSION);
3905 g_log_set_handler(NULL,
3907 console_log_handler, NULL /* user_data */);
3908 g_log_set_handler(LOG_DOMAIN_MAIN,
3910 console_log_handler, NULL /* user_data */);
3911 g_log_set_handler(LOG_DOMAIN_CAPTURE,
3913 console_log_handler, NULL /* user_data */);
3914 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3916 console_log_handler, NULL /* user_data */);
3918 /* Initialize the pcaps list */
3919 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
3921 #if !GLIB_CHECK_VERSION(2,31,0)
3922 /* Initialize the thread system */
3923 g_thread_init(NULL);
3927 /* Load wpcap if possible. Do this before collecting the run-time version information */
3930 /* ... and also load the packet.dll from wpcap */
3931 /* XXX - currently not required, may change later. */
3932 /*wpcap_packet_load();*/
3934 /* Start windows sockets */
3935 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3937 /* Set handler for Ctrl+C key */
3938 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3940 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3941 and exit. Do the same with SIGPIPE, in case, for example,
3942 we're writing to our standard output and it's a pipe.
3943 Do the same with SIGHUP if it's not being ignored (if we're
3944 being run under nohup, it might be ignored, in which case we
3945 should leave it ignored).
3947 XXX - apparently, Coverity complained that part of action
3948 wasn't initialized. Perhaps it's running on Linux, where
3949 struct sigaction has an ignored "sa_restorer" element and
3950 where "sa_handler" and "sa_sigaction" might not be two
3951 members of a union. */
3952 memset(&action, 0, sizeof(action));
3953 action.sa_handler = capture_cleanup_handler;
3955 * Arrange that system calls not get restarted, because when
3956 * our signal handler returns we don't want to restart
3957 * a call that was waiting for packets to arrive.
3959 action.sa_flags = 0;
3960 sigemptyset(&action.sa_mask);
3961 sigaction(SIGTERM, &action, NULL);
3962 sigaction(SIGINT, &action, NULL);
3963 sigaction(SIGPIPE, &action, NULL);
3964 sigaction(SIGHUP, NULL, &oldaction);
3965 if (oldaction.sa_handler == SIG_DFL)
3966 sigaction(SIGHUP, &action, NULL);
3969 /* Catch SIGINFO and, if we get it and we're capturing in
3970 quiet mode, report the number of packets we've captured. */
3971 action.sa_handler = report_counts_siginfo;
3972 action.sa_flags = SA_RESTART;
3973 sigemptyset(&action.sa_mask);
3974 sigaction(SIGINFO, &action, NULL);
3975 #endif /* SIGINFO */
3979 enable_kernel_bpf_jit_compiler();
3982 /* ----------------------------------------------------------------- */
3983 /* Privilege and capability handling */
3985 /* 1. Running not as root or suid root; no special capabilities. */
3988 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
3991 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
3993 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3994 /* capabilities; Drop all other capabilities; */
3995 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3996 /* else: after pcap_open_live() in capture_loop_open_input() */
3997 /* drop all capabilities (NET_RAW and NET_ADMIN); */
3998 /* (Note: this means that the process, although logged in */
3999 /* as root, does not have various permissions such as the */
4000 /* ability to bypass file access permissions). */
4001 /* XXX: Should we just leave capabilities alone in this case */
4002 /* so that user gets expected effect that root can do */
4005 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4007 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4008 /* else: after pcap_open_live() in capture_loop_open_input() */
4009 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4010 /* pcap_open_live). */
4012 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4014 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4015 /* capabilities; Drop all other capabilities; */
4016 /* Drop suid privileges (euid=ruid); */
4017 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4018 /* else: after pcap_open_live() in capture_loop_open_input() */
4019 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4021 /* XXX: For some Linux versions/distros with capabilities */
4022 /* a 'normal' process with any capabilities cannot be */
4023 /* 'killed' (signaled) from another (same uid) non-privileged */
4025 /* For example: If (non-suid) Wireshark forks a */
4026 /* child suid dumpcap which acts as described here (case 5), */
4027 /* Wireshark will be unable to kill (signal) the child */
4028 /* dumpcap process until the capabilities have been dropped */
4029 /* (after pcap_open_live()). */
4030 /* This behaviour will apparently be changed in the kernel */
4031 /* to allow the kill (signal) in this case. */
4032 /* See the following for details: */
4033 /* https://www.mail-archive.com/ [wrapped] */
4034 /* linux-security-module@vger.kernel.org/msg02913.html */
4036 /* It is therefore conceivable that if dumpcap somehow hangs */
4037 /* in pcap_open_live or before that wireshark will not */
4038 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4039 /* In this case, exiting wireshark will kill the child */
4040 /* dumpcap process. */
4042 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4043 /* capabilities; Using libcap. Note: capset cmd (which see) */
4044 /* used to assign capabilities to file. */
4046 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4047 /* else: after pcap_open_live() in capture_loop_open_input() */
4048 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4050 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4051 /* longer required (similar to capture). */
4053 /* ----------------------------------------------------------------- */
4055 init_process_policies();
4058 /* If 'started with special privileges' (and using libcap) */
4059 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4060 /* Set euid/egid = ruid/rgid to remove suid privileges */
4061 relinquish_privs_except_capture();
4064 /* Set the initial values in the capture options. This might be overwritten
4065 by the command line parameters. */
4066 capture_opts_init(&global_capture_opts);
4067 /* We always save to a file - if no file was specified, we save to a
4069 global_capture_opts.saving_to_file = TRUE;
4070 global_capture_opts.has_ring_num_files = TRUE;
4072 /* Pass on capture_child mode for capture_opts */
4073 global_capture_opts.capture_child = capture_child;
4075 /* Now get our args */
4076 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4078 case 'h': /* Print help and exit */
4079 printf("Dumpcap (Wireshark) %s\n"
4080 "Capture network packets and dump them into a pcapng or pcap file.\n"
4081 "See https://www.wireshark.org for more information.\n",
4082 get_ws_vcs_version_info());
4083 print_usage(stdout);
4086 case 'v': /* Show version and exit */
4088 show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4089 g_string_free(comp_info_str, TRUE);
4090 g_string_free(runtime_info_str, TRUE);
4094 /*** capture option specific ***/
4095 case 'a': /* autostop criteria */
4096 case 'b': /* Ringbuffer option */
4097 case 'c': /* Capture x packets */
4098 case 'f': /* capture filter */
4099 case 'g': /* enable group read access on file(s) */
4100 case 'i': /* Use interface x */
4101 case 'n': /* Use pcapng format */
4102 case 'p': /* Don't capture in promiscuous mode */
4103 case 'P': /* Use pcap format */
4104 case 's': /* Set the snapshot (capture) length */
4105 case 'w': /* Write to capture file x */
4106 case 'y': /* Set the pcap data link type */
4107 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4108 #ifdef HAVE_PCAP_REMOTE
4109 case 'u': /* Use UDP for data transfer */
4110 case 'r': /* Capture own RPCAP traffic too */
4111 case 'A': /* Authentication */
4113 #ifdef HAVE_PCAP_SETSAMPLING
4114 case 'm': /* Sampling */
4116 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4117 case 'B': /* Buffer size */
4119 #ifdef HAVE_PCAP_CREATE
4120 case 'I': /* Monitor mode */
4122 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4127 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4129 capture_child = TRUE;
4131 /* set output pipe to binary mode, to avoid ugly text conversions */
4132 _setmode(2, O_BINARY);
4134 * optarg = the control ID, aka the PPID, currently used for the
4137 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4138 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4139 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4140 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4142 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4143 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4144 "Signal pipe: Unable to open %s. Dead parent?",
4152 case 'q': /* Quiet */
4158 /*** all non capture option specific ***/
4159 case 'D': /* Print a list of capture devices and exit */
4160 if (!list_interfaces) {
4161 list_interfaces = TRUE;
4165 case 'L': /* Print list of link-layer types and exit */
4166 if (!list_link_layer_types) {
4167 list_link_layer_types = TRUE;
4171 #ifdef HAVE_BPF_IMAGE
4172 case 'd': /* Print BPF code for capture filter and exit */
4173 if (!print_bpf_code) {
4174 print_bpf_code = TRUE;
4179 case 'S': /* Print interface statistics once a second */
4180 if (!print_statistics) {
4181 print_statistics = TRUE;
4185 case 'k': /* Set wireless channel */
4188 set_chan_arg = optarg;
4191 cmdarg_err("Only one -k flag may be specified");
4195 case 'M': /* For -D, -L, and -S, print machine-readable output */
4196 machine_readable = TRUE;
4199 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4202 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4205 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4207 case '?': /* Bad flag - print usage message */
4216 /* user specified file name as regular command-line argument */
4217 /* XXX - use it as the capture file name (or something else)? */
4223 * Extra command line arguments were specified; complain.
4224 * XXX - interpret as capture filter, as tcpdump and tshark do?
4226 cmdarg_err("Invalid argument: %s", argv[0]);
4231 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4234 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4235 /* Use some default if the user hasn't specified some */
4236 /* XXX: Are these defaults good enough? */
4237 pcap_queue_byte_limit = 1000 * 1000;
4238 pcap_queue_packet_limit = 1000;
4241 print_usage(stderr);
4245 if (run_once_args > 1) {
4246 #ifdef HAVE_BPF_IMAGE
4247 cmdarg_err("Only one of -D, -L, -d, -k, or -S may be supplied.");
4249 cmdarg_err("Only one of -D, -L, -k, or -S may be supplied.");
4252 } else if (run_once_args == 1) {
4253 /* We're supposed to print some information, rather than
4254 to capture traffic; did they specify a ring buffer option? */
4255 if (global_capture_opts.multi_files_on) {
4256 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4260 /* We're supposed to capture traffic; */
4262 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4263 if (global_capture_opts.ifaces->len > 1) {
4265 global_capture_opts.use_pcapng = TRUE;
4268 if (global_capture_opts.capture_comment &&
4269 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4270 /* XXX - for ringbuffer, should we apply the comment to each file? */
4271 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4275 /* Was the ring buffer option specified and, if so, does it make sense? */
4276 if (global_capture_opts.multi_files_on) {
4277 /* Ring buffer works only under certain conditions:
4278 a) ring buffer does not work with temporary files;
4279 b) it makes no sense to enable the ring buffer if the maximum
4280 file size is set to "infinite". */
4281 if (global_capture_opts.save_file == NULL) {
4282 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4283 global_capture_opts.multi_files_on = FALSE;
4285 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4286 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4288 /* XXX - this must be redesigned as the conditions changed */
4289 global_capture_opts.multi_files_on = FALSE;
4296 * "-D" requires no interface to be selected; it's supposed to list
4299 if (list_interfaces) {
4300 /* Get the list of interfaces */
4305 if_list = capture_interface_list(&err, &err_str,NULL);
4306 if (if_list == NULL) {
4309 * If we're being run by another program, just give them
4310 * an empty list of interfaces, don't report this as
4311 * an error; that lets them decide whether to report
4312 * this as an error or not.
4314 if (!machine_readable) {
4315 cmdarg_err("There are no interfaces on which a capture can be done");
4319 cmdarg_err("%s", err_str);
4325 if (machine_readable) /* tab-separated values to stdout */
4326 print_machine_readable_interfaces(if_list);
4328 capture_opts_print_interfaces(if_list);
4329 free_interface_list(if_list);
4334 * "-S" requires no interface to be selected; it gives statistics
4335 * for all interfaces.
4337 if (print_statistics) {
4338 status = print_statistics_loop(machine_readable);
4343 interface_options interface_opts;
4345 if (global_capture_opts.ifaces->len != 1) {
4346 cmdarg_err("Need one interface");
4350 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4351 status = set_80211_channel(interface_opts.name, set_chan_arg);
4356 * "-L", "-d", and capturing act on a particular interface, so we have to
4357 * have an interface; if none was specified, pick a default.
4359 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4361 /* cmdarg_err() already called .... */
4365 if (list_link_layer_types) {
4366 /* Get the list of link-layer types for the capture device. */
4367 if_capabilities_t *caps;
4371 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4372 interface_options interface_opts;
4374 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4376 caps = get_if_capabilities(&interface_opts, &err_str);
4378 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4379 "Please check to make sure you have sufficient permissions, and that\n"
4380 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4384 if (caps->data_link_types == NULL) {
4385 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4388 if (machine_readable) /* tab-separated values to stdout */
4389 /* XXX: We need to change the format and adopt consumers */
4390 print_machine_readable_if_capabilities(caps);
4392 /* XXX: We might want to print also the interface name */
4393 capture_opts_print_if_capabilities(caps, interface_opts.name,
4394 interface_opts.monitor_mode);
4395 free_if_capabilities(caps);
4400 /* We're supposed to do a capture, or print the BPF code for a filter. */
4402 /* Let the user know what interfaces were chosen. */
4403 if (capture_child) {
4404 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4405 interface_options interface_opts;
4407 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4408 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4409 interface_opts.name);
4412 str = g_string_new("");
4414 if (global_capture_opts.ifaces->len < 2)
4416 if (global_capture_opts.ifaces->len < 4)
4419 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4420 interface_options interface_opts;
4422 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4424 if (global_capture_opts.ifaces->len > 2) {
4425 g_string_append_printf(str, ",");
4427 g_string_append_printf(str, " ");
4428 if (j == global_capture_opts.ifaces->len - 1) {
4429 g_string_append_printf(str, "and ");
4432 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4435 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4437 fprintf(stderr, "Capturing on %s\n", str->str);
4438 g_string_free(str, TRUE);
4441 /* Process the snapshot length, as that affects the generated BPF code. */
4442 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4444 #ifdef HAVE_BPF_IMAGE
4445 if (print_bpf_code) {
4446 show_filter_code(&global_capture_opts);
4451 /* We're supposed to do a capture. Process the ring buffer arguments. */
4452 capture_opts_trim_ring_num_files(&global_capture_opts);
4454 /* flush stderr prior to starting the main capture loop */
4457 /* Now start the capture. */
4458 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4462 /* capture failed */
4465 return 0; /* never here, make compiler happy */
4470 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4471 const char *message, gpointer user_data _U_)
4478 /* ignore log message, if log_level isn't interesting */
4479 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4480 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4485 /* create a "timestamp" */
4487 today = localtime(&curr);
4489 switch(log_level & G_LOG_LEVEL_MASK) {
4490 case G_LOG_LEVEL_ERROR:
4493 case G_LOG_LEVEL_CRITICAL:
4496 case G_LOG_LEVEL_WARNING:
4499 case G_LOG_LEVEL_MESSAGE:
4502 case G_LOG_LEVEL_INFO:
4505 case G_LOG_LEVEL_DEBUG:
4509 fprintf(stderr, "unknown log_level %d\n", log_level);
4511 g_assert_not_reached();
4514 /* Generate the output message */
4515 if (log_level & G_LOG_LEVEL_MESSAGE) {
4516 /* normal user messages without additional infos */
4517 msg = g_strdup_printf("%s\n", message);
4519 /* info/debug messages with additional infos */
4520 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4521 today->tm_hour, today->tm_min, today->tm_sec,
4522 log_domain != NULL ? log_domain : "",
4526 /* DEBUG & INFO msgs (if we're debugging today) */
4527 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4528 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4529 #ifdef DEBUG_DUMPCAP
4530 fprintf(stderr, "%s", msg);
4533 #ifdef DEBUG_CHILD_DUMPCAP
4534 fprintf(debug_log, "%s", msg);
4542 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4543 /* to parent especially formatted if dumpcap running as child. */
4544 if (capture_child) {
4545 sync_pipe_errmsg_to_parent(2, msg, "");
4547 fprintf(stderr, "%s", msg);
4554 /****************************************************************************************************************/
4555 /* indication report routines */
4559 report_packet_count(unsigned int packet_count)
4561 char tmp[SP_DECISIZE+1+1];
4562 static unsigned int count = 0;
4564 if (capture_child) {
4565 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
4566 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4567 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4569 count += packet_count;
4570 fprintf(stderr, "\rPackets: %u ", count);
4571 /* stderr could be line buffered */
4577 report_new_capture_file(const char *filename)
4579 if (capture_child) {
4580 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4581 pipe_write_block(2, SP_FILE, filename);
4585 * Prevent a SIGINFO handler from writing to the standard error
4586 * while we're doing so; instead, have it just set a flag telling
4587 * us to print that information when we're done.
4590 #endif /* SIGINFO */
4591 fprintf(stderr, "File: %s\n", filename);
4592 /* stderr could be line buffered */
4597 * Allow SIGINFO handlers to write.
4602 * If a SIGINFO handler asked us to write out capture counts, do so.
4605 report_counts_for_siginfo();
4606 #endif /* SIGINFO */
4611 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4613 interface_options interface_opts;
4614 char tmp[MSG_MAX_LENGTH+1+6];
4616 if (i < capture_opts->ifaces->len) {
4617 if (capture_child) {
4618 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4619 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4620 pipe_write_block(2, SP_BAD_FILTER, tmp);
4623 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
4624 * the error message below.
4626 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
4628 "Invalid capture filter \"%s\" for interface '%s'.\n"
4630 "That string isn't a valid capture filter (%s).\n"
4631 "See the User's Guide for a description of the capture filter syntax.",
4632 interface_opts.cfilter, interface_opts.name, errmsg);
4638 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4640 if (capture_child) {
4641 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4642 "Primary Error: %s", error_msg);
4643 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4644 "Secondary Error: %s", secondary_error_msg);
4645 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4647 cmdarg_err("%s", error_msg);
4648 if (secondary_error_msg[0] != '\0')
4649 cmdarg_err_cont("%s", secondary_error_msg);
4654 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
4656 char tmp[SP_DECISIZE+1+1];
4657 guint32 total_drops = pcap_drops + drops + flushed;
4659 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
4661 if (capture_child) {
4662 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4663 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
4664 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
4665 /* XXX: Need to provide interface id, changes to consumers required. */
4666 pipe_write_block(2, SP_DROPS, tmp);
4669 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
4670 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
4671 received ? 100.0 * received / (received + total_drops) : 0.0);
4672 /* stderr could be line buffered */
4678 /************************************************************************************************/
4679 /* signal_pipe handling */
4684 signal_pipe_check_running(void)
4686 /* any news from our parent? -> just stop the capture */
4690 /* if we are running standalone, no check required */
4691 if (!capture_child) {
4695 if (!sig_pipe_name || !sig_pipe_handle) {
4696 /* This shouldn't happen */
4697 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4698 "Signal pipe: No name or handle");
4703 * XXX - We should have the process ID of the parent (from the "-Z" flag)
4704 * at this point. Should we check to see if the parent is still alive,
4705 * e.g. by using OpenProcess?
4708 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
4710 if (!result || avail > 0) {
4711 /* peek failed or some bytes really available */
4712 /* (if not piping from stdin this would fail) */
4713 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4714 "Signal pipe: Stop capture: %s", sig_pipe_name);
4715 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4716 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
4717 sig_pipe_handle, result, avail);
4720 /* pipe ok and no bytes available */
4727 * Editor modelines - https://www.wireshark.org/tools/modelines.html
4732 * indent-tabs-mode: nil
4735 * vi: set shiftwidth=4 tabstop=8 expandtab:
4736 * :indentSize=4:tabSize=8:noTabs=true: