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>
57 #include <wsutil/cmdarg_err.h>
58 #include <wsutil/crash_info.h>
59 #include <wsutil/strtoi.h>
60 #include <ws_version_info.h>
62 #ifndef HAVE_GETOPT_LONG
63 #include "wsutil/wsgetopt.h"
71 # include <sys/prctl.h>
72 # include <sys/capability.h>
75 #include "ringbuffer.h"
77 #include "caputils/capture_ifinfo.h"
78 #include "caputils/capture-pcap-util.h"
79 #include "caputils/capture-pcap-util-int.h"
81 #include "caputils/capture-wpcap.h"
84 #include "writecap/pcapio.h"
87 #include <wsutil/unicode-utils.h>
94 #include <wsutil/clopts_common.h>
95 #include <wsutil/privileges.h>
97 #include "sync_pipe.h"
99 #include "capture_opts.h"
100 #include <capchild/capture_session.h>
101 #include <capchild/capture_sync.h>
103 #include "conditions.h"
104 #include "capture_stop_conditions.h"
106 #include "wsutil/tempfile.h"
108 #include "wsutil/file_util.h"
109 #include "wsutil/cpu_info.h"
110 #include "wsutil/os_version_info.h"
111 #include "wsutil/str_util.h"
112 #include "wsutil/inet_addr.h"
114 #include "caputils/ws80211_utils.h"
121 * Get information about libpcap format from "wiretap/libpcap.h".
122 * Get information about pcapng format from "wiretap/pcapng_module.h".
123 * XXX - can we just use pcap_open_offline() to read the pipe?
125 #include "wiretap/libpcap.h"
126 #include "wiretap/pcapng_module.h"
128 /**#define DEBUG_DUMPCAP**/
129 /**#define DEBUG_CHILD_DUMPCAP**/
133 #include <conio.h> /* _getch() */
137 #ifdef DEBUG_CHILD_DUMPCAP
138 FILE *debug_log; /* for logging debug messages to */
139 /* a file if DEBUG_CHILD_DUMPCAP */
143 static GAsyncQueue *pcap_queue;
144 static gint64 pcap_queue_bytes;
145 static gint64 pcap_queue_packets;
146 static gint64 pcap_queue_byte_limit = 0;
147 static gint64 pcap_queue_packet_limit = 0;
149 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
151 static gchar *sig_pipe_name = NULL;
152 static HANDLE sig_pipe_handle = NULL;
153 static gboolean signal_pipe_check_running(void);
157 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
158 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
161 /** Stop a low-level capture (stops the capture child). */
162 static void capture_loop_stop(void);
163 /** Close a pipe, or socket if \a from_socket is TRUE */
164 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
168 * Enable kernel BPF JIT compiler if available.
169 * If any calls fail, just drive on - the JIT compiler might not be
170 * enabled, but filtering will still work, and it's not clear what
171 * we could do if the calls fail; should we just report the error
172 * and not continue to capture, should we report it as a warning, or
176 enable_kernel_bpf_jit_compiler(void)
180 static const char file[] = "/proc/sys/net/core/bpf_jit_enable";
182 fd = ws_open(file, O_WRONLY);
186 written = ws_write(fd, "1", strlen("1"));
192 #if !defined (__linux__)
193 #ifndef HAVE_PCAP_BREAKLOOP
195 * We don't have pcap_breakloop(), which is the only way to ensure that
196 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
197 * won't, if the call to read the next packet or batch of packets is
198 * is interrupted by a signal on UN*X, just go back and try again to
201 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
202 * the signal handler, set a flag to stop capturing; however, without
203 * a guarantee of that sort, we can't guarantee that we'll stop capturing
204 * if the read will be retried and won't time out if no packets arrive.
206 * Therefore, on at least some platforms, we work around the lack of
207 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
208 * to wait for packets to arrive, so that we're probably going to be
209 * blocked in the select() when the signal arrives, and can just bail
210 * out of the loop at that point.
212 * However, we don't want to do that on BSD (because "select()" doesn't work
213 * correctly on BPF devices on at least some releases of some flavors of
214 * BSD), and we don't want to do it on Windows (because "select()" is
215 * something for sockets, not for arbitrary handles). (Note that "Windows"
216 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
217 * using WinPcap, not a UNIX libpcap.)
219 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
220 * on BSD times out even if no packets have arrived, so we'll eventually
221 * exit pcap_dispatch() with an indication that no packets have arrived,
222 * and will break out of the capture loop at that point.
224 * On Windows, we can't send a SIGINT to stop capturing, so none of this
225 * applies in any case.
227 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
228 * want to include it if it's not present on this platform, however.
230 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
231 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
233 # define MUST_DO_SELECT
234 # endif /* avoid select */
235 #endif /* HAVE_PCAP_BREAKLOOP */
237 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
238 * in pcap_dispatch(); on the other hand, select() works just fine there.
239 * Hence we use a select for that come what may.
241 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
242 * internally, and, with TPACKET_V3, once that's supported, it'll
243 * support timeouts, at least as I understand the way the code works.
245 #define MUST_DO_SELECT
248 /** init the capture filter */
251 INITFILTER_BAD_FILTER,
252 INITFILTER_OTHER_ERROR
253 } initfilter_status_t;
256 STATE_EXPECT_REC_HDR,
269 typedef struct _pcap_options {
274 #ifdef MUST_DO_SELECT
275 int pcap_fd; /**< pcap file descriptor */
282 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
283 /**< capture pipe (unix only "input file") */
284 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
285 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
286 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
287 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
289 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
291 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
292 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
293 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
295 char * cap_pipe_buf; /**< Pointer to the data buffer we read into */
296 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
297 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
299 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
300 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
302 cap_pipe_state_t cap_pipe_state;
303 cap_pipe_err_t cap_pipe_err;
306 GMutex *cap_pipe_read_mtx;
307 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
311 typedef struct _loop_data {
313 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
314 int err; /**< if non-zero, error seen while capturing */
315 gint packet_count; /**< Number of packets we have already captured */
316 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
317 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
319 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
325 guint64 bytes_written;
326 guint32 autostop_files;
329 typedef struct _pcap_queue_element {
330 pcap_options *pcap_opts;
331 struct pcap_pkthdr phdr;
333 } pcap_queue_element;
336 * Standard secondary message for unexpected errors.
338 static const char please_report[] =
339 "Please report this to the Wireshark developers.\n"
340 "https://bugs.wireshark.org/\n"
341 "(This is not a crash; please do not report it as such.)";
344 * This needs to be static, so that the SIGINT handler can clear the "go"
347 static loop_data global_ld;
350 * Timeout, in milliseconds, for reads from the stream of captured packets
351 * from a capture device.
353 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
354 * 64-bit applications, with sub-second timeouts not to work. The bug is
355 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
357 #if defined(__APPLE__) && defined(__LP64__)
358 static gboolean need_timeout_workaround;
360 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
362 #define CAP_READ_TIMEOUT 250
366 * Timeout, in microseconds, for reads from the stream of captured packets
367 * from a pipe. Pipes don't have the same problem that BPF devices do
368 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
369 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
370 * of the offending versions of Snow Leopard.
372 * On Windows this value is converted to milliseconds and passed to
373 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
374 * will return immediately.
377 #define PIPE_READ_TIMEOUT 100000
379 #define PIPE_READ_TIMEOUT 250000
382 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
385 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
386 const char *message, gpointer user_data _U_);
388 /* capture related options */
389 static capture_options global_capture_opts;
390 static gboolean quiet = FALSE;
391 static gboolean use_threads = FALSE;
392 static guint64 start_time;
394 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
396 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
398 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
399 int err, gboolean is_close);
401 static void WS_NORETURN exit_main(int err);
403 static void report_new_capture_file(const char *filename);
404 static void report_packet_count(unsigned int packet_count);
405 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
406 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
407 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
409 #define MSG_MAX_LENGTH 4096
411 /* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
413 create_timestamp(void) {
423 * Current time, represented as 100-nanosecond intervals since
424 * January 1, 1601, 00:00:00 UTC.
426 * I think DWORD might be signed, so cast both parts of "now"
427 * to guint32 so that the sign bit doesn't get treated specially.
429 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
430 * might want to use instead.
432 GetSystemTimeAsFileTime(&now);
433 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
434 (guint32)now.dwLowDateTime;
437 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
443 * Subtract difference, in microseconds, between January 1, 1601
444 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
446 timestamp -= G_GUINT64_CONSTANT(11644473600000000);
449 * Current time, represented as seconds and microseconds since
450 * January 1, 1970, 00:00:00 UTC.
452 gettimeofday(&now, NULL);
455 * Convert to delta in microseconds.
457 timestamp = (guint64)(now.tv_sec) * 1000000 +
458 (guint64)(now.tv_usec);
464 print_usage(FILE *output)
466 fprintf(output, "\nUsage: dumpcap [options] ...\n");
467 fprintf(output, "\n");
468 fprintf(output, "Capture interface:\n");
469 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
470 " or for remote capturing, use one of these formats:\n"
471 " rpcap://<host>/<interface>\n"
472 " TCP@<host>:<port>\n");
473 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
474 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
475 fprintf(output, " -p don't capture in promiscuous mode\n");
476 #ifdef HAVE_PCAP_CREATE
477 fprintf(output, " -I capture in monitor mode, if available\n");
479 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
480 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
482 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
483 fprintf(output, " -D print list of interfaces and exit\n");
484 fprintf(output, " -L print list of link-layer types of iface and exit\n");
485 #ifdef HAVE_BPF_IMAGE
486 fprintf(output, " -d print generated BPF code for capture filter\n");
488 fprintf(output, " -k set channel on wifi interface:\n"
489 " <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
490 fprintf(output, " -S print statistics for each interface once per second\n");
491 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
492 fprintf(output, "\n");
493 #ifdef HAVE_PCAP_REMOTE
494 fprintf(output, "RPCAP options:\n");
495 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
496 fprintf(output, " -u use UDP for RPCAP data transfer\n");
497 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
498 #ifdef HAVE_PCAP_SETSAMPLING
499 fprintf(output, " -m <sampling type> use packet sampling\n");
500 fprintf(output, " count:NUM - capture one packet of every NUM\n");
501 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
504 fprintf(output, "Stop conditions:\n");
505 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
506 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
507 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
508 fprintf(output, " files:NUM - stop after NUM files\n");
509 /*fprintf(output, "\n");*/
510 fprintf(output, "Output (files):\n");
511 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
512 fprintf(output, " -g enable group read access on the output file(s)\n");
513 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
514 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
515 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
516 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
517 fprintf(output, " -P use libpcap format instead of pcapng\n");
518 fprintf(output, " --capture-comment <comment>\n");
519 fprintf(output, " add a capture comment to the output file\n");
520 fprintf(output, " (only for pcapng)\n");
521 fprintf(output, "\n");
522 fprintf(output, "Miscellaneous:\n");
523 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
524 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
525 fprintf(output, " within dumpcap\n");
526 fprintf(output, " -t use a separate thread per interface\n");
527 fprintf(output, " -q don't report packet capture counts\n");
528 fprintf(output, " -v print version information and exit\n");
529 fprintf(output, " -h display this help and exit\n");
530 fprintf(output, "\n");
532 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
533 fprintf(output, "You might want to reset it\n");
534 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
535 fprintf(output, "\n");
537 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
538 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
539 fprintf(output, "\n");
540 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
544 * Report an error in command-line arguments.
545 * If we're a capture child, send a message back to the parent, otherwise
549 dumpcap_cmdarg_err(const char *fmt, va_list ap)
553 /* Generate a 'special format' message back to parent */
554 msg = g_strdup_vprintf(fmt, ap);
555 sync_pipe_errmsg_to_parent(2, msg, "");
558 fprintf(stderr, "dumpcap: ");
559 vfprintf(stderr, fmt, ap);
560 fprintf(stderr, "\n");
565 * Report additional information for an error in command-line arguments.
566 * If we're a capture child, send a message back to the parent, otherwise
570 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
574 msg = g_strdup_vprintf(fmt, ap);
575 sync_pipe_errmsg_to_parent(2, msg, "");
578 vfprintf(stderr, fmt, ap);
579 fprintf(stderr, "\n");
585 #if 0 /* Set to enable capability debugging */
586 /* see 'man cap_to_text()' for explanation of output */
587 /* '=' means 'all= ' ie: no capabilities */
588 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
590 print_caps(const char *pfx) {
591 cap_t caps = cap_get_proc();
592 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
593 "%s: EUID: %d Capabilities: %s", pfx,
594 geteuid(), cap_to_text(caps, NULL));
597 print_caps(const char *pfx _U_) {
602 relinquish_all_capabilities(void)
604 /* Drop any and all capabilities this process may have. */
605 /* Allowed whether or not process has any privileges. */
606 cap_t caps = cap_init(); /* all capabilities initialized to off */
607 print_caps("Pre-clear");
608 if (cap_set_proc(caps)) {
609 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
611 print_caps("Post-clear");
617 get_capture_device_open_failure_messages(const char *open_err_str,
619 char *errmsg, size_t errmsg_len,
620 char *secondary_errmsg,
621 size_t secondary_errmsg_len)
624 const char *libpcap_warn;
625 static const char ppamsg[] = "can't find PPA for ";
628 g_snprintf(errmsg, (gulong) errmsg_len,
629 "The capture session could not be initiated on interface '%s' (%s).",
630 iface, open_err_str);
633 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
635 "In order to capture packets, WinPcap must be installed; see\n"
637 " https://www.winpcap.org/\n"
639 "for a downloadable version of WinPcap and for instructions on how to install\n"
642 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
644 "Please check that \"%s\" is the proper interface.\n"
647 "Help can be found on the following pages:\n"
649 " https://wiki.wireshark.org/WinPcap\n"
650 " https://wiki.wireshark.org/CaptureSetup\n",
654 /* If we got a "can't find PPA for X" message, warn the user (who
655 is running dumpcap on HP-UX) that they don't have a version of
656 libpcap that properly handles HP-UX (libpcap 0.6.x and later
657 versions, which properly handle HP-UX, say "can't find /dev/dlpi
658 PPA for X" rather than "can't find PPA for X"). */
659 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
662 "You are running (T)Wireshark with a version of the libpcap library\n"
663 "that doesn't handle HP-UX network devices well; this means that\n"
664 "(T)Wireshark may not be able to capture packets.\n"
666 "To fix this, you should install libpcap 0.6.2, or a later version\n"
667 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
668 "packaged binary form from the Software Porting And Archive Centre\n"
669 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
670 "at the URL lists a number of mirror sites.";
674 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
675 "Please check to make sure you have sufficient permissions, and that you have "
676 "the proper interface or pipe specified.%s", libpcap_warn);
681 compile_capture_filter(const char *iface, pcap_t *pcap_h,
682 struct bpf_program *fcode, const char *cfilter)
684 bpf_u_int32 netnum, netmask;
685 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
687 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
689 * Well, we can't get the netmask for this interface; it's used
690 * only for filters that check for broadcast IP addresses, so
691 * we just punt and use 0. It might be nice to warn the user,
692 * but that's a pain in a GUI application, as it'd involve popping
693 * up a message box, and it's not clear how often this would make
694 * a difference (only filters that check for IP broadcast addresses
698 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
703 * Sigh. Older versions of libpcap don't properly declare the
704 * third argument to pcap_compile() as a const pointer. Cast
708 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
714 #ifdef HAVE_BPF_IMAGE
716 show_filter_code(capture_options *capture_opts)
718 interface_options interface_opts;
720 gchar open_err_str[PCAP_ERRBUF_SIZE];
721 char errmsg[MSG_MAX_LENGTH+1];
722 char secondary_errmsg[MSG_MAX_LENGTH+1];
723 struct bpf_program fcode;
724 struct bpf_insn *insn;
728 for (j = 0; j < capture_opts->ifaces->len; j++) {
729 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
730 pcap_h = open_capture_device(capture_opts, &interface_opts,
731 CAP_READ_TIMEOUT, &open_err_str);
732 if (pcap_h == NULL) {
733 /* Open failed; get messages */
734 get_capture_device_open_failure_messages(open_err_str,
736 errmsg, sizeof errmsg,
738 sizeof secondary_errmsg);
739 /* And report them */
740 report_capture_error(errmsg, secondary_errmsg);
744 /* Set the link-layer type. */
745 if (!set_pcap_datalink(pcap_h, interface_opts.linktype, interface_opts.name,
746 errmsg, sizeof errmsg,
747 secondary_errmsg, sizeof secondary_errmsg)) {
749 report_capture_error(errmsg, secondary_errmsg);
753 /* OK, try to compile the capture filter. */
754 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
755 interface_opts.cfilter)) {
757 report_cfilter_error(capture_opts, j, errmsg);
762 /* Now print the filter code. */
763 insn = fcode.bf_insns;
765 for (i = 0; i < fcode.bf_len; insn++, i++)
766 printf("%s\n", bpf_image(insn, i));
768 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
769 /* to remove any suid privileges. */
770 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
771 /* (euid/egid have already previously been set to ruid/rgid. */
772 /* (See comment in main() for details) */
774 relinquish_special_privs_perm();
776 relinquish_all_capabilities();
779 /* Let our parent know we succeeded. */
780 pipe_write_block(2, SP_SUCCESS, NULL);
787 * capture_interface_list() is expected to do the right thing to get
788 * a list of interfaces.
790 * In most of the programs in the Wireshark suite, "the right thing"
791 * is to run dumpcap and ask it for the list, because dumpcap may
792 * be the only program in the suite with enough privileges to get
795 * In dumpcap itself, however, we obviously can't run dumpcap to
796 * ask for the list. Therefore, our capture_interface_list() should
797 * just call get_interface_list().
800 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
802 return get_interface_list(err, err_str);
805 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
807 * Output a machine readable list of the interfaces
808 * This list is retrieved by the sync_interface_list_open() function
809 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
812 print_machine_readable_interfaces(GList *if_list)
819 char addr_str[ADDRSTRLEN];
822 /* Let our parent know we succeeded. */
823 pipe_write_block(2, SP_SUCCESS, NULL);
826 i = 1; /* Interface id number */
827 for (if_entry = g_list_first(if_list); if_entry != NULL;
828 if_entry = g_list_next(if_entry)) {
829 if_info = (if_info_t *)if_entry->data;
830 printf("%d. %s\t", i++, if_info->name);
833 * Print the contents of the if_entry struct in a parseable format.
834 * Each if_entry element is tab-separated. Addresses are comma-
837 /* XXX - Make sure our description doesn't contain a tab */
838 if (if_info->vendor_description != NULL)
839 printf("%s\t", if_info->vendor_description);
843 /* XXX - Make sure our friendly name doesn't contain a tab */
844 if (if_info->friendly_name != NULL)
845 printf("%s\t", if_info->friendly_name);
849 printf("%i\t", if_info->type);
851 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
852 addr = g_slist_next(addr)) {
853 if (addr != g_slist_nth(if_info->addrs, 0))
856 if_addr = (if_addr_t *)addr->data;
857 switch(if_addr->ifat_type) {
859 if (ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str,
861 printf("%s", addr_str);
863 printf("<unknown IPv4>");
867 if (ws_inet_ntop6(&if_addr->addr.ip6_addr,
868 addr_str, ADDRSTRLEN)) {
869 printf("%s", addr_str);
871 printf("<unknown IPv6>");
875 printf("<type unknown %i>", if_addr->ifat_type);
879 if (if_info->loopback)
880 printf("\tloopback");
884 printf("\t%s", if_info->extcap);
891 * If you change the machine-readable output format of this function,
892 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
895 print_machine_readable_if_capabilities(if_capabilities_t *caps)
898 data_link_info_t *data_link_info;
899 const gchar *desc_str;
902 /* Let our parent know we succeeded. */
903 pipe_write_block(2, SP_SUCCESS, NULL);
906 if (caps->can_set_rfmon)
910 for (lt_entry = caps->data_link_types; lt_entry != NULL;
911 lt_entry = g_list_next(lt_entry)) {
912 data_link_info = (data_link_info_t *)lt_entry->data;
913 if (data_link_info->description != NULL)
914 desc_str = data_link_info->description;
916 desc_str = "(not supported)";
917 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
927 /* Print the number of packets captured for each interface until we're killed. */
929 print_statistics_loop(gboolean machine_readable)
931 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
937 char errbuf[PCAP_ERRBUF_SIZE];
940 if_list = get_interface_list(&err, &err_str);
941 if (if_list == NULL) {
943 cmdarg_err("There are no interfaces on which a capture can be done");
945 cmdarg_err("%s", err_str);
951 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
952 if_info = (if_info_t *)if_entry->data;
955 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
956 * connections. We avoid collecting stats on them.
958 if (!strncmp(if_info->name, "nf", 2)) {
959 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
965 #ifdef HAVE_PCAP_OPEN
966 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
968 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
972 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
973 if_stat->name = g_strdup(if_info->name);
975 stat_list = g_list_append(stat_list, if_stat);
980 cmdarg_err("There are no interfaces on which a capture can be done");
985 /* Let our parent know we succeeded. */
986 pipe_write_block(2, SP_SUCCESS, NULL);
989 if (!machine_readable) {
990 printf("%-15s %10s %10s\n", "Interface", "Received",
995 while (global_ld.go) {
996 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
997 if_stat = (if_stat_t *)stat_entry->data;
998 pcap_stats(if_stat->pch, &ps);
1000 if (!machine_readable) {
1001 printf("%-15s %10u %10u\n", if_stat->name,
1002 ps.ps_recv, ps.ps_drop);
1004 printf("%s\t%u\t%u\n", if_stat->name,
1005 ps.ps_recv, ps.ps_drop);
1010 /* If we have a dummy signal pipe check it */
1011 if (!signal_pipe_check_running()) {
1012 global_ld.go = FALSE;
1020 /* XXX - Not reached. Should we look for 'q' in stdin? */
1021 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1022 if_stat = (if_stat_t *)stat_entry->data;
1023 pcap_close(if_stat->pch);
1024 g_free(if_stat->name);
1027 g_list_free(stat_list);
1028 free_interface_list(if_list);
1036 capture_cleanup_handler(DWORD dwCtrlType)
1038 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1039 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1040 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1041 like SIGTERM at least when the machine's shutting down.
1043 For now, if we're running as a command rather than a capture child,
1044 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1045 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1046 in that way on UN*X.
1048 If we're not running as a capture child, we might be running as
1049 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1050 user logs out. (XXX - can we explicitly check whether we're
1051 running as a service?) */
1053 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1054 "Console: Control signal");
1055 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1056 "Console: Control signal, CtrlType: %u", dwCtrlType);
1058 /* Keep capture running if we're a service and a user logs off */
1059 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1060 capture_loop_stop();
1068 capture_cleanup_handler(int signum _U_)
1070 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1071 SIGTERM. We assume that if the user wanted it to keep running
1072 after they logged out, they'd have nohupped it. */
1074 /* Note: don't call g_log() in the signal handler: if we happened to be in
1075 * g_log() in process context when the signal came in, g_log will detect
1076 * the "recursion" and abort.
1079 capture_loop_stop();
1085 report_capture_count(gboolean reportit)
1087 /* Don't print this if we're a capture child. */
1088 if (!capture_child && reportit) {
1089 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packet_count);
1090 /* stderr could be line buffered */
1098 report_counts_for_siginfo(void)
1100 report_capture_count(quiet);
1101 infoprint = FALSE; /* we just reported it */
1105 report_counts_siginfo(int signum _U_)
1107 int sav_errno = errno;
1109 /* If we've been told to delay printing, just set a flag asking
1110 that we print counts (if we're supposed to), otherwise print
1111 the count of packets captured (if we're supposed to). */
1115 report_counts_for_siginfo();
1118 #endif /* SIGINFO */
1121 exit_main(int status)
1124 /* Shutdown windows sockets */
1127 /* can be helpful for debugging */
1128 #ifdef DEBUG_DUMPCAP
1129 printf("Press any key\n");
1135 capture_opts_cleanup(&global_capture_opts);
1141 * If we were linked with libcap (not related to libpcap), make sure we have
1142 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1143 * (See comment in main() for details)
1146 relinquish_privs_except_capture(void)
1148 /* If 'started_with_special_privs' (ie: suid) then enable for
1149 * ourself the NET_ADMIN and NET_RAW capabilities and then
1150 * drop our suid privileges.
1152 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1153 * stuff we don't need (and shouldn't have).
1154 * CAP_NET_RAW: Packet capture (raw sockets).
1157 if (started_with_special_privs()) {
1158 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1159 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1161 cap_t caps = cap_init(); /* all capabilities initialized to off */
1163 print_caps("Pre drop, pre set");
1165 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1166 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1169 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1170 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1172 if (cap_set_proc(caps)) {
1173 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1175 print_caps("Pre drop, post set");
1177 relinquish_special_privs_perm();
1179 print_caps("Post drop, pre set");
1180 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1181 if (cap_set_proc(caps)) {
1182 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1184 print_caps("Post drop, post set");
1190 #endif /* HAVE_LIBCAP */
1192 /* Take care of byte order in the libpcap headers read from pipes.
1193 * (function taken from wiretap/libpcap.c) */
1195 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1198 /* Byte-swap the record header fields. */
1199 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1200 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1201 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1202 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1205 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1206 swapped, in order to match the BPF header layout.
1208 Unfortunately, some files were, according to a comment in the "libpcap"
1209 source, written with version 2.3 in their headers but without the
1210 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1211 would make no sense - we assume that we need to swap them. */
1212 if (hdr->version_major == 2 &&
1213 (hdr->version_minor < 3 ||
1214 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1217 temp = rechdr->orig_len;
1218 rechdr->orig_len = rechdr->incl_len;
1219 rechdr->incl_len = temp;
1223 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1227 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1231 return recv(pipe_fd, buf, (int)sz, 0);
1236 return ws_read(pipe_fd, buf, sz);
1242 * Thread function that reads from a pipe and pushes the data
1243 * to the main application thread.
1246 * XXX Right now we use async queues for basic signaling. The main thread
1247 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1248 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1249 * Iff the read is successful cap_pipe_read pushes an item onto
1250 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1251 * the queues themselves (yet).
1253 * We might want to move some of the cap_pipe_dispatch logic here so that
1254 * we can let cap_thread_read run independently, queuing up multiple reads
1255 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1257 static void *cap_thread_read(void *arg)
1259 pcap_options *pcap_opts;
1262 DWORD b, last_err, bytes_read;
1268 pcap_opts = (pcap_options *)arg;
1269 while (pcap_opts->cap_pipe_err == PIPOK) {
1270 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1271 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1273 while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1274 if ((pcap_opts->from_cap_socket)
1280 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1281 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1284 pcap_opts->cap_pipe_err = PIPEOF;
1288 pcap_opts->cap_pipe_err = PIPERR;
1299 /* If we try to use read() on a named pipe on Windows with partial
1300 * data it appears to return EOF.
1302 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1303 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1308 last_err = GetLastError();
1309 if (last_err == ERROR_MORE_DATA) {
1311 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1312 pcap_opts->cap_pipe_err = PIPEOF;
1316 pcap_opts->cap_pipe_err = PIPERR;
1319 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1320 pcap_opts->cap_pipe_err = PIPEOF;
1327 pcap_opts->cap_pipe_bytes_read = bytes_read;
1328 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1329 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1331 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1337 /* Provide select() functionality for a single file descriptor
1338 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1340 * Returns the same values as select.
1343 cap_pipe_select(int pipe_fd)
1346 struct timeval timeout;
1349 FD_SET(pipe_fd, &rfds);
1351 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1352 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1354 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1357 #define DEF_TCP_PORT 19000
1360 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1362 char *sockname = pipename + 4;
1363 struct sockaddr_in sa;
1370 memset(&sa, 0, sizeof(sa));
1372 p = strchr(sockname, ':');
1374 len = strlen(sockname);
1375 port = DEF_TCP_PORT;
1379 port = strtoul(p + 1, &p, 10);
1380 if (*p || port > 65535) {
1389 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1391 if (!ws_inet_pton4(buf, (guint32 *)&sa.sin_addr)) {
1395 sa.sin_family = AF_INET;
1396 sa.sin_port = g_htons((u_short)port);
1398 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1399 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1401 LPTSTR errorText = NULL;
1404 lastError = WSAGetLastError();
1405 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1406 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1407 FORMAT_MESSAGE_IGNORE_INSERTS,
1408 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1409 (LPTSTR)&errorText, 0, NULL);
1411 g_snprintf(errmsg, errmsgl,
1412 "The capture session could not be initiated due to the socket error: \n"
1414 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1416 LocalFree(errorText);
1418 " %d: %s", errno, g_strerror(errno));
1420 pcap_opts->cap_pipe_err = PIPERR;
1423 cap_pipe_close(fd, TRUE);
1427 pcap_opts->from_cap_socket = TRUE;
1431 g_snprintf(errmsg, errmsgl,
1432 "The capture session could not be initiated because\n"
1433 "\"%s\" is not a valid socket specification", pipename);
1434 pcap_opts->cap_pipe_err = PIPERR;
1438 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1442 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1446 closesocket(pipe_fd);
1453 /* Mimic pcap_open_live() for pipe captures
1455 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1456 * open it, and read the header.
1458 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1459 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1461 cap_pipe_open_live(char *pipename,
1462 pcap_options *pcap_opts,
1463 struct pcap_hdr *hdr,
1464 char *errmsg, int errmsgl)
1467 ws_statb64 pipe_stat;
1468 struct sockaddr_un sa;
1473 char* extcap_pipe_name;
1477 gboolean extcap_pipe = FALSE;
1478 interface_options interface_opts;
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) {
1508 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
1513 if ( g_strrstr(interface_opts.name, EXTCAP_PIPE_PREFIX) != NULL )
1517 if (ws_stat64(pipename, &pipe_stat) < 0) {
1518 if (errno == ENOENT || errno == ENOTDIR)
1519 pcap_opts->cap_pipe_err = PIPNEXIST;
1521 g_snprintf(errmsg, errmsgl,
1522 "The capture session could not be initiated "
1523 "due to error getting information on pipe/socket: %s.", g_strerror(errno));
1524 pcap_opts->cap_pipe_err = PIPERR;
1528 if (S_ISFIFO(pipe_stat.st_mode)) {
1529 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1531 g_snprintf(errmsg, errmsgl,
1532 "The capture session could not be initiated "
1533 "due to error on pipe open: %s.", g_strerror(errno));
1534 pcap_opts->cap_pipe_err = PIPERR;
1537 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1538 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1540 g_snprintf(errmsg, errmsgl,
1541 "The capture session could not be initiated "
1542 "due to error on socket create: %s.", g_strerror(errno));
1543 pcap_opts->cap_pipe_err = PIPERR;
1546 sa.sun_family = AF_UNIX;
1548 * The Single UNIX Specification says:
1550 * The size of sun_path has intentionally been left undefined.
1551 * This is because different implementations use different sizes.
1552 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1553 * of 104. Since most implementations originate from BSD versions,
1554 * the size is typically in the range 92 to 108.
1556 * Applications should not assume a particular length for sun_path
1557 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1561 * The <sys/un.h> header shall define the sockaddr_un structure,
1562 * which shall include at least the following members:
1564 * sa_family_t sun_family Address family.
1565 * char sun_path[] Socket pathname.
1567 * so we assume that it's an array, with a specified size,
1568 * and that the size reflects the maximum path length.
1570 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1571 /* Path name too long */
1572 g_snprintf(errmsg, errmsgl,
1573 "The capture session coud not be initiated "
1574 "due to error on socket connect: Path name too long.");
1575 pcap_opts->cap_pipe_err = PIPERR;
1579 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1581 g_snprintf(errmsg, errmsgl,
1582 "The capture session coud not be initiated "
1583 "due to error on socket connect: %s.", g_strerror(errno));
1584 pcap_opts->cap_pipe_err = PIPERR;
1589 if (S_ISCHR(pipe_stat.st_mode)) {
1591 * Assume the user specified an interface on a system where
1592 * interfaces are in /dev. Pretend we haven't seen it.
1594 pcap_opts->cap_pipe_err = PIPNEXIST;
1596 g_snprintf(errmsg, errmsgl,
1597 "The capture session could not be initiated because\n"
1598 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1599 pcap_opts->cap_pipe_err = PIPERR;
1605 #define PIPE_STR "\\pipe\\"
1606 /* Under Windows, named pipes _must_ have the form
1607 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1609 pncopy = g_strdup(pipename);
1610 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1611 pos = strchr(pncopy + 3, '\\');
1612 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1619 g_snprintf(errmsg, errmsgl,
1620 "The capture session could not be initiated because\n"
1621 "\"%s\" is neither an interface nor a pipe.", pipename);
1622 pcap_opts->cap_pipe_err = PIPNEXIST;
1626 extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
1627 extcap_pipe = strstr(interface_opts.name, extcap_pipe_name) ? TRUE : FALSE;
1628 g_free(extcap_pipe_name);
1631 /* Wait for the pipe to appear */
1636 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1639 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1640 OPEN_EXISTING, 0, NULL);
1642 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
1645 if (GetLastError() != ERROR_PIPE_BUSY) {
1646 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1647 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1648 g_snprintf(errmsg, errmsgl,
1649 "The capture session on \"%s\" could not be started "
1650 "due to error on pipe open: %s (error %d).",
1651 pipename, utf_16to8(err_str), GetLastError());
1653 pcap_opts->cap_pipe_err = PIPERR;
1657 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1658 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1659 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1660 g_snprintf(errmsg, errmsgl,
1661 "The capture session on \"%s\" timed out during "
1662 "pipe open: %s (error %d).",
1663 pipename, utf_16to8(err_str), GetLastError());
1665 pcap_opts->cap_pipe_err = PIPERR;
1672 pcap_opts->from_cap_pipe = TRUE;
1675 if (pcap_opts->from_cap_socket)
1678 /* read the pcap header */
1680 while (bytes_read < sizeof magic) {
1682 g_snprintf(errmsg, errmsgl, "Invalid file descriptor.");
1686 sel_ret = cap_pipe_select(fd);
1688 g_snprintf(errmsg, errmsgl,
1689 "Unexpected error from select: %s.", g_strerror(errno));
1691 } else if (sel_ret > 0) {
1692 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1693 sizeof magic-bytes_read,
1694 pcap_opts->from_cap_socket);
1696 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1697 if (extcap_pipe && b <= 0)
1702 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1704 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1714 #if GLIB_CHECK_VERSION(2,31,0)
1715 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
1717 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
1720 pcap_opts->cap_pipe_buf = (char *) &magic;
1721 pcap_opts->cap_pipe_bytes_read = 0;
1722 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
1723 /* We don't have to worry about cap_pipe_read_mtx here */
1724 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1725 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
1726 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1727 if (pcap_opts->cap_pipe_bytes_read <= 0 && extcap_pipe)
1730 if (pcap_opts->cap_pipe_bytes_read <= 0) {
1731 if (pcap_opts->cap_pipe_bytes_read == 0)
1732 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1734 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1743 case PCAP_NSEC_MAGIC:
1744 /* Host that wrote it has our byte order, and was running
1745 a program using either standard or ss990417 libpcap. */
1746 pcap_opts->cap_pipe_byte_swapped = FALSE;
1747 pcap_opts->cap_pipe_modified = FALSE;
1748 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
1750 case PCAP_MODIFIED_MAGIC:
1751 /* Host that wrote it has our byte order, but was running
1752 a program using either ss990915 or ss991029 libpcap. */
1753 pcap_opts->cap_pipe_byte_swapped = FALSE;
1754 pcap_opts->cap_pipe_modified = TRUE;
1756 case PCAP_SWAPPED_MAGIC:
1757 case PCAP_SWAPPED_NSEC_MAGIC:
1758 /* Host that wrote it has a byte order opposite to ours,
1759 and was running a program using either standard or
1760 ss990417 libpcap. */
1761 pcap_opts->cap_pipe_byte_swapped = TRUE;
1762 pcap_opts->cap_pipe_modified = FALSE;
1763 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
1765 case PCAP_SWAPPED_MODIFIED_MAGIC:
1766 /* Host that wrote it out has a byte order opposite to
1767 ours, and was running a program using either ss990915
1768 or ss991029 libpcap. */
1769 pcap_opts->cap_pipe_byte_swapped = TRUE;
1770 pcap_opts->cap_pipe_modified = TRUE;
1772 case BLOCK_TYPE_SHB:
1773 /* This isn't pcap, it's pcapng. We don't yet support
1775 g_snprintf(errmsg, errmsgl, "Capturing from a pipe doesn't support pcapng format.");
1778 /* Not a pcap type we know about, or not pcap at all. */
1779 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format or not libpcap data.");
1784 if (pcap_opts->from_cap_socket)
1787 /* Read the rest of the header */
1789 while (bytes_read < sizeof(struct pcap_hdr)) {
1790 sel_ret = cap_pipe_select(fd);
1792 g_snprintf(errmsg, errmsgl,
1793 "Unexpected error from select: %s.", g_strerror(errno));
1795 } else if (sel_ret > 0) {
1796 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
1797 sizeof(struct pcap_hdr) - bytes_read,
1798 pcap_opts->from_cap_socket);
1801 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1803 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s.",
1813 pcap_opts->cap_pipe_buf = (char *) hdr;
1814 pcap_opts->cap_pipe_bytes_read = 0;
1815 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1816 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1817 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
1818 if (pcap_opts->cap_pipe_bytes_read <= 0) {
1819 if (pcap_opts->cap_pipe_bytes_read == 0)
1820 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1822 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s.",
1829 if (pcap_opts->cap_pipe_byte_swapped) {
1830 /* Byte-swap the header fields about which we care. */
1831 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
1832 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
1833 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
1834 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
1836 pcap_opts->linktype = hdr->network;
1838 if (hdr->version_major < 2) {
1839 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1843 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
1844 pcap_opts->cap_pipe_err = PIPOK;
1845 pcap_opts->cap_pipe_fd = fd;
1849 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1850 pcap_opts->cap_pipe_err = PIPERR;
1851 cap_pipe_close(fd, pcap_opts->from_cap_socket);
1852 pcap_opts->cap_pipe_fd = -1;
1854 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1859 /* We read one record from the pipe, take care of byte order in the record
1860 * header, write the record to the capture file, and update capture statistics. */
1862 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
1864 struct pcap_pkthdr phdr;
1865 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1868 #if !GLIB_CHECK_VERSION(2,31,18)
1876 #ifdef LOG_CAPTURE_VERBOSE
1877 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1880 switch (pcap_opts->cap_pipe_state) {
1882 case STATE_EXPECT_REC_HDR:
1884 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
1887 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
1888 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
1889 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1890 pcap_opts->cap_pipe_bytes_read = 0;
1893 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
1894 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1895 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1900 case STATE_READ_REC_HDR:
1902 if (pcap_opts->from_cap_socket)
1905 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
1906 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
1909 result = PD_PIPE_EOF;
1911 result = PD_PIPE_ERR;
1914 pcap_opts->cap_pipe_bytes_read += b;
1918 #if GLIB_CHECK_VERSION(2,31,18)
1919 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
1921 g_get_current_time(&wait_time);
1922 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
1923 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
1925 if (pcap_opts->cap_pipe_err == PIPEOF) {
1926 result = PD_PIPE_EOF;
1928 } else if (pcap_opts->cap_pipe_err == PIPERR) {
1929 result = PD_PIPE_ERR;
1937 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
1939 result = PD_REC_HDR_READ;
1942 case STATE_EXPECT_DATA:
1944 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
1947 pcap_opts->cap_pipe_state = STATE_READ_DATA;
1948 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
1949 pcap_opts->cap_pipe_bytes_read = 0;
1952 pcap_opts->cap_pipe_buf = (char *) data;
1953 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1954 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1959 case STATE_READ_DATA:
1961 if (pcap_opts->from_cap_socket)
1964 b = cap_pipe_read(pcap_opts->cap_pipe_fd,
1965 data+pcap_opts->cap_pipe_bytes_read,
1966 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
1967 pcap_opts->from_cap_socket);
1970 result = PD_PIPE_EOF;
1972 result = PD_PIPE_ERR;
1975 pcap_opts->cap_pipe_bytes_read += b;
1980 #if GLIB_CHECK_VERSION(2,31,18)
1981 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
1983 g_get_current_time(&wait_time);
1984 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
1985 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
1986 #endif /* GLIB_CHECK_VERSION(2,31,18) */
1987 if (pcap_opts->cap_pipe_err == PIPEOF) {
1988 result = PD_PIPE_EOF;
1990 } else if (pcap_opts->cap_pipe_err == PIPERR) {
1991 result = PD_PIPE_ERR;
1999 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2001 result = PD_DATA_READ;
2005 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2008 } /* switch (pcap_opts->cap_pipe_state) */
2011 * We've now read as much data as we were expecting, so process it.
2015 case PD_REC_HDR_READ:
2016 /* We've read the header. Take care of byte order. */
2017 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2018 &pcap_opts->cap_pipe_rechdr.hdr);
2019 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2020 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2021 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2025 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2026 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2029 /* no data to read? fall through */
2032 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2033 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2034 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2035 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2036 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2039 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2041 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2043 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2047 pcap_opts->cap_pipe_err = PIPEOF;
2052 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2053 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2054 g_snprintf(errmsg, errmsgl,
2055 "Error reading from pipe: %s (error %d)",
2056 utf_16to8(err_str), GetLastError());
2059 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2067 pcap_opts->cap_pipe_err = PIPERR;
2068 /* Return here rather than inside the switch to prevent GCC warning */
2073 /** Open the capture input file (pcap or capture pipe).
2074 * Returns TRUE if it succeeds, FALSE otherwise. */
2076 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2077 char *errmsg, size_t errmsg_len,
2078 char *secondary_errmsg, size_t secondary_errmsg_len)
2080 gchar open_err_str[PCAP_ERRBUF_SIZE];
2081 gchar *sync_msg_str;
2082 interface_options interface_opts;
2083 pcap_options *pcap_opts;
2087 WORD wVersionRequested;
2091 /* XXX - opening Winsock on tshark? */
2093 /* Initialize Windows Socket if we are in a Win32 OS
2094 This needs to be done before querying the interface for network/netmask */
2096 /* XXX - do we really require 1.1 or earlier?
2097 Are there any versions that support only 2.0 or higher? */
2098 wVersionRequested = MAKEWORD(1, 1);
2099 err = WSAStartup(wVersionRequested, &wsaData);
2103 case WSASYSNOTREADY:
2104 g_snprintf(errmsg, (gulong) errmsg_len,
2105 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2108 case WSAVERNOTSUPPORTED:
2109 g_snprintf(errmsg, (gulong) errmsg_len,
2110 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2111 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2114 case WSAEINPROGRESS:
2115 g_snprintf(errmsg, (gulong) errmsg_len,
2116 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2120 g_snprintf(errmsg, (gulong) errmsg_len,
2121 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2125 g_snprintf(errmsg, (gulong) errmsg_len,
2126 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2130 g_snprintf(errmsg, (gulong) errmsg_len,
2131 "Couldn't initialize Windows Sockets: error %d", err);
2134 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2138 if ((use_threads == FALSE) &&
2139 (capture_opts->ifaces->len > 1)) {
2140 g_snprintf(errmsg, (gulong) errmsg_len,
2141 "Using threads is required for capturing on multiple interfaces.");
2145 for (i = 0; i < capture_opts->ifaces->len; i++) {
2146 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2147 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2148 if (pcap_opts == NULL) {
2149 g_snprintf(errmsg, (gulong) errmsg_len,
2150 "Could not allocate memory.");
2153 pcap_opts->received = 0;
2154 pcap_opts->dropped = 0;
2155 pcap_opts->flushed = 0;
2156 pcap_opts->pcap_h = NULL;
2157 #ifdef MUST_DO_SELECT
2158 pcap_opts->pcap_fd = -1;
2160 pcap_opts->pcap_err = FALSE;
2161 pcap_opts->interface_id = i;
2162 pcap_opts->tid = NULL;
2163 pcap_opts->snaplen = 0;
2164 pcap_opts->linktype = -1;
2165 pcap_opts->ts_nsec = FALSE;
2166 pcap_opts->from_cap_pipe = FALSE;
2167 pcap_opts->from_cap_socket = FALSE;
2168 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2169 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2171 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2173 pcap_opts->cap_pipe_fd = -1;
2174 pcap_opts->cap_pipe_modified = FALSE;
2175 pcap_opts->cap_pipe_byte_swapped = FALSE;
2177 pcap_opts->cap_pipe_buf = NULL;
2179 pcap_opts->cap_pipe_bytes_to_read = 0;
2180 pcap_opts->cap_pipe_bytes_read = 0;
2181 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2182 pcap_opts->cap_pipe_err = PIPOK;
2184 #if GLIB_CHECK_VERSION(2,31,0)
2185 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2186 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2188 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2190 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2191 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2193 g_array_append_val(ld->pcaps, pcap_opts);
2195 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2196 pcap_opts->pcap_h = open_capture_device(capture_opts, &interface_opts,
2197 CAP_READ_TIMEOUT, &open_err_str);
2199 if (pcap_opts->pcap_h != NULL) {
2200 /* we've opened "iface" as a network device */
2202 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2203 /* Find out if we're getting nanosecond-precision time stamps */
2204 pcap_opts->ts_nsec = have_high_resolution_timestamp(pcap_opts->pcap_h);
2207 #if defined(HAVE_PCAP_SETSAMPLING)
2208 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2209 struct pcap_samp *samp;
2211 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2212 switch (interface_opts.sampling_method) {
2213 case CAPTURE_SAMP_BY_COUNT:
2214 samp->method = PCAP_SAMP_1_EVERY_N;
2217 case CAPTURE_SAMP_BY_TIMER:
2218 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2222 sync_msg_str = g_strdup_printf(
2223 "Unknown sampling method %d specified,\n"
2224 "continue without packet sampling",
2225 interface_opts.sampling_method);
2226 report_capture_error("Couldn't set the capture "
2227 "sampling", sync_msg_str);
2228 g_free(sync_msg_str);
2230 samp->value = interface_opts.sampling_param;
2232 report_capture_error("Couldn't set the capture sampling",
2233 "Cannot get packet sampling data structure");
2238 /* setting the data link type only works on real interfaces */
2239 if (!set_pcap_datalink(pcap_opts->pcap_h, interface_opts.linktype,
2240 interface_opts.name,
2242 secondary_errmsg, secondary_errmsg_len)) {
2245 pcap_opts->linktype = get_pcap_datalink(pcap_opts->pcap_h, interface_opts.name);
2247 /* We couldn't open "iface" as a network device. */
2248 /* Try to open it as a pipe */
2249 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2252 if (pcap_opts->cap_pipe_fd == -1) {
2254 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2256 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2258 * We tried opening as an interface, and that failed,
2259 * so we tried to open it as a pipe, but the pipe
2260 * doesn't exist. Report the error message for
2263 get_capture_device_open_failure_messages(open_err_str,
2264 interface_opts.name,
2268 secondary_errmsg_len);
2271 * Else pipe (or file) does exist and cap_pipe_open_live() has
2276 /* cap_pipe_open_live() succeeded; don't want
2277 error message from pcap_open_live() */
2278 open_err_str[0] = '\0';
2282 /* XXX - will this work for tshark? */
2283 #ifdef MUST_DO_SELECT
2284 if (!pcap_opts->from_cap_pipe) {
2285 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2286 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2288 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2293 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2294 returned a warning; print it, but keep capturing. */
2295 if (open_err_str[0] != '\0') {
2296 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2297 report_capture_error(sync_msg_str, "");
2298 g_free(sync_msg_str);
2300 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2301 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2304 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2305 /* to remove any suid privileges. */
2306 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2307 /* (euid/egid have already previously been set to ruid/rgid. */
2308 /* (See comment in main() for details) */
2310 relinquish_special_privs_perm();
2312 relinquish_all_capabilities();
2317 /* close the capture input file (pcap or capture pipe) */
2318 static void capture_loop_close_input(loop_data *ld)
2321 pcap_options *pcap_opts;
2323 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2325 for (i = 0; i < ld->pcaps->len; i++) {
2326 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2327 /* if open, close the capture pipe "input file" */
2328 if (pcap_opts->cap_pipe_fd >= 0) {
2329 g_assert(pcap_opts->from_cap_pipe);
2330 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2331 pcap_opts->cap_pipe_fd = -1;
2334 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2335 CloseHandle(pcap_opts->cap_pipe_h);
2336 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2339 /* if open, close the pcap "input file" */
2340 if (pcap_opts->pcap_h != NULL) {
2341 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2342 pcap_close(pcap_opts->pcap_h);
2343 pcap_opts->pcap_h = NULL;
2350 /* Shut down windows sockets */
2356 /* init the capture filter */
2357 static initfilter_status_t
2358 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2359 const gchar * name, const gchar * cfilter)
2361 struct bpf_program fcode;
2363 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2365 /* capture filters only work on real interfaces */
2366 if (cfilter && !from_cap_pipe) {
2367 /* A capture filter was specified; set it up. */
2368 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2369 /* Treat this specially - our caller might try to compile this
2370 as a display filter and, if that succeeds, warn the user that
2371 the display and capture filter syntaxes are different. */
2372 return INITFILTER_BAD_FILTER;
2374 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2375 #ifdef HAVE_PCAP_FREECODE
2376 pcap_freecode(&fcode);
2378 return INITFILTER_OTHER_ERROR;
2380 #ifdef HAVE_PCAP_FREECODE
2381 pcap_freecode(&fcode);
2385 return INITFILTER_NO_ERROR;
2389 /* set up to write to the already-opened capture output file/files */
2391 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2395 pcap_options *pcap_opts;
2396 interface_options interface_opts;
2397 gboolean successful;
2399 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2401 if ((capture_opts->use_pcapng == FALSE) &&
2402 (capture_opts->ifaces->len > 1)) {
2403 g_snprintf(errmsg, errmsg_len,
2404 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
2408 /* Set up to write to the capture file. */
2409 if (capture_opts->multi_files_on) {
2410 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2412 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2413 if (ld->pdh == NULL) {
2418 if (capture_opts->use_pcapng) {
2420 GString *cpu_info_str;
2421 GString *os_info_str;
2423 cpu_info_str = g_string_new("");
2424 os_info_str = g_string_new("");
2425 get_cpu_info(cpu_info_str);
2426 get_os_version_info(os_info_str);
2428 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2429 successful = pcapng_write_session_header_block(ld->pdh,
2430 (const char *)capture_opts->capture_comment, /* Comment */
2431 cpu_info_str->str, /* HW */
2432 os_info_str->str, /* OS */
2434 -1, /* section_length */
2439 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2440 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2441 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2442 if (pcap_opts->from_cap_pipe) {
2443 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2445 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2447 successful = pcapng_write_interface_description_block(global_ld.pdh,
2448 NULL, /* OPT_COMMENT 1 */
2449 interface_opts.name, /* IDB_NAME 2 */
2450 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2451 interface_opts.cfilter, /* IDB_FILTER 11 */
2452 os_info_str->str, /* IDB_OS 12 */
2453 pcap_opts->linktype,
2455 &(global_ld.bytes_written),
2456 0, /* IDB_IF_SPEED 8 */
2457 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2461 g_string_free(os_info_str, TRUE);
2464 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2465 if (pcap_opts->from_cap_pipe) {
2466 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2468 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2470 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2471 pcap_opts->ts_nsec, &ld->bytes_written, &err);
2479 if (ld->pdh == NULL) {
2480 /* We couldn't set up to write to the capture file. */
2481 /* XXX - use cf_open_error_message from tshark instead? */
2486 g_snprintf(errmsg, errmsg_len,
2487 "The file to which the capture would be"
2488 " saved (\"%s\") could not be opened: Error %d.",
2489 capture_opts->save_file, err);
2491 g_snprintf(errmsg, errmsg_len,
2492 "The file to which the capture would be"
2493 " saved (\"%s\") could not be opened: %s.",
2494 capture_opts->save_file, g_strerror(err));
2506 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2510 pcap_options *pcap_opts;
2511 guint64 end_time = create_timestamp();
2513 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2515 if (capture_opts->multi_files_on) {
2516 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2518 if (capture_opts->use_pcapng) {
2519 for (i = 0; i < global_ld.pcaps->len; i++) {
2520 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2521 if (!pcap_opts->from_cap_pipe) {
2522 guint64 isb_ifrecv, isb_ifdrop;
2523 struct pcap_stat stats;
2525 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
2526 isb_ifrecv = pcap_opts->received;
2527 isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
2529 isb_ifrecv = G_MAXUINT64;
2530 isb_ifdrop = G_MAXUINT64;
2532 pcapng_write_interface_statistics_block(ld->pdh,
2535 "Counters provided by dumpcap",
2544 if (fclose(ld->pdh) == EOF) {
2545 if (err_close != NULL) {
2555 /* dispatch incoming packets (pcap or capture pipe)
2557 * Waits for incoming packets to be available, and calls pcap_dispatch()
2558 * to cause them to be processed.
2560 * Returns the number of packets which were processed.
2562 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2563 * packet-batching behaviour does not cause packets to get held back
2567 capture_loop_dispatch(loop_data *ld,
2568 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
2571 gint packet_count_before;
2572 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2577 packet_count_before = ld->packet_count;
2578 if (pcap_opts->from_cap_pipe) {
2579 /* dispatch from capture pipe */
2580 #ifdef LOG_CAPTURE_VERBOSE
2581 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2584 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
2586 if (sel_ret < 0 && errno != EINTR) {
2587 g_snprintf(errmsg, errmsg_len,
2588 "Unexpected error from select: %s", g_strerror(errno));
2589 report_capture_error(errmsg, please_report);
2594 * "select()" says we can read from the pipe without blocking
2597 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
2607 /* dispatch from pcap */
2608 #ifdef MUST_DO_SELECT
2610 * If we have "pcap_get_selectable_fd()", we use it to get the
2611 * descriptor on which to select; if that's -1, it means there
2612 * is no descriptor on which you can do a "select()" (perhaps
2613 * because you're capturing on a special device, and that device's
2614 * driver unfortunately doesn't support "select()", in which case
2615 * we don't do the select - which means it might not be possible
2616 * to stop a capture until a packet arrives. If that's unacceptable,
2617 * plead with whoever supplies the software for that device to add
2618 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2619 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2620 * later, so it can use pcap_breakloop().
2622 #ifdef LOG_CAPTURE_VERBOSE
2623 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2625 if (pcap_opts->pcap_fd != -1) {
2626 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
2629 * "select()" says we can read from it without blocking; go for
2632 * We don't have pcap_breakloop(), so we only process one packet
2633 * per pcap_dispatch() call, to allow a signal to stop the
2634 * processing immediately, rather than processing all packets
2635 * in a batch before quitting.
2638 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2640 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2644 /* Error, rather than pcap_breakloop(). */
2645 pcap_opts->pcap_err = TRUE;
2647 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2650 if (sel_ret < 0 && errno != EINTR) {
2651 g_snprintf(errmsg, errmsg_len,
2652 "Unexpected error from select: %s", g_strerror(errno));
2653 report_capture_error(errmsg, please_report);
2659 #endif /* MUST_DO_SELECT */
2661 /* dispatch from pcap without select */
2663 #ifdef LOG_CAPTURE_VERBOSE
2664 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2668 * On Windows, we don't support asynchronously telling a process to
2669 * stop capturing; instead, we check for an indication on a pipe
2670 * after processing packets. We therefore process only one packet
2671 * at a time, so that we can check the pipe after every packet.
2674 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2676 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2680 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2682 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2687 /* Error, rather than pcap_breakloop(). */
2688 pcap_opts->pcap_err = TRUE;
2690 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2692 #else /* pcap_next_ex */
2693 #ifdef LOG_CAPTURE_VERBOSE
2694 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2696 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2699 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2700 * see https://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
2701 * This should be fixed in the WinPcap 4.0 alpha release.
2703 * For reference, an example remote interface:
2704 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2707 /* emulate dispatch from pcap */
2710 struct pcap_pkthdr *pkt_header;
2715 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
2717 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2719 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2724 pcap_opts->pcap_err = TRUE;
2728 #endif /* pcap_next_ex */
2732 #ifdef LOG_CAPTURE_VERBOSE
2733 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2736 return ld->packet_count - packet_count_before;
2740 /* Isolate the Universally Unique Identifier from the interface. Basically, we
2741 * want to grab only the characters between the '{' and '}' delimiters.
2743 * Returns a GString that must be freed with g_string_free(). */
2745 isolate_uuid(const char *iface)
2750 ptr = strchr(iface, '{');
2752 return g_string_new(iface);
2753 gstr = g_string_new(ptr + 1);
2755 ptr = strchr(gstr->str, '}');
2759 gstr = g_string_truncate(gstr, ptr - gstr->str);
2764 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2765 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2767 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2768 char *errmsg, int errmsg_len)
2771 gchar *capfile_name;
2772 gchar *prefix, *suffix;
2773 gboolean is_tempfile;
2775 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2776 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
2778 if (capture_opts->save_file != NULL) {
2779 /* We return to the caller while the capture is in progress.
2780 * Therefore we need to take a copy of save_file in
2781 * case the caller destroys it after we return.
2783 capfile_name = g_strdup(capture_opts->save_file);
2785 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2786 if (capture_opts->multi_files_on) {
2787 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2788 g_snprintf(errmsg, errmsg_len,
2789 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2790 g_free(capfile_name);
2793 if (strcmp(capfile_name, "-") == 0) {
2794 /* write to stdout */
2797 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2798 _setmode(1, O_BINARY);
2801 } /* if (...output_to_pipe ... */
2804 if (capture_opts->multi_files_on) {
2805 /* ringbuffer is enabled */
2806 *save_file_fd = ringbuf_init(capfile_name,
2807 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
2808 capture_opts->group_read_access);
2810 /* we need the ringbuf name */
2811 if (*save_file_fd != -1) {
2812 g_free(capfile_name);
2813 capfile_name = g_strdup(ringbuf_current_filename());
2816 /* Try to open/create the specified file for use as a capture buffer. */
2817 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2818 (capture_opts->group_read_access) ? 0640 : 0600);
2821 is_tempfile = FALSE;
2823 /* Choose a random name for the temporary capture buffer */
2824 if (global_capture_opts.ifaces->len > 1) {
2825 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
2826 if (capture_opts->use_pcapng) {
2833 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
2835 /* use the generic portion of the interface guid to form the basis of the filename */
2836 if (strncmp("NPF_{", basename, 5)==0)
2838 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
2840 iface = isolate_uuid(basename);
2842 basename = g_strdup(iface->str);
2843 g_string_free(iface, TRUE);
2846 /* generate the temp file name prefix and suffix */
2847 if (capture_opts->use_pcapng) {
2848 prefix = g_strconcat("wireshark_", basename, NULL);
2851 prefix = g_strconcat("wireshark_", basename, NULL);
2856 *save_file_fd = create_tempfile(&tmpname, prefix, suffix);
2858 capfile_name = g_strdup(tmpname);
2862 /* did we fail to open the output file? */
2863 if (*save_file_fd == -1) {
2865 g_snprintf(errmsg, errmsg_len,
2866 "The temporary file to which the capture would be saved (\"%s\") "
2867 "could not be opened: %s.", capfile_name, g_strerror(errno));
2869 if (capture_opts->multi_files_on) {
2870 ringbuf_error_cleanup();
2873 g_snprintf(errmsg, errmsg_len,
2874 "The file to which the capture would be saved (\"%s\") "
2875 "could not be opened: %s.", capfile_name,
2878 g_free(capfile_name);
2882 if (capture_opts->save_file != NULL) {
2883 g_free(capture_opts->save_file);
2885 capture_opts->save_file = capfile_name;
2886 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2887 "g_free(capfile_name)". */
2893 /* Do the work of handling either the file size or file duration capture
2894 conditions being reached, and switching files or stopping. */
2896 do_file_switch_or_stop(capture_options *capture_opts,
2897 condition *cnd_autostop_files,
2898 condition *cnd_autostop_size,
2899 condition *cnd_file_duration)
2902 pcap_options *pcap_opts;
2903 interface_options interface_opts;
2904 gboolean successful;
2906 if (capture_opts->multi_files_on) {
2907 if (cnd_autostop_files != NULL &&
2908 cnd_eval(cnd_autostop_files, (guint64)++global_ld.autostop_files)) {
2909 /* no files left: stop here */
2910 global_ld.go = FALSE;
2914 /* Switch to the next ringbuffer file */
2915 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2916 &global_ld.save_file_fd, &global_ld.err)) {
2918 /* File switch succeeded: reset the conditions */
2919 global_ld.bytes_written = 0;
2920 if (capture_opts->use_pcapng) {
2922 GString *cpu_info_str;
2923 GString *os_info_str;
2925 cpu_info_str = g_string_new("");
2926 os_info_str = g_string_new("");
2927 get_cpu_info(cpu_info_str);
2928 get_os_version_info(os_info_str);
2930 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2931 successful = pcapng_write_session_header_block(global_ld.pdh,
2932 (const char *)capture_opts->capture_comment, /* Comment */
2933 cpu_info_str->str, /* HW */
2934 os_info_str->str, /* OS */
2936 -1, /* section_length */
2937 &(global_ld.bytes_written),
2941 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2942 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2943 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2944 successful = pcapng_write_interface_description_block(global_ld.pdh,
2945 NULL, /* OPT_COMMENT 1 */
2946 interface_opts.name, /* IDB_NAME 2 */
2947 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2948 interface_opts.cfilter, /* IDB_FILTER 11 */
2949 os_info_str->str, /* IDB_OS 12 */
2950 pcap_opts->linktype,
2952 &(global_ld.bytes_written),
2953 0, /* IDB_IF_SPEED 8 */
2954 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2958 g_string_free(os_info_str, TRUE);
2961 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
2962 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
2963 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
2966 fclose(global_ld.pdh);
2967 global_ld.pdh = NULL;
2968 global_ld.go = FALSE;
2971 if (cnd_autostop_size)
2972 cnd_reset(cnd_autostop_size);
2973 if (cnd_file_duration)
2974 cnd_reset(cnd_file_duration);
2975 fflush(global_ld.pdh);
2977 report_packet_count(global_ld.inpkts_to_sync_pipe);
2978 global_ld.inpkts_to_sync_pipe = 0;
2979 report_new_capture_file(capture_opts->save_file);
2981 /* File switch failed: stop here */
2982 global_ld.go = FALSE;
2986 /* single file, stop now */
2987 global_ld.go = FALSE;
2994 pcap_read_handler(void* arg)
2996 pcap_options *pcap_opts;
2997 char errmsg[MSG_MAX_LENGTH+1];
2999 pcap_opts = (pcap_options *)arg;
3001 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3002 pcap_opts->interface_id);
3004 while (global_ld.go) {
3005 /* dispatch incoming packets */
3006 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3008 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3009 pcap_opts->interface_id);
3010 g_thread_exit(NULL);
3014 /* Do the low-level work of a capture.
3015 Returns TRUE if it succeeds, FALSE otherwise. */
3017 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3020 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3022 struct timeval upd_time, cur_time;
3026 condition *cnd_file_duration = NULL;
3027 condition *cnd_autostop_files = NULL;
3028 condition *cnd_autostop_size = NULL;
3029 condition *cnd_autostop_duration = NULL;
3032 gboolean cfilter_error = FALSE;
3033 char errmsg[MSG_MAX_LENGTH+1];
3034 char secondary_errmsg[MSG_MAX_LENGTH+1];
3035 pcap_options *pcap_opts;
3036 interface_options interface_opts;
3037 guint i, error_index = 0;
3040 *secondary_errmsg = '\0';
3042 /* init the loop data */
3043 global_ld.go = TRUE;
3044 global_ld.packet_count = 0;
3046 global_ld.report_packet_count = FALSE;
3048 if (capture_opts->has_autostop_packets)
3049 global_ld.packet_max = capture_opts->autostop_packets;
3051 global_ld.packet_max = 0; /* no limit */
3052 global_ld.inpkts_to_sync_pipe = 0;
3053 global_ld.err = 0; /* no error seen yet */
3054 global_ld.pdh = NULL;
3055 global_ld.autostop_files = 0;
3056 global_ld.save_file_fd = -1;
3058 /* We haven't yet gotten the capture statistics. */
3059 *stats_known = FALSE;
3061 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3062 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3064 /* open the "input file" from network interface or capture pipe */
3065 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3066 secondary_errmsg, sizeof(secondary_errmsg))) {
3069 for (i = 0; i < capture_opts->ifaces->len; i++) {
3070 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3071 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3072 /* init the input filter from the network interface (capture pipe will do nothing) */
3074 * When remote capturing WinPCap crashes when the capture filter
3075 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3078 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3079 interface_opts.name,
3080 interface_opts.cfilter?interface_opts.cfilter:"")) {
3082 case INITFILTER_NO_ERROR:
3085 case INITFILTER_BAD_FILTER:
3086 cfilter_error = TRUE;
3088 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3091 case INITFILTER_OTHER_ERROR:
3092 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3093 pcap_geterr(pcap_opts->pcap_h));
3094 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3099 /* If we're supposed to write to a capture file, open it for output
3100 (temporary/specified name/ringbuffer) */
3101 if (capture_opts->saving_to_file) {
3102 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3103 errmsg, sizeof(errmsg))) {
3107 /* set up to write to the already-opened capture output file/files */
3108 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3113 /* XXX - capture SIGTERM and close the capture, in case we're on a
3114 Linux 2.0[.x] system and you have to explicitly close the capture
3115 stream in order to turn promiscuous mode off? We need to do that
3116 in other places as well - and I don't think that works all the
3117 time in any case, due to libpcap bugs. */
3119 /* Well, we should be able to start capturing.
3121 Sync out the capture file, so the header makes it to the file system,
3122 and send a "capture started successfully and capture file created"
3123 message to our parent so that they'll open the capture file and
3124 update its windows to indicate that we have a live capture in
3126 fflush(global_ld.pdh);
3127 report_new_capture_file(capture_opts->save_file);
3130 /* initialize capture stop (and alike) conditions */
3131 init_capture_stop_conditions();
3132 /* create stop conditions */
3133 if (capture_opts->has_autostop_filesize) {
3134 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3135 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3138 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3140 if (capture_opts->has_autostop_duration)
3141 cnd_autostop_duration =
3142 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3144 if (capture_opts->multi_files_on) {
3145 if (capture_opts->has_file_duration)
3147 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3149 if (capture_opts->has_autostop_files)
3150 cnd_autostop_files =
3151 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_files);
3154 /* init the time values */
3156 upd_time = GetTickCount();
3158 gettimeofday(&upd_time, NULL);
3160 start_time = create_timestamp();
3161 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3163 /* WOW, everything is prepared! */
3164 /* please fasten your seat belts, we will enter now the actual capture loop */
3166 pcap_queue = g_async_queue_new();
3167 pcap_queue_bytes = 0;
3168 pcap_queue_packets = 0;
3169 for (i = 0; i < global_ld.pcaps->len; i++) {
3170 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3171 #if GLIB_CHECK_VERSION(2,31,0)
3172 /* XXX - Add an interface name here? */
3173 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3175 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3179 while (global_ld.go) {
3180 /* dispatch incoming packets */
3182 pcap_queue_element *queue_element;
3183 #if GLIB_CHECK_VERSION(2,31,18)
3185 g_async_queue_lock(pcap_queue);
3186 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3188 GTimeVal write_thread_time;
3190 g_get_current_time(&write_thread_time);
3191 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3192 g_async_queue_lock(pcap_queue);
3193 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3195 if (queue_element) {
3196 pcap_queue_bytes -= queue_element->phdr.caplen;
3197 pcap_queue_packets -= 1;
3199 g_async_queue_unlock(pcap_queue);
3200 if (queue_element) {
3201 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3202 "Dequeued a packet of length %d captured on interface %d.",
3203 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3205 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3206 &queue_element->phdr,
3208 g_free(queue_element->pd);
3209 g_free(queue_element);
3215 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3216 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3217 sizeof(errmsg), pcap_opts);
3220 /* Were we asked to print packet counts by the SIGINFO handler? */
3221 if (global_ld.report_packet_count) {
3222 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3223 plurality(global_ld.packet_count, "", "s"));
3224 global_ld.report_packet_count = FALSE;
3229 /* any news from our parent (signal pipe)? -> just stop the capture */
3230 if (!signal_pipe_check_running()) {
3231 global_ld.go = FALSE;
3236 global_ld.inpkts_to_sync_pipe += inpkts;
3238 /* check capture size condition */
3239 if (cnd_autostop_size != NULL &&
3240 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3241 /* Capture size limit reached, do we have another file? */
3242 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3243 cnd_autostop_size, cnd_file_duration))
3245 } /* cnd_autostop_size */
3246 if (capture_opts->output_to_pipe) {
3247 fflush(global_ld.pdh);
3251 /* Only update once every 500ms so as not to overload slow displays.
3252 * This also prevents too much context-switching between the dumpcap
3253 * and wireshark processes.
3255 #define DUMPCAP_UPD_TIME 500
3258 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3259 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3261 gettimeofday(&cur_time, NULL);
3262 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3263 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3266 upd_time = cur_time;
3269 if (pcap_stats(pch, stats) >= 0) {
3270 *stats_known = TRUE;
3273 /* Let the parent process know. */
3274 if (global_ld.inpkts_to_sync_pipe) {
3276 fflush(global_ld.pdh);
3278 /* Send our parent a message saying we've written out
3279 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3281 report_packet_count(global_ld.inpkts_to_sync_pipe);
3283 global_ld.inpkts_to_sync_pipe = 0;
3286 /* check capture duration condition */
3287 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3288 /* The maximum capture time has elapsed; stop the capture. */
3289 global_ld.go = FALSE;
3293 /* check capture file duration condition */
3294 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3295 /* duration limit reached, do we have another file? */
3296 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3297 cnd_autostop_size, cnd_file_duration))
3299 } /* cnd_file_duration */
3303 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3305 pcap_queue_element *queue_element;
3307 for (i = 0; i < global_ld.pcaps->len; i++) {
3308 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3309 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3310 pcap_opts->interface_id);
3311 g_thread_join(pcap_opts->tid);
3312 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3313 pcap_opts->interface_id);
3316 g_async_queue_lock(pcap_queue);
3317 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3318 if (queue_element) {
3319 pcap_queue_bytes -= queue_element->phdr.caplen;
3320 pcap_queue_packets -= 1;
3322 g_async_queue_unlock(pcap_queue);
3323 if (queue_element == NULL) {
3326 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3327 "Dequeued a packet of length %d captured on interface %d.",
3328 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3329 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3330 &queue_element->phdr,
3332 g_free(queue_element->pd);
3333 g_free(queue_element);
3334 global_ld.inpkts_to_sync_pipe += 1;
3335 if (capture_opts->output_to_pipe) {
3336 fflush(global_ld.pdh);
3342 /* delete stop conditions */
3343 if (cnd_file_duration != NULL)
3344 cnd_delete(cnd_file_duration);
3345 if (cnd_autostop_files != NULL)
3346 cnd_delete(cnd_autostop_files);
3347 if (cnd_autostop_size != NULL)
3348 cnd_delete(cnd_autostop_size);
3349 if (cnd_autostop_duration != NULL)
3350 cnd_delete(cnd_autostop_duration);
3352 /* did we have a pcap (input) error? */
3353 for (i = 0; i < capture_opts->ifaces->len; i++) {
3354 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3355 if (pcap_opts->pcap_err) {
3356 /* On Linux, if an interface goes down while you're capturing on it,
3357 you'll get a "recvfrom: Network is down" or
3358 "The interface went down" error (ENETDOWN).
3359 (At least you will if g_strerror() doesn't show a local translation
3362 On FreeBSD and OS X, if a network adapter disappears while
3363 you're capturing on it, you'll get a "read: Device not configured"
3364 error (ENXIO). (See previous parenthetical note.)
3366 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3368 These should *not* be reported to the Wireshark developers. */
3371 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3372 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3373 strcmp(cap_err_str, "The interface went down") == 0 ||
3374 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3375 strcmp(cap_err_str, "read: I/O error") == 0 ||
3376 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3377 report_capture_error("The network adapter on which the capture was being done "
3378 "is no longer running; the capture has stopped.",
3381 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3383 report_capture_error(errmsg, please_report);
3386 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3387 report_capture_error(errmsg, "");
3391 /* did we have an output error while capturing? */
3392 if (global_ld.err == 0) {
3395 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3396 global_ld.err, FALSE);
3397 report_capture_error(errmsg, please_report);
3401 if (capture_opts->saving_to_file) {
3402 /* close the output file */
3403 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3407 /* there might be packets not yet notified to the parent */
3408 /* (do this after closing the file, so all packets are already flushed) */
3409 if (global_ld.inpkts_to_sync_pipe) {
3411 report_packet_count(global_ld.inpkts_to_sync_pipe);
3412 global_ld.inpkts_to_sync_pipe = 0;
3415 /* If we've displayed a message about a write error, there's no point
3416 in displaying another message about an error on close. */
3417 if (!close_ok && write_ok) {
3418 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3420 report_capture_error(errmsg, "");
3424 * XXX We exhibit different behaviour between normal mode and sync mode
3425 * when the pipe is stdin and not already at EOF. If we're a child, the
3426 * parent's stdin isn't closed, so if the user starts another capture,
3427 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3428 * will say "Unrecognized libpcap format". On the other hand, in normal
3429 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3432 report_capture_count(TRUE);
3434 /* get packet drop statistics from pcap */
3435 for (i = 0; i < capture_opts->ifaces->len; i++) {
3437 guint32 pcap_dropped = 0;
3439 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3440 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3441 received = pcap_opts->received;
3442 if (pcap_opts->pcap_h != NULL) {
3443 g_assert(!pcap_opts->from_cap_pipe);
3444 /* Get the capture statistics, so we know how many packets were dropped. */
3446 * Older versions of libpcap didn't set ps_ifdrop on some
3447 * platforms; initialize it to 0 to handle that.
3449 stats->ps_ifdrop = 0;
3450 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3451 *stats_known = TRUE;
3452 /* Let the parent process know. */
3453 pcap_dropped += stats->ps_drop;
3455 g_snprintf(errmsg, sizeof(errmsg),
3456 "Can't get packet-drop statistics: %s",
3457 pcap_geterr(pcap_opts->pcap_h));
3458 report_capture_error(errmsg, please_report);
3461 report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
3464 /* close the input file (pcap or capture pipe) */
3465 capture_loop_close_input(&global_ld);
3467 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
3469 /* ok, if the write and the close were successful. */
3470 return write_ok && close_ok;
3473 if (capture_opts->multi_files_on) {
3474 /* cleanup ringbuffer */
3475 ringbuf_error_cleanup();
3477 /* We can't use the save file, and we have no FILE * for the stream
3478 to close in order to close it, so close the FD directly. */
3479 if (global_ld.save_file_fd != -1) {
3480 ws_close(global_ld.save_file_fd);
3483 /* We couldn't even start the capture, so get rid of the capture
3485 if (capture_opts->save_file != NULL) {
3486 ws_unlink(capture_opts->save_file);
3487 g_free(capture_opts->save_file);
3490 capture_opts->save_file = NULL;
3492 report_cfilter_error(capture_opts, error_index, errmsg);
3494 report_capture_error(errmsg, secondary_errmsg);
3496 /* close the input file (pcap or cap_pipe) */
3497 capture_loop_close_input(&global_ld);
3499 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3506 capture_loop_stop(void)
3508 #ifdef HAVE_PCAP_BREAKLOOP
3510 pcap_options *pcap_opts;
3512 for (i = 0; i < global_ld.pcaps->len; i++) {
3513 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3514 if (pcap_opts->pcap_h != NULL)
3515 pcap_breakloop(pcap_opts->pcap_h);
3518 global_ld.go = FALSE;
3523 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3524 int err, gboolean is_close)
3529 g_snprintf(errmsg, errmsglen,
3530 "Not all the packets could be written to the file"
3531 " to which the capture was being saved\n"
3532 "(\"%s\") because there is no space left on the file system\n"
3533 "on which that file resides.",
3539 g_snprintf(errmsg, errmsglen,
3540 "Not all the packets could be written to the file"
3541 " to which the capture was being saved\n"
3542 "(\"%s\") because you are too close to, or over,"
3543 " your disk quota\n"
3544 "on the file system on which that file resides.",
3551 g_snprintf(errmsg, errmsglen,
3552 "The file to which the capture was being saved\n"
3553 "(\"%s\") could not be closed: %s.",
3554 fname, g_strerror(err));
3556 g_snprintf(errmsg, errmsglen,
3557 "An error occurred while writing to the file"
3558 " to which the capture was being saved\n"
3560 fname, g_strerror(err));
3567 /* one packet was captured, process it */
3569 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3572 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3574 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
3576 /* We may be called multiple times from pcap_dispatch(); if we've set
3577 the "stop capturing" flag, ignore this packet, as we're not
3578 supposed to be saving any more packets. */
3579 if (!global_ld.go) {
3580 pcap_opts->flushed++;
3584 if (global_ld.pdh) {
3585 gboolean successful;
3587 /* We're supposed to write the packet to a file; do so.
3588 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3589 "ld->err" to the error. */
3590 if (global_capture_opts.use_pcapng) {
3591 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
3593 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3594 phdr->caplen, phdr->len,
3595 pcap_opts->interface_id,
3598 &global_ld.bytes_written, &err);
3600 successful = libpcap_write_packet(global_ld.pdh,
3601 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3602 phdr->caplen, phdr->len,
3604 &global_ld.bytes_written, &err);
3607 global_ld.go = FALSE;
3608 global_ld.err = err;
3609 pcap_opts->dropped++;
3611 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3612 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3613 "Wrote a packet of length %d captured on interface %u.",
3614 phdr->caplen, pcap_opts->interface_id);
3616 global_ld.packet_count++;
3617 pcap_opts->received++;
3618 /* if the user told us to stop after x packets, do we already have enough? */
3619 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
3620 global_ld.go = FALSE;
3626 /* one packet was captured, queue it */
3628 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3631 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3632 pcap_queue_element *queue_element;
3633 gboolean limit_reached;
3635 /* We may be called multiple times from pcap_dispatch(); if we've set
3636 the "stop capturing" flag, ignore this packet, as we're not
3637 supposed to be saving any more packets. */
3638 if (!global_ld.go) {
3639 pcap_opts->flushed++;
3643 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
3644 if (queue_element == NULL) {
3645 pcap_opts->dropped++;
3648 queue_element->pcap_opts = pcap_opts;
3649 queue_element->phdr = *phdr;
3650 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
3651 if (queue_element->pd == NULL) {
3652 pcap_opts->dropped++;
3653 g_free(queue_element);
3656 memcpy(queue_element->pd, pd, phdr->caplen);
3657 g_async_queue_lock(pcap_queue);
3658 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
3659 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
3660 limit_reached = FALSE;
3661 g_async_queue_push_unlocked(pcap_queue, queue_element);
3662 pcap_queue_bytes += phdr->caplen;
3663 pcap_queue_packets += 1;
3665 limit_reached = TRUE;
3667 g_async_queue_unlock(pcap_queue);
3668 if (limit_reached) {
3669 pcap_opts->dropped++;
3670 g_free(queue_element->pd);
3671 g_free(queue_element);
3672 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3673 "Dropped a packet of length %d captured on interface %u.",
3674 phdr->caplen, pcap_opts->interface_id);
3676 pcap_opts->received++;
3677 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3678 "Queued a packet of length %d captured on interface %u.",
3679 phdr->caplen, pcap_opts->interface_id);
3681 /* I don't want to hold the mutex over the debug output. So the
3682 output may be wrong */
3683 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3684 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
3685 pcap_queue_bytes, pcap_queue_packets);
3689 set_80211_channel(const char *iface, const char *opt)
3693 guint32 center_freq1 = 0;
3694 guint32 center_freq2 = 0;
3697 gchar **options = NULL;
3699 options = g_strsplit_set(opt, ",", 4);
3700 for (args = 0; options[args]; args++);
3703 freq = get_nonzero_guint32(options[0], "802.11 channel frequency");
3705 if (args >= 1 && options[1]) {
3706 type = ws80211_str_to_chan_type(options[1]);
3708 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
3714 if (args >= 2 && options[2])
3715 center_freq1 = get_nonzero_guint32(options[2], "VHT center frequency");
3717 if (args >= 3 && options[3])
3718 center_freq2 = get_nonzero_guint32(options[3], "VHT center frequency 2");
3720 ret = ws80211_init();
3722 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
3726 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
3729 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
3735 pipe_write_block(2, SP_SUCCESS, NULL);
3738 g_strfreev(options);
3743 get_dumpcap_compiled_info(GString *str)
3745 /* Capture libraries */
3746 g_string_append(str, ", ");
3747 get_compiled_caplibs_version(str);
3751 get_dumpcap_runtime_info(GString *str)
3753 /* Capture libraries */
3754 g_string_append(str, ", ");
3755 get_runtime_caplibs_version(str);
3758 /* And now our feature presentation... [ fade to music ] */
3760 main(int argc, char *argv[])
3762 GString *comp_info_str;
3763 GString *runtime_info_str;
3765 static const struct option long_options[] = {
3766 {"help", no_argument, NULL, 'h'},
3767 {"version", no_argument, NULL, 'v'},
3768 LONGOPT_CAPTURE_COMMON
3772 gboolean arg_error = FALSE;
3777 struct sigaction action, oldaction;
3780 gboolean start_capture = TRUE;
3781 gboolean stats_known;
3782 struct pcap_stat stats;
3783 GLogLevelFlags log_flags;
3784 gboolean list_interfaces = FALSE;
3785 gboolean list_link_layer_types = FALSE;
3786 #ifdef HAVE_BPF_IMAGE
3787 gboolean print_bpf_code = FALSE;
3789 gboolean set_chan = FALSE;
3790 gchar *set_chan_arg = NULL;
3791 gboolean machine_readable = FALSE;
3792 gboolean print_statistics = FALSE;
3793 int status, run_once_args = 0;
3796 #if defined(__APPLE__) && defined(__LP64__)
3797 struct utsname osinfo;
3801 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
3803 /* Get the compile-time version information string */
3804 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
3806 /* Get the run-time version information string */
3807 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
3809 /* Add it to the information to be reported on a crash. */
3810 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
3815 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
3816 g_string_free(comp_info_str, TRUE);
3817 g_string_free(runtime_info_str, TRUE);
3820 arg_list_utf_16to8(argc, argv);
3821 create_app_running_mutex();
3824 * Initialize our DLL search path. MUST be called before LoadLibrary
3827 ws_init_dll_search_path();
3830 #ifdef HAVE_BPF_IMAGE
3831 #define OPTSTRING_d "d"
3833 #define OPTSTRING_d ""
3836 #ifdef HAVE_PCAP_REMOTE
3837 #define OPTSTRING_r "r"
3838 #define OPTSTRING_u "u"
3840 #define OPTSTRING_r ""
3841 #define OPTSTRING_u ""
3844 #ifdef HAVE_PCAP_SETSAMPLING
3845 #define OPTSTRING_m "m:"
3847 #define OPTSTRING_m ""
3850 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
3852 #ifdef DEBUG_CHILD_DUMPCAP
3853 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3854 fprintf (stderr, "Unable to open debug log file .\n");
3859 #if defined(__APPLE__) && defined(__LP64__)
3861 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
3862 * a bug workaround - timeouts less than 1 second don't work with libpcap
3863 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3864 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
3865 * The problem is extremely unlikely to be reintroduced in a future
3868 if (uname(&osinfo) == 0) {
3870 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
3871 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3872 * number of 10.0.0, not 10.1.0 - go figure).
3874 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
3875 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
3876 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
3877 need_timeout_workaround = TRUE;
3882 * Determine if dumpcap is being requested to run in a special
3883 * capture_child mode by going thru the command line args to see if
3884 * a -Z is present. (-Z is a hidden option).
3886 * The primary result of running in capture_child mode is that
3887 * all messages sent out on stderr are in a special type/len/string
3888 * format to allow message processing by type. These messages include
3889 * error messages if dumpcap fails to start the operation it was
3890 * requested to do, as well as various "status" messages which are sent
3891 * when an actual capture is in progress, and a "success" message sent
3892 * if dumpcap was requested to perform an operation other than a
3895 * Capture_child mode would normally be requested by a parent process
3896 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3897 * to which dumpcap stderr has been redirected. It might also have
3898 * another pipe to obtain dumpcap stdout output; for operations other
3899 * than a capture, that information is formatted specially for easier
3900 * parsing by the parent process.
3902 * Capture_child mode needs to be determined immediately upon
3903 * startup so that any messages generated by dumpcap in this mode
3904 * (eg: during initialization) will be formatted properly.
3907 for (i=1; i<argc; i++) {
3908 if (strcmp("-Z", argv[i]) == 0) {
3909 capture_child = TRUE;
3910 machine_readable = TRUE; /* request machine-readable output */
3912 /* set output pipe to binary mode, to avoid ugly text conversions */
3913 _setmode(2, O_BINARY);
3918 /* The default_log_handler will use stdout, which makes trouble in */
3919 /* capture child mode, as it uses stdout for its sync_pipe. */
3920 /* So: the filtering is done in the console_log_handler and not here.*/
3921 /* We set the log handlers right up front to make sure that any log */
3922 /* messages when running as child will be sent back to the parent */
3923 /* with the correct format. */
3928 G_LOG_LEVEL_CRITICAL|
3929 G_LOG_LEVEL_WARNING|
3930 G_LOG_LEVEL_MESSAGE|
3934 G_LOG_FLAG_RECURSION);
3936 g_log_set_handler(NULL,
3938 console_log_handler, NULL /* user_data */);
3939 g_log_set_handler(LOG_DOMAIN_MAIN,
3941 console_log_handler, NULL /* user_data */);
3942 g_log_set_handler(LOG_DOMAIN_CAPTURE,
3944 console_log_handler, NULL /* user_data */);
3945 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3947 console_log_handler, NULL /* user_data */);
3949 /* Initialize the pcaps list */
3950 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
3952 #if !GLIB_CHECK_VERSION(2,31,0)
3953 /* Initialize the thread system */
3954 g_thread_init(NULL);
3958 /* Load wpcap if possible. Do this before collecting the run-time version information */
3961 /* ... and also load the packet.dll from wpcap */
3962 /* XXX - currently not required, may change later. */
3963 /*wpcap_packet_load();*/
3965 /* Start windows sockets */
3966 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3968 /* Set handler for Ctrl+C key */
3969 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3971 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3972 and exit. Do the same with SIGPIPE, in case, for example,
3973 we're writing to our standard output and it's a pipe.
3974 Do the same with SIGHUP if it's not being ignored (if we're
3975 being run under nohup, it might be ignored, in which case we
3976 should leave it ignored).
3978 XXX - apparently, Coverity complained that part of action
3979 wasn't initialized. Perhaps it's running on Linux, where
3980 struct sigaction has an ignored "sa_restorer" element and
3981 where "sa_handler" and "sa_sigaction" might not be two
3982 members of a union. */
3983 memset(&action, 0, sizeof(action));
3984 action.sa_handler = capture_cleanup_handler;
3986 * Arrange that system calls not get restarted, because when
3987 * our signal handler returns we don't want to restart
3988 * a call that was waiting for packets to arrive.
3990 action.sa_flags = 0;
3991 sigemptyset(&action.sa_mask);
3992 sigaction(SIGTERM, &action, NULL);
3993 sigaction(SIGINT, &action, NULL);
3994 sigaction(SIGPIPE, &action, NULL);
3995 sigaction(SIGHUP, NULL, &oldaction);
3996 if (oldaction.sa_handler == SIG_DFL)
3997 sigaction(SIGHUP, &action, NULL);
4000 /* Catch SIGINFO and, if we get it and we're capturing in
4001 quiet mode, report the number of packets we've captured. */
4002 action.sa_handler = report_counts_siginfo;
4003 action.sa_flags = SA_RESTART;
4004 sigemptyset(&action.sa_mask);
4005 sigaction(SIGINFO, &action, NULL);
4006 #endif /* SIGINFO */
4010 enable_kernel_bpf_jit_compiler();
4013 /* ----------------------------------------------------------------- */
4014 /* Privilege and capability handling */
4016 /* 1. Running not as root or suid root; no special capabilities. */
4019 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4022 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4024 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4025 /* capabilities; Drop all other capabilities; */
4026 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4027 /* else: after pcap_open_live() in capture_loop_open_input() */
4028 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4029 /* (Note: this means that the process, although logged in */
4030 /* as root, does not have various permissions such as the */
4031 /* ability to bypass file access permissions). */
4032 /* XXX: Should we just leave capabilities alone in this case */
4033 /* so that user gets expected effect that root can do */
4036 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4038 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4039 /* else: after pcap_open_live() in capture_loop_open_input() */
4040 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4041 /* pcap_open_live). */
4043 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4045 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4046 /* capabilities; Drop all other capabilities; */
4047 /* Drop suid privileges (euid=ruid); */
4048 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4049 /* else: after pcap_open_live() in capture_loop_open_input() */
4050 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4052 /* XXX: For some Linux versions/distros with capabilities */
4053 /* a 'normal' process with any capabilities cannot be */
4054 /* 'killed' (signaled) from another (same uid) non-privileged */
4056 /* For example: If (non-suid) Wireshark forks a */
4057 /* child suid dumpcap which acts as described here (case 5), */
4058 /* Wireshark will be unable to kill (signal) the child */
4059 /* dumpcap process until the capabilities have been dropped */
4060 /* (after pcap_open_live()). */
4061 /* This behaviour will apparently be changed in the kernel */
4062 /* to allow the kill (signal) in this case. */
4063 /* See the following for details: */
4064 /* https://www.mail-archive.com/ [wrapped] */
4065 /* linux-security-module@vger.kernel.org/msg02913.html */
4067 /* It is therefore conceivable that if dumpcap somehow hangs */
4068 /* in pcap_open_live or before that wireshark will not */
4069 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4070 /* In this case, exiting wireshark will kill the child */
4071 /* dumpcap process. */
4073 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4074 /* capabilities; Using libcap. Note: capset cmd (which see) */
4075 /* used to assign capabilities to file. */
4077 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4078 /* else: after pcap_open_live() in capture_loop_open_input() */
4079 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4081 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4082 /* longer required (similar to capture). */
4084 /* ----------------------------------------------------------------- */
4086 init_process_policies();
4089 /* If 'started with special privileges' (and using libcap) */
4090 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4091 /* Set euid/egid = ruid/rgid to remove suid privileges */
4092 relinquish_privs_except_capture();
4095 /* Set the initial values in the capture options. This might be overwritten
4096 by the command line parameters. */
4097 capture_opts_init(&global_capture_opts);
4098 /* We always save to a file - if no file was specified, we save to a
4100 global_capture_opts.saving_to_file = TRUE;
4101 global_capture_opts.has_ring_num_files = TRUE;
4103 /* Pass on capture_child mode for capture_opts */
4104 global_capture_opts.capture_child = capture_child;
4106 /* Now get our args */
4107 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4109 case 'h': /* Print help and exit */
4110 printf("Dumpcap (Wireshark) %s\n"
4111 "Capture network packets and dump them into a pcapng or pcap file.\n"
4112 "See https://www.wireshark.org for more information.\n",
4113 get_ws_vcs_version_info());
4114 print_usage(stdout);
4117 case 'v': /* Show version and exit */
4118 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4119 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4120 show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4121 g_string_free(comp_info_str, TRUE);
4122 g_string_free(runtime_info_str, TRUE);
4125 /*** capture option specific ***/
4126 case 'a': /* autostop criteria */
4127 case 'b': /* Ringbuffer option */
4128 case 'c': /* Capture x packets */
4129 case 'f': /* capture filter */
4130 case 'g': /* enable group read access on file(s) */
4131 case 'i': /* Use interface x */
4132 case 'n': /* Use pcapng format */
4133 case 'p': /* Don't capture in promiscuous mode */
4134 case 'P': /* Use pcap format */
4135 case 's': /* Set the snapshot (capture) length */
4136 case 'w': /* Write to capture file x */
4137 case 'y': /* Set the pcap data link type */
4138 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4139 #ifdef HAVE_PCAP_REMOTE
4140 case 'u': /* Use UDP for data transfer */
4141 case 'r': /* Capture own RPCAP traffic too */
4142 case 'A': /* Authentication */
4144 #ifdef HAVE_PCAP_SETSAMPLING
4145 case 'm': /* Sampling */
4147 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4148 case 'B': /* Buffer size */
4150 #ifdef HAVE_PCAP_CREATE
4151 case 'I': /* Monitor mode */
4153 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4158 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4160 capture_child = TRUE;
4162 /* set output pipe to binary mode, to avoid ugly text conversions */
4163 _setmode(2, O_BINARY);
4165 * optarg = the control ID, aka the PPID, currently used for the
4168 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4169 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4170 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4171 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4173 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4174 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4175 "Signal pipe: Unable to open %s. Dead parent?",
4183 case 'q': /* Quiet */
4189 /*** all non capture option specific ***/
4190 case 'D': /* Print a list of capture devices and exit */
4191 if (!list_interfaces) {
4192 list_interfaces = TRUE;
4196 case 'L': /* Print list of link-layer types and exit */
4197 if (!list_link_layer_types) {
4198 list_link_layer_types = TRUE;
4202 #ifdef HAVE_BPF_IMAGE
4203 case 'd': /* Print BPF code for capture filter and exit */
4204 if (!print_bpf_code) {
4205 print_bpf_code = TRUE;
4210 case 'S': /* Print interface statistics once a second */
4211 if (!print_statistics) {
4212 print_statistics = TRUE;
4216 case 'k': /* Set wireless channel */
4219 set_chan_arg = optarg;
4222 cmdarg_err("Only one -k flag may be specified");
4226 case 'M': /* For -D, -L, and -S, print machine-readable output */
4227 machine_readable = TRUE;
4230 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4233 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4236 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4238 case '?': /* Bad flag - print usage message */
4247 /* user specified file name as regular command-line argument */
4248 /* XXX - use it as the capture file name (or something else)? */
4254 * Extra command line arguments were specified; complain.
4255 * XXX - interpret as capture filter, as tcpdump and tshark do?
4257 cmdarg_err("Invalid argument: %s", argv[0]);
4262 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4265 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4266 /* Use some default if the user hasn't specified some */
4267 /* XXX: Are these defaults good enough? */
4268 pcap_queue_byte_limit = 1000 * 1000;
4269 pcap_queue_packet_limit = 1000;
4272 print_usage(stderr);
4276 if (run_once_args > 1) {
4277 #ifdef HAVE_BPF_IMAGE
4278 cmdarg_err("Only one of -D, -L, -d, -k, or -S may be supplied.");
4280 cmdarg_err("Only one of -D, -L, -k, or -S may be supplied.");
4283 } else if (run_once_args == 1) {
4284 /* We're supposed to print some information, rather than
4285 to capture traffic; did they specify a ring buffer option? */
4286 if (global_capture_opts.multi_files_on) {
4287 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4291 /* We're supposed to capture traffic; */
4293 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4294 if (global_capture_opts.ifaces->len > 1) {
4296 global_capture_opts.use_pcapng = TRUE;
4299 if (global_capture_opts.capture_comment &&
4300 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4301 /* XXX - for ringbuffer, should we apply the comment to each file? */
4302 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4306 /* Was the ring buffer option specified and, if so, does it make sense? */
4307 if (global_capture_opts.multi_files_on) {
4308 /* Ring buffer works only under certain conditions:
4309 a) ring buffer does not work with temporary files;
4310 b) it makes no sense to enable the ring buffer if the maximum
4311 file size is set to "infinite". */
4312 if (global_capture_opts.save_file == NULL) {
4313 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4314 global_capture_opts.multi_files_on = FALSE;
4316 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4317 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4319 /* XXX - this must be redesigned as the conditions changed */
4320 global_capture_opts.multi_files_on = FALSE;
4327 * "-D" requires no interface to be selected; it's supposed to list
4330 if (list_interfaces) {
4331 /* Get the list of interfaces */
4336 if_list = capture_interface_list(&err, &err_str,NULL);
4337 if (if_list == NULL) {
4340 * If we're being run by another program, just give them
4341 * an empty list of interfaces, don't report this as
4342 * an error; that lets them decide whether to report
4343 * this as an error or not.
4345 if (!machine_readable) {
4346 cmdarg_err("There are no interfaces on which a capture can be done");
4350 cmdarg_err("%s", err_str);
4356 if (machine_readable) /* tab-separated values to stdout */
4357 print_machine_readable_interfaces(if_list);
4359 capture_opts_print_interfaces(if_list);
4360 free_interface_list(if_list);
4365 * "-S" requires no interface to be selected; it gives statistics
4366 * for all interfaces.
4368 if (print_statistics) {
4369 status = print_statistics_loop(machine_readable);
4374 interface_options interface_opts;
4376 if (global_capture_opts.ifaces->len != 1) {
4377 cmdarg_err("Need one interface");
4381 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4382 status = set_80211_channel(interface_opts.name, set_chan_arg);
4387 * "-L", "-d", and capturing act on a particular interface, so we have to
4388 * have an interface; if none was specified, pick a default.
4390 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4392 /* cmdarg_err() already called .... */
4396 if (list_link_layer_types) {
4397 /* Get the list of link-layer types for the capture device. */
4398 if_capabilities_t *caps;
4402 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4403 interface_options interface_opts;
4405 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4407 caps = get_if_capabilities(&interface_opts, &err_str);
4409 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4410 "Please check to make sure you have sufficient permissions, and that\n"
4411 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4415 if (caps->data_link_types == NULL) {
4416 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4419 if (machine_readable) /* tab-separated values to stdout */
4420 /* XXX: We need to change the format and adopt consumers */
4421 print_machine_readable_if_capabilities(caps);
4423 /* XXX: We might want to print also the interface name */
4424 capture_opts_print_if_capabilities(caps, interface_opts.name,
4425 interface_opts.monitor_mode);
4426 free_if_capabilities(caps);
4431 /* We're supposed to do a capture, or print the BPF code for a filter. */
4433 /* Let the user know what interfaces were chosen. */
4434 if (capture_child) {
4435 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4436 interface_options interface_opts;
4438 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4439 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4440 interface_opts.name);
4443 str = g_string_new("");
4445 if (global_capture_opts.ifaces->len < 2)
4447 if (global_capture_opts.ifaces->len < 4)
4450 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4451 interface_options interface_opts;
4453 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4455 if (global_capture_opts.ifaces->len > 2) {
4456 g_string_append_printf(str, ",");
4458 g_string_append_printf(str, " ");
4459 if (j == global_capture_opts.ifaces->len - 1) {
4460 g_string_append_printf(str, "and ");
4463 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4466 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4468 fprintf(stderr, "Capturing on %s\n", str->str);
4469 g_string_free(str, TRUE);
4472 /* Process the snapshot length, as that affects the generated BPF code. */
4473 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4475 #ifdef HAVE_BPF_IMAGE
4476 if (print_bpf_code) {
4477 show_filter_code(&global_capture_opts);
4482 /* We're supposed to do a capture. Process the ring buffer arguments. */
4483 capture_opts_trim_ring_num_files(&global_capture_opts);
4485 /* flush stderr prior to starting the main capture loop */
4488 /* Now start the capture. */
4489 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4493 /* capture failed */
4496 return 0; /* never here, make compiler happy */
4501 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4502 const char *message, gpointer user_data _U_)
4509 /* ignore log message, if log_level isn't interesting */
4510 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4511 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4516 switch(log_level & G_LOG_LEVEL_MASK) {
4517 case G_LOG_LEVEL_ERROR:
4520 case G_LOG_LEVEL_CRITICAL:
4523 case G_LOG_LEVEL_WARNING:
4526 case G_LOG_LEVEL_MESSAGE:
4529 case G_LOG_LEVEL_INFO:
4532 case G_LOG_LEVEL_DEBUG:
4536 fprintf(stderr, "unknown log_level %d\n", log_level);
4538 g_assert_not_reached();
4541 /* Generate the output message */
4542 if (log_level & G_LOG_LEVEL_MESSAGE) {
4543 /* normal user messages without additional infos */
4544 msg = g_strdup_printf("%s\n", message);
4546 /* create a "timestamp" */
4548 today = localtime(&curr);
4550 /* info/debug messages with additional infos */
4552 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4553 today->tm_hour, today->tm_min, today->tm_sec,
4554 log_domain != NULL ? log_domain : "",
4557 msg = g_strdup_printf("Time not representable %8s %s %s\n",
4558 log_domain != NULL ? log_domain : "",
4562 /* DEBUG & INFO msgs (if we're debugging today) */
4563 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4564 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4565 #ifdef DEBUG_DUMPCAP
4566 fprintf(stderr, "%s", msg);
4569 #ifdef DEBUG_CHILD_DUMPCAP
4570 fprintf(debug_log, "%s", msg);
4578 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4579 /* to parent especially formatted if dumpcap running as child. */
4580 if (capture_child) {
4581 sync_pipe_errmsg_to_parent(2, msg, "");
4583 fprintf(stderr, "%s", msg);
4590 /****************************************************************************************************************/
4591 /* indication report routines */
4595 report_packet_count(unsigned int packet_count)
4597 char tmp[SP_DECISIZE+1+1];
4598 static unsigned int count = 0;
4600 if (capture_child) {
4601 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
4602 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4603 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4605 count += packet_count;
4606 fprintf(stderr, "\rPackets: %u ", count);
4607 /* stderr could be line buffered */
4613 report_new_capture_file(const char *filename)
4615 if (capture_child) {
4616 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4617 pipe_write_block(2, SP_FILE, filename);
4621 * Prevent a SIGINFO handler from writing to the standard error
4622 * while we're doing so; instead, have it just set a flag telling
4623 * us to print that information when we're done.
4626 #endif /* SIGINFO */
4627 fprintf(stderr, "File: %s\n", filename);
4628 /* stderr could be line buffered */
4633 * Allow SIGINFO handlers to write.
4638 * If a SIGINFO handler asked us to write out capture counts, do so.
4641 report_counts_for_siginfo();
4642 #endif /* SIGINFO */
4647 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4649 interface_options interface_opts;
4650 char tmp[MSG_MAX_LENGTH+1+6];
4652 if (i < capture_opts->ifaces->len) {
4653 if (capture_child) {
4654 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4655 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4656 pipe_write_block(2, SP_BAD_FILTER, tmp);
4659 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
4660 * the error message below.
4662 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
4664 "Invalid capture filter \"%s\" for interface '%s'.\n"
4666 "That string isn't a valid capture filter (%s).\n"
4667 "See the User's Guide for a description of the capture filter syntax.",
4668 interface_opts.cfilter, interface_opts.name, errmsg);
4674 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4676 if (capture_child) {
4677 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4678 "Primary Error: %s", error_msg);
4679 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4680 "Secondary Error: %s", secondary_error_msg);
4681 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4683 cmdarg_err("%s", error_msg);
4684 if (secondary_error_msg[0] != '\0')
4685 cmdarg_err_cont("%s", secondary_error_msg);
4690 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
4692 char tmp[SP_DECISIZE+1+1];
4693 guint32 total_drops = pcap_drops + drops + flushed;
4695 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
4697 if (capture_child) {
4698 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4699 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
4700 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
4701 /* XXX: Need to provide interface id, changes to consumers required. */
4702 pipe_write_block(2, SP_DROPS, tmp);
4705 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
4706 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
4707 received ? 100.0 * received / (received + total_drops) : 0.0);
4708 /* stderr could be line buffered */
4714 /************************************************************************************************/
4715 /* signal_pipe handling */
4720 signal_pipe_check_running(void)
4722 /* any news from our parent? -> just stop the capture */
4726 /* if we are running standalone, no check required */
4727 if (!capture_child) {
4731 if (!sig_pipe_name || !sig_pipe_handle) {
4732 /* This shouldn't happen */
4733 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4734 "Signal pipe: No name or handle");
4739 * XXX - We should have the process ID of the parent (from the "-Z" flag)
4740 * at this point. Should we check to see if the parent is still alive,
4741 * e.g. by using OpenProcess?
4744 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
4746 if (!result || avail > 0) {
4747 /* peek failed or some bytes really available */
4748 /* (if not piping from stdin this would fail) */
4749 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4750 "Signal pipe: Stop capture: %s", sig_pipe_name);
4751 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4752 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
4753 sig_pipe_handle, result, avail);
4756 /* pipe ok and no bytes available */
4763 * Editor modelines - https://www.wireshark.org/tools/modelines.html
4768 * indent-tabs-mode: nil
4771 * vi: set shiftwidth=4 tabstop=8 expandtab:
4772 * :indentSize=4:tabSize=8:noTabs=true: