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,
270 * A source of packets from which we're capturing.
272 typedef struct _capture_src {
277 #ifdef MUST_DO_SELECT
278 int pcap_fd; /**< pcap file descriptor */
285 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
286 /**< capture pipe (unix only "input file") */
287 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
288 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
289 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
290 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
292 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
294 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
295 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
296 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
297 char * cap_pipe_databuf; /**< Pointer to the data buffer we've allocated */
299 char * cap_pipe_buf; /**< Pointer to the buffer we read into */
300 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
301 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
303 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
304 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
306 cap_pipe_state_t cap_pipe_state;
307 cap_pipe_err_t cap_pipe_err;
310 GMutex *cap_pipe_read_mtx;
311 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
316 * Global capture loop state.
318 typedef struct _loop_data {
320 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
321 int err; /**< if non-zero, error seen while capturing */
322 gint packet_count; /**< Number of packets we have already captured */
323 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
324 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
326 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
328 GArray *pcaps; /**< Array of capture_src's on which we're capturing */
332 guint64 bytes_written;
333 guint32 autostop_files;
336 typedef struct _pcap_queue_element {
337 capture_src *pcap_src;
338 struct pcap_pkthdr phdr;
340 } pcap_queue_element;
343 * Standard secondary message for unexpected errors.
345 static const char please_report[] =
346 "Please report this to the Wireshark developers.\n"
347 "https://bugs.wireshark.org/\n"
348 "(This is not a crash; please do not report it as such.)";
351 * This needs to be static, so that the SIGINT handler can clear the "go"
354 static loop_data global_ld;
357 * Timeout, in milliseconds, for reads from the stream of captured packets
358 * from a capture device.
360 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
361 * 64-bit applications, with sub-second timeouts not to work. The bug is
362 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
364 #if defined(__APPLE__) && defined(__LP64__)
365 static gboolean need_timeout_workaround;
367 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
369 #define CAP_READ_TIMEOUT 250
373 * Timeout, in microseconds, for reads from the stream of captured packets
374 * from a pipe. Pipes don't have the same problem that BPF devices do
375 * in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
376 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
377 * of the offending versions of Snow Leopard.
379 * On Windows this value is converted to milliseconds and passed to
380 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
381 * will return immediately.
384 #define PIPE_READ_TIMEOUT 100000
386 #define PIPE_READ_TIMEOUT 250000
389 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
392 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
393 const char *message, gpointer user_data _U_);
395 /* capture related options */
396 static capture_options global_capture_opts;
397 static gboolean quiet = FALSE;
398 static gboolean use_threads = FALSE;
399 static guint64 start_time;
401 static void capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
403 static void capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
405 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
406 int err, gboolean is_close);
408 static void WS_NORETURN exit_main(int err);
410 static void report_new_capture_file(const char *filename);
411 static void report_packet_count(unsigned int packet_count);
412 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
413 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
414 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
416 #define MSG_MAX_LENGTH 4096
418 /* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
420 create_timestamp(void) {
430 * Current time, represented as 100-nanosecond intervals since
431 * January 1, 1601, 00:00:00 UTC.
433 * I think DWORD might be signed, so cast both parts of "now"
434 * to guint32 so that the sign bit doesn't get treated specially.
436 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
437 * might want to use instead.
439 GetSystemTimeAsFileTime(&now);
440 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
441 (guint32)now.dwLowDateTime;
444 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
450 * Subtract difference, in microseconds, between January 1, 1601
451 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
453 timestamp -= G_GUINT64_CONSTANT(11644473600000000);
456 * Current time, represented as seconds and microseconds since
457 * January 1, 1970, 00:00:00 UTC.
459 gettimeofday(&now, NULL);
462 * Convert to delta in microseconds.
464 timestamp = (guint64)(now.tv_sec) * 1000000 +
465 (guint64)(now.tv_usec);
471 print_usage(FILE *output)
473 fprintf(output, "\nUsage: dumpcap [options] ...\n");
474 fprintf(output, "\n");
475 fprintf(output, "Capture interface:\n");
476 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
477 " or for remote capturing, use one of these formats:\n"
478 " rpcap://<host>/<interface>\n"
479 " TCP@<host>:<port>\n");
480 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
481 fprintf(output, " -s <snaplen> packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE);
482 fprintf(output, " -p don't capture in promiscuous mode\n");
483 #ifdef HAVE_PCAP_CREATE
484 fprintf(output, " -I capture in monitor mode, if available\n");
486 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
487 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
489 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
490 fprintf(output, " -D print list of interfaces and exit\n");
491 fprintf(output, " -L print list of link-layer types of iface and exit\n");
492 #ifdef HAVE_BPF_IMAGE
493 fprintf(output, " -d print generated BPF code for capture filter\n");
495 fprintf(output, " -k set channel on wifi interface:\n"
496 " <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
497 fprintf(output, " -S print statistics for each interface once per second\n");
498 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
499 fprintf(output, "\n");
500 #ifdef HAVE_PCAP_REMOTE
501 fprintf(output, "RPCAP options:\n");
502 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
503 fprintf(output, " -u use UDP for RPCAP data transfer\n");
504 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
505 #ifdef HAVE_PCAP_SETSAMPLING
506 fprintf(output, " -m <sampling type> use packet sampling\n");
507 fprintf(output, " count:NUM - capture one packet of every NUM\n");
508 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
511 fprintf(output, "Stop conditions:\n");
512 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
513 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
514 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
515 fprintf(output, " files:NUM - stop after NUM files\n");
516 /*fprintf(output, "\n");*/
517 fprintf(output, "Output (files):\n");
518 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
519 fprintf(output, " -g enable group read access on the output file(s)\n");
520 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
521 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
522 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
523 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
524 fprintf(output, " -P use libpcap format instead of pcapng\n");
525 fprintf(output, " --capture-comment <comment>\n");
526 fprintf(output, " add a capture comment to the output file\n");
527 fprintf(output, " (only for pcapng)\n");
528 fprintf(output, "\n");
529 fprintf(output, "Miscellaneous:\n");
530 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
531 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
532 fprintf(output, " within dumpcap\n");
533 fprintf(output, " -t use a separate thread per interface\n");
534 fprintf(output, " -q don't report packet capture counts\n");
535 fprintf(output, " -v print version information and exit\n");
536 fprintf(output, " -h display this help and exit\n");
537 fprintf(output, "\n");
539 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
540 fprintf(output, "You might want to reset it\n");
541 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
542 fprintf(output, "\n");
544 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
545 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
546 fprintf(output, "\n");
547 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
551 * Report an error in command-line arguments.
552 * If we're a capture child, send a message back to the parent, otherwise
556 dumpcap_cmdarg_err(const char *fmt, va_list ap)
560 /* Generate a 'special format' message back to parent */
561 msg = g_strdup_vprintf(fmt, ap);
562 sync_pipe_errmsg_to_parent(2, msg, "");
565 fprintf(stderr, "dumpcap: ");
566 vfprintf(stderr, fmt, ap);
567 fprintf(stderr, "\n");
572 * Report additional information for an error in command-line arguments.
573 * If we're a capture child, send a message back to the parent, otherwise
577 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
581 msg = g_strdup_vprintf(fmt, ap);
582 sync_pipe_errmsg_to_parent(2, msg, "");
585 vfprintf(stderr, fmt, ap);
586 fprintf(stderr, "\n");
592 #if 0 /* Set to enable capability debugging */
593 /* see 'man cap_to_text()' for explanation of output */
594 /* '=' means 'all= ' ie: no capabilities */
595 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
597 print_caps(const char *pfx) {
598 cap_t caps = cap_get_proc();
599 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
600 "%s: EUID: %d Capabilities: %s", pfx,
601 geteuid(), cap_to_text(caps, NULL));
604 print_caps(const char *pfx _U_) {
609 relinquish_all_capabilities(void)
611 /* Drop any and all capabilities this process may have. */
612 /* Allowed whether or not process has any privileges. */
613 cap_t caps = cap_init(); /* all capabilities initialized to off */
614 print_caps("Pre-clear");
615 if (cap_set_proc(caps)) {
616 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
618 print_caps("Post-clear");
624 get_capture_device_open_failure_messages(const char *open_err_str,
626 char *errmsg, size_t errmsg_len,
627 char *secondary_errmsg,
628 size_t secondary_errmsg_len)
631 const char *libpcap_warn;
632 static const char ppamsg[] = "can't find PPA for ";
635 g_snprintf(errmsg, (gulong) errmsg_len,
636 "The capture session could not be initiated on interface '%s' (%s).",
637 iface, open_err_str);
640 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
642 "In order to capture packets, WinPcap must be installed; see\n"
644 " https://www.winpcap.org/\n"
646 "for a downloadable version of WinPcap and for instructions on how to install\n"
649 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
651 "Please check that \"%s\" is the proper interface.\n"
654 "Help can be found on the following pages:\n"
656 " https://wiki.wireshark.org/WinPcap\n"
657 " https://wiki.wireshark.org/CaptureSetup\n",
661 /* If we got a "can't find PPA for X" message, warn the user (who
662 is running dumpcap on HP-UX) that they don't have a version of
663 libpcap that properly handles HP-UX (libpcap 0.6.x and later
664 versions, which properly handle HP-UX, say "can't find /dev/dlpi
665 PPA for X" rather than "can't find PPA for X"). */
666 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
669 "You are running (T)Wireshark with a version of the libpcap library\n"
670 "that doesn't handle HP-UX network devices well; this means that\n"
671 "(T)Wireshark may not be able to capture packets.\n"
673 "To fix this, you should install libpcap 0.6.2, or a later version\n"
674 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
675 "packaged binary form from the Software Porting And Archive Centre\n"
676 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
677 "at the URL lists a number of mirror sites.";
681 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
682 "Please check to make sure you have sufficient permissions, and that you have "
683 "the proper interface or pipe specified.%s", libpcap_warn);
688 compile_capture_filter(const char *iface, pcap_t *pcap_h,
689 struct bpf_program *fcode, const char *cfilter)
691 bpf_u_int32 netnum, netmask;
692 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
694 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
696 * Well, we can't get the netmask for this interface; it's used
697 * only for filters that check for broadcast IP addresses, so
698 * we just punt and use 0. It might be nice to warn the user,
699 * but that's a pain in a GUI application, as it'd involve popping
700 * up a message box, and it's not clear how often this would make
701 * a difference (only filters that check for IP broadcast addresses
705 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
710 * Sigh. Older versions of libpcap don't properly declare the
711 * third argument to pcap_compile() as a const pointer. Cast
715 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
721 #ifdef HAVE_BPF_IMAGE
723 show_filter_code(capture_options *capture_opts)
725 interface_options interface_opts;
727 gchar open_err_str[PCAP_ERRBUF_SIZE];
728 char errmsg[MSG_MAX_LENGTH+1];
729 char secondary_errmsg[MSG_MAX_LENGTH+1];
730 struct bpf_program fcode;
731 struct bpf_insn *insn;
735 for (j = 0; j < capture_opts->ifaces->len; j++) {
736 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
737 pcap_h = open_capture_device(capture_opts, &interface_opts,
738 CAP_READ_TIMEOUT, &open_err_str);
739 if (pcap_h == NULL) {
740 /* Open failed; get messages */
741 get_capture_device_open_failure_messages(open_err_str,
743 errmsg, sizeof errmsg,
745 sizeof secondary_errmsg);
746 /* And report them */
747 report_capture_error(errmsg, secondary_errmsg);
751 /* Set the link-layer type. */
752 if (!set_pcap_datalink(pcap_h, interface_opts.linktype, interface_opts.name,
753 errmsg, sizeof errmsg,
754 secondary_errmsg, sizeof secondary_errmsg)) {
756 report_capture_error(errmsg, secondary_errmsg);
760 /* OK, try to compile the capture filter. */
761 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
762 interface_opts.cfilter)) {
764 report_cfilter_error(capture_opts, j, errmsg);
769 /* Now print the filter code. */
770 insn = fcode.bf_insns;
772 for (i = 0; i < fcode.bf_len; insn++, i++)
773 printf("%s\n", bpf_image(insn, i));
775 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
776 /* to remove any suid privileges. */
777 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
778 /* (euid/egid have already previously been set to ruid/rgid. */
779 /* (See comment in main() for details) */
781 relinquish_special_privs_perm();
783 relinquish_all_capabilities();
786 /* Let our parent know we succeeded. */
787 pipe_write_block(2, SP_SUCCESS, NULL);
794 * capture_interface_list() is expected to do the right thing to get
795 * a list of interfaces.
797 * In most of the programs in the Wireshark suite, "the right thing"
798 * is to run dumpcap and ask it for the list, because dumpcap may
799 * be the only program in the suite with enough privileges to get
802 * In dumpcap itself, however, we obviously can't run dumpcap to
803 * ask for the list. Therefore, our capture_interface_list() should
804 * just call get_interface_list().
807 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
809 return get_interface_list(err, err_str);
812 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
814 * Output a machine readable list of the interfaces
815 * This list is retrieved by the sync_interface_list_open() function
816 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
819 print_machine_readable_interfaces(GList *if_list)
826 char addr_str[ADDRSTRLEN];
829 /* Let our parent know we succeeded. */
830 pipe_write_block(2, SP_SUCCESS, NULL);
833 i = 1; /* Interface id number */
834 for (if_entry = g_list_first(if_list); if_entry != NULL;
835 if_entry = g_list_next(if_entry)) {
836 if_info = (if_info_t *)if_entry->data;
837 printf("%d. %s\t", i++, if_info->name);
840 * Print the contents of the if_entry struct in a parseable format.
841 * Each if_entry element is tab-separated. Addresses are comma-
844 /* XXX - Make sure our description doesn't contain a tab */
845 if (if_info->vendor_description != NULL)
846 printf("%s\t", if_info->vendor_description);
850 /* XXX - Make sure our friendly name doesn't contain a tab */
851 if (if_info->friendly_name != NULL)
852 printf("%s\t", if_info->friendly_name);
856 printf("%i\t", if_info->type);
858 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
859 addr = g_slist_next(addr)) {
860 if (addr != g_slist_nth(if_info->addrs, 0))
863 if_addr = (if_addr_t *)addr->data;
864 switch(if_addr->ifat_type) {
866 if (ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str,
868 printf("%s", addr_str);
870 printf("<unknown IPv4>");
874 if (ws_inet_ntop6(&if_addr->addr.ip6_addr,
875 addr_str, ADDRSTRLEN)) {
876 printf("%s", addr_str);
878 printf("<unknown IPv6>");
882 printf("<type unknown %i>", if_addr->ifat_type);
886 if (if_info->loopback)
887 printf("\tloopback");
891 printf("\t%s", if_info->extcap);
898 * If you change the machine-readable output format of this function,
899 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
902 print_machine_readable_if_capabilities(if_capabilities_t *caps)
905 data_link_info_t *data_link_info;
906 const gchar *desc_str;
909 /* Let our parent know we succeeded. */
910 pipe_write_block(2, SP_SUCCESS, NULL);
913 if (caps->can_set_rfmon)
917 for (lt_entry = caps->data_link_types; lt_entry != NULL;
918 lt_entry = g_list_next(lt_entry)) {
919 data_link_info = (data_link_info_t *)lt_entry->data;
920 if (data_link_info->description != NULL)
921 desc_str = data_link_info->description;
923 desc_str = "(not supported)";
924 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
934 /* Print the number of packets captured for each interface until we're killed. */
936 print_statistics_loop(gboolean machine_readable)
938 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
944 char errbuf[PCAP_ERRBUF_SIZE];
947 if_list = get_interface_list(&err, &err_str);
948 if (if_list == NULL) {
950 cmdarg_err("There are no interfaces on which a capture can be done");
952 cmdarg_err("%s", err_str);
958 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
959 if_info = (if_info_t *)if_entry->data;
962 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
963 * connections. We avoid collecting stats on them.
965 if (!strncmp(if_info->name, "nf", 2)) {
966 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
972 #ifdef HAVE_PCAP_OPEN
973 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
975 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
979 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
980 if_stat->name = g_strdup(if_info->name);
982 stat_list = g_list_append(stat_list, if_stat);
987 cmdarg_err("There are no interfaces on which a capture can be done");
992 /* Let our parent know we succeeded. */
993 pipe_write_block(2, SP_SUCCESS, NULL);
996 if (!machine_readable) {
997 printf("%-15s %10s %10s\n", "Interface", "Received",
1001 global_ld.go = TRUE;
1002 while (global_ld.go) {
1003 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1004 if_stat = (if_stat_t *)stat_entry->data;
1005 pcap_stats(if_stat->pch, &ps);
1007 if (!machine_readable) {
1008 printf("%-15s %10u %10u\n", if_stat->name,
1009 ps.ps_recv, ps.ps_drop);
1011 printf("%s\t%u\t%u\n", if_stat->name,
1012 ps.ps_recv, ps.ps_drop);
1017 /* If we have a dummy signal pipe check it */
1018 if (!signal_pipe_check_running()) {
1019 global_ld.go = FALSE;
1027 /* XXX - Not reached. Should we look for 'q' in stdin? */
1028 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1029 if_stat = (if_stat_t *)stat_entry->data;
1030 pcap_close(if_stat->pch);
1031 g_free(if_stat->name);
1034 g_list_free(stat_list);
1035 free_interface_list(if_list);
1043 capture_cleanup_handler(DWORD dwCtrlType)
1045 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1046 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1047 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1048 like SIGTERM at least when the machine's shutting down.
1050 For now, if we're running as a command rather than a capture child,
1051 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1052 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1053 in that way on UN*X.
1055 If we're not running as a capture child, we might be running as
1056 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1057 user logs out. (XXX - can we explicitly check whether we're
1058 running as a service?) */
1060 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1061 "Console: Control signal");
1062 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1063 "Console: Control signal, CtrlType: %u", dwCtrlType);
1065 /* Keep capture running if we're a service and a user logs off */
1066 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1067 capture_loop_stop();
1075 capture_cleanup_handler(int signum _U_)
1077 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1078 SIGTERM. We assume that if the user wanted it to keep running
1079 after they logged out, they'd have nohupped it. */
1081 /* Note: don't call g_log() in the signal handler: if we happened to be in
1082 * g_log() in process context when the signal came in, g_log will detect
1083 * the "recursion" and abort.
1086 capture_loop_stop();
1092 report_capture_count(gboolean reportit)
1094 /* Don't print this if we're a capture child. */
1095 if (!capture_child && reportit) {
1096 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packet_count);
1097 /* stderr could be line buffered */
1105 report_counts_for_siginfo(void)
1107 report_capture_count(quiet);
1108 infoprint = FALSE; /* we just reported it */
1112 report_counts_siginfo(int signum _U_)
1114 int sav_errno = errno;
1116 /* If we've been told to delay printing, just set a flag asking
1117 that we print counts (if we're supposed to), otherwise print
1118 the count of packets captured (if we're supposed to). */
1122 report_counts_for_siginfo();
1125 #endif /* SIGINFO */
1128 exit_main(int status)
1131 /* Shutdown windows sockets */
1134 /* can be helpful for debugging */
1135 #ifdef DEBUG_DUMPCAP
1136 printf("Press any key\n");
1142 capture_opts_cleanup(&global_capture_opts);
1148 * If we were linked with libcap (not related to libpcap), make sure we have
1149 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1150 * (See comment in main() for details)
1153 relinquish_privs_except_capture(void)
1155 /* If 'started_with_special_privs' (ie: suid) then enable for
1156 * ourself the NET_ADMIN and NET_RAW capabilities and then
1157 * drop our suid privileges.
1159 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1160 * stuff we don't need (and shouldn't have).
1161 * CAP_NET_RAW: Packet capture (raw sockets).
1164 if (started_with_special_privs()) {
1165 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1166 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1168 cap_t caps = cap_init(); /* all capabilities initialized to off */
1170 print_caps("Pre drop, pre set");
1172 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1173 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1176 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1177 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1179 if (cap_set_proc(caps)) {
1180 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1182 print_caps("Pre drop, post set");
1184 relinquish_special_privs_perm();
1186 print_caps("Post drop, pre set");
1187 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1188 if (cap_set_proc(caps)) {
1189 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1191 print_caps("Post drop, post set");
1197 #endif /* HAVE_LIBCAP */
1199 /* Take care of byte order in the libpcap headers read from pipes.
1200 * (function taken from wiretap/libpcap.c) */
1202 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1205 /* Byte-swap the record header fields. */
1206 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1207 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1208 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1209 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1212 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1213 swapped, in order to match the BPF header layout.
1215 Unfortunately, some files were, according to a comment in the "libpcap"
1216 source, written with version 2.3 in their headers but without the
1217 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1218 would make no sense - we assume that we need to swap them. */
1219 if (hdr->version_major == 2 &&
1220 (hdr->version_minor < 3 ||
1221 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1224 temp = rechdr->orig_len;
1225 rechdr->orig_len = rechdr->incl_len;
1226 rechdr->incl_len = temp;
1230 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1234 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1238 return recv(pipe_fd, buf, (int)sz, 0);
1243 return ws_read(pipe_fd, buf, sz);
1249 * Thread function that reads from a pipe and pushes the data
1250 * to the main application thread.
1253 * XXX Right now we use async queues for basic signaling. The main thread
1254 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1255 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1256 * Iff the read is successful cap_pipe_read pushes an item onto
1257 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1258 * the queues themselves (yet).
1260 * We might want to move some of the cap_pipe_dispatch logic here so that
1261 * we can let cap_thread_read run independently, queuing up multiple reads
1262 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1264 static void *cap_thread_read(void *arg)
1266 capture_src *pcap_src;
1269 DWORD b, last_err, bytes_read;
1275 pcap_src = (capture_src *)arg;
1276 while (pcap_src->cap_pipe_err == PIPOK) {
1277 g_async_queue_pop(pcap_src->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1278 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1280 while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1281 if ((pcap_src->from_cap_socket)
1287 b = cap_pipe_read(pcap_src->cap_pipe_fd, pcap_src->cap_pipe_buf+bytes_read,
1288 pcap_src->cap_pipe_bytes_to_read - bytes_read, pcap_src->from_cap_socket);
1291 pcap_src->cap_pipe_err = PIPEOF;
1295 pcap_src->cap_pipe_err = PIPERR;
1306 /* If we try to use read() on a named pipe on Windows with partial
1307 * data it appears to return EOF.
1309 res = ReadFile(pcap_src->cap_pipe_h, pcap_src->cap_pipe_buf+bytes_read,
1310 pcap_src->cap_pipe_bytes_to_read - bytes_read,
1315 last_err = GetLastError();
1316 if (last_err == ERROR_MORE_DATA) {
1318 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1319 pcap_src->cap_pipe_err = PIPEOF;
1323 pcap_src->cap_pipe_err = PIPERR;
1326 } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1327 pcap_src->cap_pipe_err = PIPEOF;
1334 pcap_src->cap_pipe_bytes_read = bytes_read;
1335 if (pcap_src->cap_pipe_bytes_read >= pcap_src->cap_pipe_bytes_to_read) {
1336 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1338 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1344 /* Provide select() functionality for a single file descriptor
1345 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1347 * Returns the same values as select.
1350 cap_pipe_select(int pipe_fd)
1353 struct timeval timeout;
1356 FD_SET(pipe_fd, &rfds);
1358 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1359 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1361 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1364 #define DEF_TCP_PORT 19000
1367 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, int errmsgl)
1369 char *sockname = pipename + 4;
1370 struct sockaddr_in sa;
1377 memset(&sa, 0, sizeof(sa));
1379 p = strchr(sockname, ':');
1381 len = strlen(sockname);
1382 port = DEF_TCP_PORT;
1386 port = strtoul(p + 1, &p, 10);
1387 if (*p || port > 65535) {
1396 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1398 if (!ws_inet_pton4(buf, (guint32 *)&sa.sin_addr)) {
1402 sa.sin_family = AF_INET;
1403 sa.sin_port = g_htons((u_short)port);
1405 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1406 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1408 LPTSTR errorText = NULL;
1411 lastError = WSAGetLastError();
1412 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1413 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1414 FORMAT_MESSAGE_IGNORE_INSERTS,
1415 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1416 (LPTSTR)&errorText, 0, NULL);
1418 g_snprintf(errmsg, errmsgl,
1419 "The capture session could not be initiated due to the socket error: \n"
1421 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1423 LocalFree(errorText);
1425 " %d: %s", errno, g_strerror(errno));
1427 pcap_src->cap_pipe_err = PIPERR;
1430 cap_pipe_close(fd, TRUE);
1434 pcap_src->from_cap_socket = TRUE;
1438 g_snprintf(errmsg, errmsgl,
1439 "The capture session could not be initiated because\n"
1440 "\"%s\" is not a valid socket specification", pipename);
1441 pcap_src->cap_pipe_err = PIPERR;
1445 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1449 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1453 closesocket(pipe_fd);
1460 /* Mimic pcap_open_live() for pipe captures
1462 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1463 * open it, and read the header.
1465 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1466 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1468 cap_pipe_open_live(char *pipename,
1469 capture_src *pcap_src,
1470 struct pcap_hdr *hdr,
1471 char *errmsg, int errmsgl)
1474 ws_statb64 pipe_stat;
1475 struct sockaddr_un sa;
1480 char* extcap_pipe_name;
1484 gboolean extcap_pipe = FALSE;
1485 interface_options interface_opts;
1488 int fd = -1, sel_ret;
1491 pcap_src->cap_pipe_fd = -1;
1493 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1496 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1499 * XXX - this blocks until a pcap per-file header has been written to
1500 * the pipe, so it could block indefinitely.
1502 if (strcmp(pipename, "-") == 0) {
1504 fd = 0; /* read from stdin */
1506 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1508 } else if (!strncmp(pipename, "TCP@", 4)) {
1509 if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1515 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
1520 if ( g_strrstr(interface_opts.name, EXTCAP_PIPE_PREFIX) != NULL )
1524 if (ws_stat64(pipename, &pipe_stat) < 0) {
1525 if (errno == ENOENT || errno == ENOTDIR)
1526 pcap_src->cap_pipe_err = PIPNEXIST;
1528 g_snprintf(errmsg, errmsgl,
1529 "The capture session could not be initiated "
1530 "due to error getting information on pipe/socket: %s.", g_strerror(errno));
1531 pcap_src->cap_pipe_err = PIPERR;
1535 if (S_ISFIFO(pipe_stat.st_mode)) {
1536 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1538 g_snprintf(errmsg, errmsgl,
1539 "The capture session could not be initiated "
1540 "due to error on pipe open: %s.", g_strerror(errno));
1541 pcap_src->cap_pipe_err = PIPERR;
1544 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1545 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1547 g_snprintf(errmsg, errmsgl,
1548 "The capture session could not be initiated "
1549 "due to error on socket create: %s.", g_strerror(errno));
1550 pcap_src->cap_pipe_err = PIPERR;
1553 sa.sun_family = AF_UNIX;
1555 * The Single UNIX Specification says:
1557 * The size of sun_path has intentionally been left undefined.
1558 * This is because different implementations use different sizes.
1559 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1560 * of 104. Since most implementations originate from BSD versions,
1561 * the size is typically in the range 92 to 108.
1563 * Applications should not assume a particular length for sun_path
1564 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1568 * The <sys/un.h> header shall define the sockaddr_un structure,
1569 * which shall include at least the following members:
1571 * sa_family_t sun_family Address family.
1572 * char sun_path[] Socket pathname.
1574 * so we assume that it's an array, with a specified size,
1575 * and that the size reflects the maximum path length.
1577 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1578 /* Path name too long */
1579 g_snprintf(errmsg, errmsgl,
1580 "The capture session coud not be initiated "
1581 "due to error on socket connect: Path name too long.");
1582 pcap_src->cap_pipe_err = PIPERR;
1586 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1588 g_snprintf(errmsg, errmsgl,
1589 "The capture session coud not be initiated "
1590 "due to error on socket connect: %s.", g_strerror(errno));
1591 pcap_src->cap_pipe_err = PIPERR;
1596 if (S_ISCHR(pipe_stat.st_mode)) {
1598 * Assume the user specified an interface on a system where
1599 * interfaces are in /dev. Pretend we haven't seen it.
1601 pcap_src->cap_pipe_err = PIPNEXIST;
1603 g_snprintf(errmsg, errmsgl,
1604 "The capture session could not be initiated because\n"
1605 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1606 pcap_src->cap_pipe_err = PIPERR;
1612 #define PIPE_STR "\\pipe\\"
1613 /* Under Windows, named pipes _must_ have the form
1614 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1616 pncopy = g_strdup(pipename);
1617 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1618 pos = strchr(pncopy + 3, '\\');
1619 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1626 g_snprintf(errmsg, errmsgl,
1627 "The capture session could not be initiated because\n"
1628 "\"%s\" is neither an interface nor a pipe.", pipename);
1629 pcap_src->cap_pipe_err = PIPNEXIST;
1633 extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
1634 extcap_pipe = strstr(interface_opts.name, extcap_pipe_name) ? TRUE : FALSE;
1635 g_free(extcap_pipe_name);
1638 /* Wait for the pipe to appear */
1643 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1646 pcap_src->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1647 OPEN_EXISTING, 0, NULL);
1649 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE)
1652 if (GetLastError() != ERROR_PIPE_BUSY) {
1653 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1654 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1655 g_snprintf(errmsg, errmsgl,
1656 "The capture session on \"%s\" could not be started "
1657 "due to error on pipe open: %s (error %d).",
1658 pipename, utf_16to8(err_str), GetLastError());
1660 pcap_src->cap_pipe_err = PIPERR;
1664 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1665 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1666 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1667 g_snprintf(errmsg, errmsgl,
1668 "The capture session on \"%s\" timed out during "
1669 "pipe open: %s (error %d).",
1670 pipename, utf_16to8(err_str), GetLastError());
1672 pcap_src->cap_pipe_err = PIPERR;
1679 pcap_src->from_cap_pipe = TRUE;
1680 pcap_src->cap_pipe_databuf = (guchar*)g_malloc(WTAP_MAX_PACKET_SIZE);
1683 if (pcap_src->from_cap_socket)
1686 /* read the pcap header */
1688 while (bytes_read < sizeof magic) {
1690 g_snprintf(errmsg, errmsgl, "Invalid file descriptor.");
1694 sel_ret = cap_pipe_select(fd);
1696 g_snprintf(errmsg, errmsgl,
1697 "Unexpected error from select: %s.", g_strerror(errno));
1699 } else if (sel_ret > 0) {
1700 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1701 sizeof magic-bytes_read,
1702 pcap_src->from_cap_socket);
1704 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1705 if (extcap_pipe && b <= 0)
1710 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1712 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1722 #if GLIB_CHECK_VERSION(2,31,0)
1723 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
1725 g_thread_create(&cap_thread_read, pcap_src, FALSE, NULL);
1728 pcap_src->cap_pipe_buf = (char *) &magic;
1729 pcap_src->cap_pipe_bytes_read = 0;
1730 pcap_src->cap_pipe_bytes_to_read = sizeof(magic);
1731 /* We don't have to worry about cap_pipe_read_mtx here */
1732 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1733 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1734 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1735 if (pcap_src->cap_pipe_bytes_read <= 0 && extcap_pipe)
1738 if (pcap_src->cap_pipe_bytes_read <= 0) {
1739 if (pcap_src->cap_pipe_bytes_read == 0)
1740 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1742 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1751 case PCAP_NSEC_MAGIC:
1752 /* Host that wrote it has our byte order, and was running
1753 a program using either standard or ss990417 libpcap. */
1754 pcap_src->cap_pipe_byte_swapped = FALSE;
1755 pcap_src->cap_pipe_modified = FALSE;
1756 pcap_src->ts_nsec = magic == PCAP_NSEC_MAGIC;
1758 case PCAP_MODIFIED_MAGIC:
1759 /* Host that wrote it has our byte order, but was running
1760 a program using either ss990915 or ss991029 libpcap. */
1761 pcap_src->cap_pipe_byte_swapped = FALSE;
1762 pcap_src->cap_pipe_modified = TRUE;
1764 case PCAP_SWAPPED_MAGIC:
1765 case PCAP_SWAPPED_NSEC_MAGIC:
1766 /* Host that wrote it has a byte order opposite to ours,
1767 and was running a program using either standard or
1768 ss990417 libpcap. */
1769 pcap_src->cap_pipe_byte_swapped = TRUE;
1770 pcap_src->cap_pipe_modified = FALSE;
1771 pcap_src->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
1773 case PCAP_SWAPPED_MODIFIED_MAGIC:
1774 /* Host that wrote it out has a byte order opposite to
1775 ours, and was running a program using either ss990915
1776 or ss991029 libpcap. */
1777 pcap_src->cap_pipe_byte_swapped = TRUE;
1778 pcap_src->cap_pipe_modified = TRUE;
1780 case BLOCK_TYPE_SHB:
1781 /* This isn't pcap, it's pcapng. We don't yet support
1783 g_snprintf(errmsg, errmsgl, "Capturing from a pipe doesn't support pcapng format.");
1786 /* Not a pcap type we know about, or not pcap at all. */
1787 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format or not libpcap data.");
1792 if (pcap_src->from_cap_socket)
1795 /* Read the rest of the header */
1797 while (bytes_read < sizeof(struct pcap_hdr)) {
1798 sel_ret = cap_pipe_select(fd);
1800 g_snprintf(errmsg, errmsgl,
1801 "Unexpected error from select: %s.", g_strerror(errno));
1803 } else if (sel_ret > 0) {
1804 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
1805 sizeof(struct pcap_hdr) - bytes_read,
1806 pcap_src->from_cap_socket);
1809 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1811 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s.",
1821 pcap_src->cap_pipe_buf = (char *) hdr;
1822 pcap_src->cap_pipe_bytes_read = 0;
1823 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1824 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1825 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1826 if (pcap_src->cap_pipe_bytes_read <= 0) {
1827 if (pcap_src->cap_pipe_bytes_read == 0)
1828 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1830 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s.",
1837 if (pcap_src->cap_pipe_byte_swapped) {
1838 /* Byte-swap the header fields about which we care. */
1839 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
1840 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
1841 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
1842 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
1844 pcap_src->linktype = hdr->network;
1846 if (hdr->version_major < 2) {
1847 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1851 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
1852 pcap_src->cap_pipe_err = PIPOK;
1853 pcap_src->cap_pipe_fd = fd;
1857 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1858 pcap_src->cap_pipe_err = PIPERR;
1859 cap_pipe_close(fd, pcap_src->from_cap_socket);
1860 pcap_src->cap_pipe_fd = -1;
1862 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1867 /* We read one record from the pipe, take care of byte order in the record
1868 * header, write the record to the capture file, and update capture statistics. */
1870 cap_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, int errmsgl)
1872 struct pcap_pkthdr phdr;
1873 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1876 #if !GLIB_CHECK_VERSION(2,31,18)
1884 #ifdef LOG_CAPTURE_VERBOSE
1885 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1888 switch (pcap_src->cap_pipe_state) {
1890 case STATE_EXPECT_REC_HDR:
1892 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
1895 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
1896 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_modified ?
1897 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1898 pcap_src->cap_pipe_bytes_read = 0;
1901 pcap_src->cap_pipe_buf = (char *) &pcap_src->cap_pipe_rechdr;
1902 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1903 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1908 case STATE_READ_REC_HDR:
1910 if (pcap_src->from_cap_socket)
1913 b = cap_pipe_read(pcap_src->cap_pipe_fd, ((char *)&pcap_src->cap_pipe_rechdr)+pcap_src->cap_pipe_bytes_read,
1914 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read, pcap_src->from_cap_socket);
1917 result = PD_PIPE_EOF;
1919 result = PD_PIPE_ERR;
1922 pcap_src->cap_pipe_bytes_read += b;
1926 #if GLIB_CHECK_VERSION(2,31,18)
1927 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
1929 g_get_current_time(&wait_time);
1930 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
1931 q_status = g_async_queue_timed_pop(pcap_src->cap_pipe_done_q, &wait_time);
1933 if (pcap_src->cap_pipe_err == PIPEOF) {
1934 result = PD_PIPE_EOF;
1936 } else if (pcap_src->cap_pipe_err == PIPERR) {
1937 result = PD_PIPE_ERR;
1945 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
1947 result = PD_REC_HDR_READ;
1950 case STATE_EXPECT_DATA:
1952 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
1955 pcap_src->cap_pipe_state = STATE_READ_DATA;
1956 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_rechdr.hdr.incl_len;
1957 pcap_src->cap_pipe_bytes_read = 0;
1960 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
1961 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1962 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1967 case STATE_READ_DATA:
1969 if (pcap_src->from_cap_socket)
1972 b = cap_pipe_read(pcap_src->cap_pipe_fd,
1973 pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read,
1974 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read,
1975 pcap_src->from_cap_socket);
1978 result = PD_PIPE_EOF;
1980 result = PD_PIPE_ERR;
1983 pcap_src->cap_pipe_bytes_read += b;
1988 #if GLIB_CHECK_VERSION(2,31,18)
1989 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
1991 g_get_current_time(&wait_time);
1992 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
1993 q_status = g_async_queue_timed_pop(pcap_src->cap_pipe_done_q, &wait_time);
1994 #endif /* GLIB_CHECK_VERSION(2,31,18) */
1995 if (pcap_src->cap_pipe_err == PIPEOF) {
1996 result = PD_PIPE_EOF;
1998 } else if (pcap_src->cap_pipe_err == PIPERR) {
1999 result = PD_PIPE_ERR;
2007 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2009 result = PD_DATA_READ;
2013 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2016 } /* switch (pcap_src->cap_pipe_state) */
2019 * We've now read as much data as we were expecting, so process it.
2023 case PD_REC_HDR_READ:
2024 /* We've read the header. Take care of byte order. */
2025 cap_pipe_adjust_header(pcap_src->cap_pipe_byte_swapped, &pcap_src->cap_pipe_hdr,
2026 &pcap_src->cap_pipe_rechdr.hdr);
2027 if (pcap_src->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2028 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2029 ld->packet_count+1, pcap_src->cap_pipe_rechdr.hdr.incl_len);
2033 if (pcap_src->cap_pipe_rechdr.hdr.incl_len) {
2034 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2037 /* no data to read? */
2040 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2041 phdr.ts.tv_sec = pcap_src->cap_pipe_rechdr.hdr.ts_sec;
2042 phdr.ts.tv_usec = pcap_src->cap_pipe_rechdr.hdr.ts_usec;
2043 phdr.caplen = pcap_src->cap_pipe_rechdr.hdr.incl_len;
2044 phdr.len = pcap_src->cap_pipe_rechdr.hdr.orig_len;
2047 capture_loop_queue_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2049 capture_loop_write_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2051 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2055 pcap_src->cap_pipe_err = PIPEOF;
2060 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2061 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2062 g_snprintf(errmsg, errmsgl,
2063 "Error reading from pipe: %s (error %d)",
2064 utf_16to8(err_str), GetLastError());
2067 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2075 pcap_src->cap_pipe_err = PIPERR;
2076 /* Return here rather than inside the switch to prevent GCC warning */
2081 /** Open the capture input file (pcap or capture pipe).
2082 * Returns TRUE if it succeeds, FALSE otherwise. */
2084 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2085 char *errmsg, size_t errmsg_len,
2086 char *secondary_errmsg, size_t secondary_errmsg_len)
2088 gchar open_err_str[PCAP_ERRBUF_SIZE];
2089 gchar *sync_msg_str;
2090 interface_options interface_opts;
2091 capture_src *pcap_src;
2095 WORD wVersionRequested;
2099 /* XXX - opening Winsock on tshark? */
2101 /* Initialize Windows Socket if we are in a Win32 OS
2102 This needs to be done before querying the interface for network/netmask */
2104 /* XXX - do we really require 1.1 or earlier?
2105 Are there any versions that support only 2.0 or higher? */
2106 wVersionRequested = MAKEWORD(1, 1);
2107 err = WSAStartup(wVersionRequested, &wsaData);
2111 case WSASYSNOTREADY:
2112 g_snprintf(errmsg, (gulong) errmsg_len,
2113 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2116 case WSAVERNOTSUPPORTED:
2117 g_snprintf(errmsg, (gulong) errmsg_len,
2118 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2119 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2122 case WSAEINPROGRESS:
2123 g_snprintf(errmsg, (gulong) errmsg_len,
2124 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2128 g_snprintf(errmsg, (gulong) errmsg_len,
2129 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2133 g_snprintf(errmsg, (gulong) errmsg_len,
2134 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2138 g_snprintf(errmsg, (gulong) errmsg_len,
2139 "Couldn't initialize Windows Sockets: error %d", err);
2142 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2146 if ((use_threads == FALSE) &&
2147 (capture_opts->ifaces->len > 1)) {
2148 g_snprintf(errmsg, (gulong) errmsg_len,
2149 "Using threads is required for capturing on multiple interfaces.");
2153 for (i = 0; i < capture_opts->ifaces->len; i++) {
2154 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2155 pcap_src = (capture_src *)g_malloc(sizeof (capture_src));
2156 if (pcap_src == NULL) {
2157 g_snprintf(errmsg, (gulong) errmsg_len,
2158 "Could not allocate memory.");
2161 pcap_src->received = 0;
2162 pcap_src->dropped = 0;
2163 pcap_src->flushed = 0;
2164 pcap_src->pcap_h = NULL;
2165 #ifdef MUST_DO_SELECT
2166 pcap_src->pcap_fd = -1;
2168 pcap_src->pcap_err = FALSE;
2169 pcap_src->interface_id = i;
2170 pcap_src->tid = NULL;
2171 pcap_src->snaplen = 0;
2172 pcap_src->linktype = -1;
2173 pcap_src->ts_nsec = FALSE;
2174 pcap_src->from_cap_pipe = FALSE;
2175 pcap_src->from_cap_socket = FALSE;
2176 memset(&pcap_src->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2177 memset(&pcap_src->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2179 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2181 pcap_src->cap_pipe_fd = -1;
2182 pcap_src->cap_pipe_modified = FALSE;
2183 pcap_src->cap_pipe_byte_swapped = FALSE;
2185 pcap_src->cap_pipe_buf = NULL;
2187 pcap_src->cap_pipe_bytes_to_read = 0;
2188 pcap_src->cap_pipe_bytes_read = 0;
2189 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2190 pcap_src->cap_pipe_err = PIPOK;
2192 #if GLIB_CHECK_VERSION(2,31,0)
2193 pcap_src->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2194 g_mutex_init(pcap_src->cap_pipe_read_mtx);
2196 pcap_src->cap_pipe_read_mtx = g_mutex_new();
2198 pcap_src->cap_pipe_pending_q = g_async_queue_new();
2199 pcap_src->cap_pipe_done_q = g_async_queue_new();
2201 g_array_append_val(ld->pcaps, pcap_src);
2203 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2204 pcap_src->pcap_h = open_capture_device(capture_opts, &interface_opts,
2205 CAP_READ_TIMEOUT, &open_err_str);
2207 if (pcap_src->pcap_h != NULL) {
2208 /* we've opened "iface" as a network device */
2210 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2211 /* Find out if we're getting nanosecond-precision time stamps */
2212 pcap_src->ts_nsec = have_high_resolution_timestamp(pcap_src->pcap_h);
2215 #if defined(HAVE_PCAP_SETSAMPLING)
2216 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2217 struct pcap_samp *samp;
2219 if ((samp = pcap_setsampling(pcap_src->pcap_h)) != NULL) {
2220 switch (interface_opts.sampling_method) {
2221 case CAPTURE_SAMP_BY_COUNT:
2222 samp->method = PCAP_SAMP_1_EVERY_N;
2225 case CAPTURE_SAMP_BY_TIMER:
2226 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2230 sync_msg_str = g_strdup_printf(
2231 "Unknown sampling method %d specified,\n"
2232 "continue without packet sampling",
2233 interface_opts.sampling_method);
2234 report_capture_error("Couldn't set the capture "
2235 "sampling", sync_msg_str);
2236 g_free(sync_msg_str);
2238 samp->value = interface_opts.sampling_param;
2240 report_capture_error("Couldn't set the capture sampling",
2241 "Cannot get packet sampling data structure");
2246 /* setting the data link type only works on real interfaces */
2247 if (!set_pcap_datalink(pcap_src->pcap_h, interface_opts.linktype,
2248 interface_opts.name,
2250 secondary_errmsg, secondary_errmsg_len)) {
2253 pcap_src->linktype = get_pcap_datalink(pcap_src->pcap_h, interface_opts.name);
2255 /* We couldn't open "iface" as a network device. */
2256 /* Try to open it as a pipe */
2257 cap_pipe_open_live(interface_opts.name, pcap_src, &pcap_src->cap_pipe_hdr, errmsg, (int) errmsg_len);
2260 if (pcap_src->cap_pipe_fd == -1) {
2262 if (pcap_src->cap_pipe_h == INVALID_HANDLE_VALUE) {
2264 if (pcap_src->cap_pipe_err == PIPNEXIST) {
2266 * We tried opening as an interface, and that failed,
2267 * so we tried to open it as a pipe, but the pipe
2268 * doesn't exist. Report the error message for
2271 get_capture_device_open_failure_messages(open_err_str,
2272 interface_opts.name,
2276 secondary_errmsg_len);
2279 * Else pipe (or file) does exist and cap_pipe_open_live() has
2284 /* cap_pipe_open_live() succeeded; don't want
2285 error message from pcap_open_live() */
2286 open_err_str[0] = '\0';
2290 /* XXX - will this work for tshark? */
2291 #ifdef MUST_DO_SELECT
2292 if (!pcap_src->from_cap_pipe) {
2293 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2294 pcap_src->pcap_fd = pcap_get_selectable_fd(pcap_src->pcap_h);
2296 pcap_src->pcap_fd = pcap_fileno(pcap_src->pcap_h);
2301 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2302 returned a warning; print it, but keep capturing. */
2303 if (open_err_str[0] != '\0') {
2304 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2305 report_capture_error(sync_msg_str, "");
2306 g_free(sync_msg_str);
2308 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2309 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2312 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2313 /* to remove any suid privileges. */
2314 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2315 /* (euid/egid have already previously been set to ruid/rgid. */
2316 /* (See comment in main() for details) */
2318 relinquish_special_privs_perm();
2320 relinquish_all_capabilities();
2325 /* close the capture input file (pcap or capture pipe) */
2326 static void capture_loop_close_input(loop_data *ld)
2329 capture_src *pcap_src;
2331 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2333 for (i = 0; i < ld->pcaps->len; i++) {
2334 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2335 /* Pipe, or capture device? */
2336 if (pcap_src->from_cap_pipe) {
2337 /* Pipe. If open, close the capture pipe "input file". */
2338 if (pcap_src->cap_pipe_fd >= 0) {
2339 cap_pipe_close(pcap_src->cap_pipe_fd, pcap_src->from_cap_socket);
2340 pcap_src->cap_pipe_fd = -1;
2343 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE) {
2344 CloseHandle(pcap_src->cap_pipe_h);
2345 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2348 if (pcap_src->cap_pipe_databuf != NULL) {
2349 /* Free the buffer. */
2350 g_free(pcap_src->cap_pipe_databuf);
2351 pcap_src->cap_pipe_databuf = NULL;
2354 /* Capture device. If open, close the pcap_t. */
2355 if (pcap_src->pcap_h != NULL) {
2356 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_src->pcap_h);
2357 pcap_close(pcap_src->pcap_h);
2358 pcap_src->pcap_h = NULL;
2366 /* Shut down windows sockets */
2372 /* init the capture filter */
2373 static initfilter_status_t
2374 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2375 const gchar * name, const gchar * cfilter)
2377 struct bpf_program fcode;
2379 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2381 /* capture filters only work on real interfaces */
2382 if (cfilter && !from_cap_pipe) {
2383 /* A capture filter was specified; set it up. */
2384 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2385 /* Treat this specially - our caller might try to compile this
2386 as a display filter and, if that succeeds, warn the user that
2387 the display and capture filter syntaxes are different. */
2388 return INITFILTER_BAD_FILTER;
2390 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2391 #ifdef HAVE_PCAP_FREECODE
2392 pcap_freecode(&fcode);
2394 return INITFILTER_OTHER_ERROR;
2396 #ifdef HAVE_PCAP_FREECODE
2397 pcap_freecode(&fcode);
2401 return INITFILTER_NO_ERROR;
2405 /* set up to write to the already-opened capture output file/files */
2407 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2411 capture_src *pcap_src;
2412 interface_options interface_opts;
2413 gboolean successful;
2415 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2417 if ((capture_opts->use_pcapng == FALSE) &&
2418 (capture_opts->ifaces->len > 1)) {
2419 g_snprintf(errmsg, errmsg_len,
2420 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
2424 /* Set up to write to the capture file. */
2425 if (capture_opts->multi_files_on) {
2426 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2428 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2429 if (ld->pdh == NULL) {
2434 if (capture_opts->use_pcapng) {
2436 GString *cpu_info_str;
2437 GString *os_info_str;
2439 cpu_info_str = g_string_new("");
2440 os_info_str = g_string_new("");
2441 get_cpu_info(cpu_info_str);
2442 get_os_version_info(os_info_str);
2444 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2445 successful = pcapng_write_session_header_block(ld->pdh,
2446 (const char *)capture_opts->capture_comment, /* Comment */
2447 cpu_info_str->str, /* HW */
2448 os_info_str->str, /* OS */
2450 -1, /* section_length */
2455 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2456 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2457 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2458 if (pcap_src->from_cap_pipe) {
2459 pcap_src->snaplen = pcap_src->cap_pipe_hdr.snaplen;
2461 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
2463 successful = pcapng_write_interface_description_block(global_ld.pdh,
2464 NULL, /* OPT_COMMENT 1 */
2465 interface_opts.name, /* IDB_NAME 2 */
2466 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2467 interface_opts.cfilter, /* IDB_FILTER 11 */
2468 os_info_str->str, /* IDB_OS 12 */
2471 &(global_ld.bytes_written),
2472 0, /* IDB_IF_SPEED 8 */
2473 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2477 g_string_free(os_info_str, TRUE);
2480 pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
2481 if (pcap_src->from_cap_pipe) {
2482 pcap_src->snaplen = pcap_src->cap_pipe_hdr.snaplen;
2484 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
2486 successful = libpcap_write_file_header(ld->pdh, pcap_src->linktype, pcap_src->snaplen,
2487 pcap_src->ts_nsec, &ld->bytes_written, &err);
2495 if (ld->pdh == NULL) {
2496 /* We couldn't set up to write to the capture file. */
2497 /* XXX - use cf_open_error_message from tshark instead? */
2502 g_snprintf(errmsg, errmsg_len,
2503 "The file to which the capture would be"
2504 " saved (\"%s\") could not be opened: Error %d.",
2505 capture_opts->save_file, err);
2507 g_snprintf(errmsg, errmsg_len,
2508 "The file to which the capture would be"
2509 " saved (\"%s\") could not be opened: %s.",
2510 capture_opts->save_file, g_strerror(err));
2522 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2526 capture_src *pcap_src;
2527 guint64 end_time = create_timestamp();
2529 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2531 if (capture_opts->multi_files_on) {
2532 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2534 if (capture_opts->use_pcapng) {
2535 for (i = 0; i < global_ld.pcaps->len; i++) {
2536 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
2537 if (!pcap_src->from_cap_pipe) {
2538 guint64 isb_ifrecv, isb_ifdrop;
2539 struct pcap_stat stats;
2541 if (pcap_stats(pcap_src->pcap_h, &stats) >= 0) {
2542 isb_ifrecv = pcap_src->received;
2543 isb_ifdrop = stats.ps_drop + pcap_src->dropped + pcap_src->flushed;
2545 isb_ifrecv = G_MAXUINT64;
2546 isb_ifdrop = G_MAXUINT64;
2548 pcapng_write_interface_statistics_block(ld->pdh,
2551 "Counters provided by dumpcap",
2560 if (fclose(ld->pdh) == EOF) {
2561 if (err_close != NULL) {
2571 /* dispatch incoming packets (pcap or capture pipe)
2573 * Waits for incoming packets to be available, and calls pcap_dispatch()
2574 * to cause them to be processed.
2576 * Returns the number of packets which were processed.
2578 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2579 * packet-batching behaviour does not cause packets to get held back
2583 capture_loop_dispatch(loop_data *ld,
2584 char *errmsg, int errmsg_len, capture_src *pcap_src)
2587 gint packet_count_before;
2592 packet_count_before = ld->packet_count;
2593 if (pcap_src->from_cap_pipe) {
2594 /* dispatch from capture pipe */
2595 #ifdef LOG_CAPTURE_VERBOSE
2596 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2599 sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
2601 if (sel_ret < 0 && errno != EINTR) {
2602 g_snprintf(errmsg, errmsg_len,
2603 "Unexpected error from select: %s", g_strerror(errno));
2604 report_capture_error(errmsg, please_report);
2609 * "select()" says we can read from the pipe without blocking
2612 inpkts = cap_pipe_dispatch(ld, pcap_src, errmsg, errmsg_len);
2622 /* dispatch from pcap */
2623 #ifdef MUST_DO_SELECT
2625 * If we have "pcap_get_selectable_fd()", we use it to get the
2626 * descriptor on which to select; if that's -1, it means there
2627 * is no descriptor on which you can do a "select()" (perhaps
2628 * because you're capturing on a special device, and that device's
2629 * driver unfortunately doesn't support "select()", in which case
2630 * we don't do the select - which means it might not be possible
2631 * to stop a capture until a packet arrives. If that's unacceptable,
2632 * plead with whoever supplies the software for that device to add
2633 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2634 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2635 * later, so it can use pcap_breakloop().
2637 #ifdef LOG_CAPTURE_VERBOSE
2638 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2640 if (pcap_src->pcap_fd != -1) {
2641 sel_ret = cap_pipe_select(pcap_src->pcap_fd);
2644 * "select()" says we can read from it without blocking; go for
2647 * We don't have pcap_breakloop(), so we only process one packet
2648 * per pcap_dispatch() call, to allow a signal to stop the
2649 * processing immediately, rather than processing all packets
2650 * in a batch before quitting.
2653 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
2655 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
2659 /* Error, rather than pcap_breakloop(). */
2660 pcap_src->pcap_err = TRUE;
2662 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2665 if (sel_ret < 0 && errno != EINTR) {
2666 g_snprintf(errmsg, errmsg_len,
2667 "Unexpected error from select: %s", g_strerror(errno));
2668 report_capture_error(errmsg, please_report);
2674 #endif /* MUST_DO_SELECT */
2676 /* dispatch from pcap without select */
2678 #ifdef LOG_CAPTURE_VERBOSE
2679 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2683 * On Windows, we don't support asynchronously telling a process to
2684 * stop capturing; instead, we check for an indication on a pipe
2685 * after processing packets. We therefore process only one packet
2686 * at a time, so that we can check the pipe after every packet.
2689 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
2691 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
2695 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
2697 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_src);
2702 /* Error, rather than pcap_breakloop(). */
2703 pcap_src->pcap_err = TRUE;
2705 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2707 #else /* pcap_next_ex */
2708 #ifdef LOG_CAPTURE_VERBOSE
2709 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2711 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2714 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2715 * see https://wiki.wireshark.org/CaptureSetup/WinPcapRemote
2716 * This should be fixed in the WinPcap 4.0 alpha release.
2718 * For reference, an example remote interface:
2719 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2722 /* emulate dispatch from pcap */
2725 struct pcap_pkthdr *pkt_header;
2730 (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
2732 capture_loop_queue_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
2734 capture_loop_write_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
2739 pcap_src->pcap_err = TRUE;
2743 #endif /* pcap_next_ex */
2747 #ifdef LOG_CAPTURE_VERBOSE
2748 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2751 return ld->packet_count - packet_count_before;
2755 /* Isolate the Universally Unique Identifier from the interface. Basically, we
2756 * want to grab only the characters between the '{' and '}' delimiters.
2758 * Returns a GString that must be freed with g_string_free(). */
2760 isolate_uuid(const char *iface)
2765 ptr = strchr(iface, '{');
2767 return g_string_new(iface);
2768 gstr = g_string_new(ptr + 1);
2770 ptr = strchr(gstr->str, '}');
2774 gstr = g_string_truncate(gstr, ptr - gstr->str);
2779 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2780 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2782 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2783 char *errmsg, int errmsg_len)
2786 gchar *capfile_name;
2787 gchar *prefix, *suffix;
2788 gboolean is_tempfile;
2790 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2791 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
2793 if (capture_opts->save_file != NULL) {
2794 /* We return to the caller while the capture is in progress.
2795 * Therefore we need to take a copy of save_file in
2796 * case the caller destroys it after we return.
2798 capfile_name = g_strdup(capture_opts->save_file);
2800 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2801 if (capture_opts->multi_files_on) {
2802 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2803 g_snprintf(errmsg, errmsg_len,
2804 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2805 g_free(capfile_name);
2808 if (strcmp(capfile_name, "-") == 0) {
2809 /* write to stdout */
2812 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2813 _setmode(1, O_BINARY);
2816 } /* if (...output_to_pipe ... */
2819 if (capture_opts->multi_files_on) {
2820 /* ringbuffer is enabled */
2821 *save_file_fd = ringbuf_init(capfile_name,
2822 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
2823 capture_opts->group_read_access);
2825 /* we need the ringbuf name */
2826 if (*save_file_fd != -1) {
2827 g_free(capfile_name);
2828 capfile_name = g_strdup(ringbuf_current_filename());
2831 /* Try to open/create the specified file for use as a capture buffer. */
2832 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2833 (capture_opts->group_read_access) ? 0640 : 0600);
2836 is_tempfile = FALSE;
2838 /* Choose a random name for the temporary capture buffer */
2839 if (global_capture_opts.ifaces->len > 1) {
2840 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
2841 if (capture_opts->use_pcapng) {
2848 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
2850 /* use the generic portion of the interface guid to form the basis of the filename */
2851 if (strncmp("NPF_{", basename, 5)==0)
2853 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
2855 iface = isolate_uuid(basename);
2857 basename = g_strdup(iface->str);
2858 g_string_free(iface, TRUE);
2861 /* generate the temp file name prefix and suffix */
2862 if (capture_opts->use_pcapng) {
2863 prefix = g_strconcat("wireshark_", basename, NULL);
2866 prefix = g_strconcat("wireshark_", basename, NULL);
2871 *save_file_fd = create_tempfile(&tmpname, prefix, suffix);
2873 capfile_name = g_strdup(tmpname);
2877 /* did we fail to open the output file? */
2878 if (*save_file_fd == -1) {
2880 g_snprintf(errmsg, errmsg_len,
2881 "The temporary file to which the capture would be saved (\"%s\") "
2882 "could not be opened: %s.", capfile_name, g_strerror(errno));
2884 if (capture_opts->multi_files_on) {
2885 ringbuf_error_cleanup();
2888 g_snprintf(errmsg, errmsg_len,
2889 "The file to which the capture would be saved (\"%s\") "
2890 "could not be opened: %s.", capfile_name,
2893 g_free(capfile_name);
2897 if (capture_opts->save_file != NULL) {
2898 g_free(capture_opts->save_file);
2900 capture_opts->save_file = capfile_name;
2901 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2902 "g_free(capfile_name)". */
2908 /* Do the work of handling either the file size or file duration capture
2909 conditions being reached, and switching files or stopping. */
2911 do_file_switch_or_stop(capture_options *capture_opts,
2912 condition *cnd_autostop_files,
2913 condition *cnd_autostop_size,
2914 condition *cnd_file_duration)
2917 capture_src *pcap_src;
2918 interface_options interface_opts;
2919 gboolean successful;
2921 if (capture_opts->multi_files_on) {
2922 if (cnd_autostop_files != NULL &&
2923 cnd_eval(cnd_autostop_files, (guint64)++global_ld.autostop_files)) {
2924 /* no files left: stop here */
2925 global_ld.go = FALSE;
2929 /* Switch to the next ringbuffer file */
2930 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2931 &global_ld.save_file_fd, &global_ld.err)) {
2933 /* File switch succeeded: reset the conditions */
2934 global_ld.bytes_written = 0;
2935 if (capture_opts->use_pcapng) {
2937 GString *cpu_info_str;
2938 GString *os_info_str;
2940 cpu_info_str = g_string_new("");
2941 os_info_str = g_string_new("");
2942 get_cpu_info(cpu_info_str);
2943 get_os_version_info(os_info_str);
2945 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2946 successful = pcapng_write_session_header_block(global_ld.pdh,
2947 (const char *)capture_opts->capture_comment, /* Comment */
2948 cpu_info_str->str, /* HW */
2949 os_info_str->str, /* OS */
2951 -1, /* section_length */
2952 &(global_ld.bytes_written),
2956 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2957 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2958 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
2959 successful = pcapng_write_interface_description_block(global_ld.pdh,
2960 NULL, /* OPT_COMMENT 1 */
2961 interface_opts.name, /* IDB_NAME 2 */
2962 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2963 interface_opts.cfilter, /* IDB_FILTER 11 */
2964 os_info_str->str, /* IDB_OS 12 */
2967 &(global_ld.bytes_written),
2968 0, /* IDB_IF_SPEED 8 */
2969 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2973 g_string_free(os_info_str, TRUE);
2976 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
2977 successful = libpcap_write_file_header(global_ld.pdh, pcap_src->linktype, pcap_src->snaplen,
2978 pcap_src->ts_nsec, &global_ld.bytes_written, &global_ld.err);
2981 fclose(global_ld.pdh);
2982 global_ld.pdh = NULL;
2983 global_ld.go = FALSE;
2986 if (cnd_autostop_size)
2987 cnd_reset(cnd_autostop_size);
2988 if (cnd_file_duration)
2989 cnd_reset(cnd_file_duration);
2990 fflush(global_ld.pdh);
2992 report_packet_count(global_ld.inpkts_to_sync_pipe);
2993 global_ld.inpkts_to_sync_pipe = 0;
2994 report_new_capture_file(capture_opts->save_file);
2996 /* File switch failed: stop here */
2997 global_ld.go = FALSE;
3001 /* single file, stop now */
3002 global_ld.go = FALSE;
3009 pcap_read_handler(void* arg)
3011 capture_src *pcap_src;
3012 char errmsg[MSG_MAX_LENGTH+1];
3014 pcap_src = (capture_src *)arg;
3016 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3017 pcap_src->interface_id);
3019 while (global_ld.go) {
3020 /* dispatch incoming packets */
3021 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_src);
3023 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3024 pcap_src->interface_id);
3025 g_thread_exit(NULL);
3029 /* Do the low-level work of a capture.
3030 Returns TRUE if it succeeds, FALSE otherwise. */
3032 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3035 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3037 struct timeval upd_time, cur_time;
3041 condition *cnd_file_duration = NULL;
3042 condition *cnd_autostop_files = NULL;
3043 condition *cnd_autostop_size = NULL;
3044 condition *cnd_autostop_duration = NULL;
3047 gboolean cfilter_error = FALSE;
3048 char errmsg[MSG_MAX_LENGTH+1];
3049 char secondary_errmsg[MSG_MAX_LENGTH+1];
3050 capture_src *pcap_src;
3051 interface_options interface_opts;
3052 guint i, error_index = 0;
3055 *secondary_errmsg = '\0';
3057 /* init the loop data */
3058 global_ld.go = TRUE;
3059 global_ld.packet_count = 0;
3061 global_ld.report_packet_count = FALSE;
3063 if (capture_opts->has_autostop_packets)
3064 global_ld.packet_max = capture_opts->autostop_packets;
3066 global_ld.packet_max = 0; /* no limit */
3067 global_ld.inpkts_to_sync_pipe = 0;
3068 global_ld.err = 0; /* no error seen yet */
3069 global_ld.pdh = NULL;
3070 global_ld.autostop_files = 0;
3071 global_ld.save_file_fd = -1;
3073 /* We haven't yet gotten the capture statistics. */
3074 *stats_known = FALSE;
3076 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3077 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3079 /* open the "input file" from network interface or capture pipe */
3080 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3081 secondary_errmsg, sizeof(secondary_errmsg))) {
3084 for (i = 0; i < capture_opts->ifaces->len; i++) {
3085 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3086 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3087 /* init the input filter from the network interface (capture pipe will do nothing) */
3089 * When remote capturing WinPCap crashes when the capture filter
3090 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3093 switch (capture_loop_init_filter(pcap_src->pcap_h, pcap_src->from_cap_pipe,
3094 interface_opts.name,
3095 interface_opts.cfilter?interface_opts.cfilter:"")) {
3097 case INITFILTER_NO_ERROR:
3100 case INITFILTER_BAD_FILTER:
3101 cfilter_error = TRUE;
3103 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
3106 case INITFILTER_OTHER_ERROR:
3107 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3108 pcap_geterr(pcap_src->pcap_h));
3109 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3114 /* If we're supposed to write to a capture file, open it for output
3115 (temporary/specified name/ringbuffer) */
3116 if (capture_opts->saving_to_file) {
3117 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3118 errmsg, sizeof(errmsg))) {
3122 /* set up to write to the already-opened capture output file/files */
3123 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3128 /* XXX - capture SIGTERM and close the capture, in case we're on a
3129 Linux 2.0[.x] system and you have to explicitly close the capture
3130 stream in order to turn promiscuous mode off? We need to do that
3131 in other places as well - and I don't think that works all the
3132 time in any case, due to libpcap bugs. */
3134 /* Well, we should be able to start capturing.
3136 Sync out the capture file, so the header makes it to the file system,
3137 and send a "capture started successfully and capture file created"
3138 message to our parent so that they'll open the capture file and
3139 update its windows to indicate that we have a live capture in
3141 fflush(global_ld.pdh);
3142 report_new_capture_file(capture_opts->save_file);
3145 /* initialize capture stop (and alike) conditions */
3146 init_capture_stop_conditions();
3147 /* create stop conditions */
3148 if (capture_opts->has_autostop_filesize) {
3149 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3150 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3153 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3155 if (capture_opts->has_autostop_duration)
3156 cnd_autostop_duration =
3157 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3159 if (capture_opts->multi_files_on) {
3160 if (capture_opts->has_file_duration)
3162 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3164 if (capture_opts->has_autostop_files)
3165 cnd_autostop_files =
3166 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_files);
3169 /* init the time values */
3171 upd_time = GetTickCount();
3173 gettimeofday(&upd_time, NULL);
3175 start_time = create_timestamp();
3176 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3177 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3179 /* WOW, everything is prepared! */
3180 /* please fasten your seat belts, we will enter now the actual capture loop */
3182 pcap_queue = g_async_queue_new();
3183 pcap_queue_bytes = 0;
3184 pcap_queue_packets = 0;
3185 for (i = 0; i < global_ld.pcaps->len; i++) {
3186 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3187 #if GLIB_CHECK_VERSION(2,31,0)
3188 /* XXX - Add an interface name here? */
3189 pcap_src->tid = g_thread_new("Capture read", pcap_read_handler, pcap_src);
3191 pcap_src->tid = g_thread_create(pcap_read_handler, pcap_src, TRUE, NULL);
3195 while (global_ld.go) {
3196 /* dispatch incoming packets */
3198 pcap_queue_element *queue_element;
3199 #if GLIB_CHECK_VERSION(2,31,18)
3201 g_async_queue_lock(pcap_queue);
3202 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3204 GTimeVal write_thread_time;
3206 g_get_current_time(&write_thread_time);
3207 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3208 g_async_queue_lock(pcap_queue);
3209 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3211 if (queue_element) {
3212 pcap_queue_bytes -= queue_element->phdr.caplen;
3213 pcap_queue_packets -= 1;
3215 g_async_queue_unlock(pcap_queue);
3216 if (queue_element) {
3217 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3218 "Dequeued a packet of length %d captured on interface %d.",
3219 queue_element->phdr.caplen, queue_element->pcap_src->interface_id);
3221 capture_loop_write_packet_cb((u_char *) queue_element->pcap_src,
3222 &queue_element->phdr,
3224 g_free(queue_element->pd);
3225 g_free(queue_element);
3231 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3232 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3233 sizeof(errmsg), pcap_src);
3236 /* Were we asked to print packet counts by the SIGINFO handler? */
3237 if (global_ld.report_packet_count) {
3238 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3239 plurality(global_ld.packet_count, "", "s"));
3240 global_ld.report_packet_count = FALSE;
3245 /* any news from our parent (signal pipe)? -> just stop the capture */
3246 if (!signal_pipe_check_running()) {
3247 global_ld.go = FALSE;
3252 global_ld.inpkts_to_sync_pipe += inpkts;
3254 /* check capture size condition */
3255 if (cnd_autostop_size != NULL &&
3256 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3257 /* Capture size limit reached, do we have another file? */
3258 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3259 cnd_autostop_size, cnd_file_duration))
3261 } /* cnd_autostop_size */
3262 if (capture_opts->output_to_pipe) {
3263 fflush(global_ld.pdh);
3267 /* Only update once every 500ms so as not to overload slow displays.
3268 * This also prevents too much context-switching between the dumpcap
3269 * and wireshark processes.
3271 #define DUMPCAP_UPD_TIME 500
3274 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3275 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3277 gettimeofday(&cur_time, NULL);
3278 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3279 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3282 upd_time = cur_time;
3285 if (pcap_stats(pch, stats) >= 0) {
3286 *stats_known = TRUE;
3289 /* Let the parent process know. */
3290 if (global_ld.inpkts_to_sync_pipe) {
3292 fflush(global_ld.pdh);
3294 /* Send our parent a message saying we've written out
3295 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3297 report_packet_count(global_ld.inpkts_to_sync_pipe);
3299 global_ld.inpkts_to_sync_pipe = 0;
3302 /* check capture duration condition */
3303 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3304 /* The maximum capture time has elapsed; stop the capture. */
3305 global_ld.go = FALSE;
3309 /* check capture file duration condition */
3310 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3311 /* duration limit reached, do we have another file? */
3312 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3313 cnd_autostop_size, cnd_file_duration))
3315 } /* cnd_file_duration */
3319 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3321 pcap_queue_element *queue_element;
3323 for (i = 0; i < global_ld.pcaps->len; i++) {
3324 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3325 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3326 pcap_src->interface_id);
3327 g_thread_join(pcap_src->tid);
3328 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3329 pcap_src->interface_id);
3332 g_async_queue_lock(pcap_queue);
3333 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3334 if (queue_element) {
3335 pcap_queue_bytes -= queue_element->phdr.caplen;
3336 pcap_queue_packets -= 1;
3338 g_async_queue_unlock(pcap_queue);
3339 if (queue_element == NULL) {
3342 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3343 "Dequeued a packet of length %d captured on interface %d.",
3344 queue_element->phdr.caplen, queue_element->pcap_src->interface_id);
3345 capture_loop_write_packet_cb((u_char *)queue_element->pcap_src,
3346 &queue_element->phdr,
3348 g_free(queue_element->pd);
3349 g_free(queue_element);
3350 global_ld.inpkts_to_sync_pipe += 1;
3351 if (capture_opts->output_to_pipe) {
3352 fflush(global_ld.pdh);
3358 /* delete stop conditions */
3359 if (cnd_file_duration != NULL)
3360 cnd_delete(cnd_file_duration);
3361 if (cnd_autostop_files != NULL)
3362 cnd_delete(cnd_autostop_files);
3363 if (cnd_autostop_size != NULL)
3364 cnd_delete(cnd_autostop_size);
3365 if (cnd_autostop_duration != NULL)
3366 cnd_delete(cnd_autostop_duration);
3368 /* did we have a pcap (input) error? */
3369 for (i = 0; i < capture_opts->ifaces->len; i++) {
3370 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3371 if (pcap_src->pcap_err) {
3372 /* On Linux, if an interface goes down while you're capturing on it,
3373 you'll get a "recvfrom: Network is down" or
3374 "The interface went down" error (ENETDOWN).
3375 (At least you will if g_strerror() doesn't show a local translation
3378 On FreeBSD, DragonFly BSD, and macOS, if a network adapter
3379 disappears while you're capturing on it, you'll get a
3380 "read: Device not configured" error (ENXIO). (See previous
3381 parenthetical note.)
3383 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3385 These should *not* be reported to the Wireshark developers. */
3388 cap_err_str = pcap_geterr(pcap_src->pcap_h);
3389 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3390 strcmp(cap_err_str, "The interface went down") == 0 ||
3391 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3392 strcmp(cap_err_str, "read: I/O error") == 0 ||
3393 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3394 report_capture_error("The network adapter on which the capture was being done "
3395 "is no longer running; the capture has stopped.",
3398 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3400 report_capture_error(errmsg, please_report);
3403 } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
3404 report_capture_error(errmsg, "");
3408 /* did we have an output error while capturing? */
3409 if (global_ld.err == 0) {
3412 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3413 global_ld.err, FALSE);
3414 report_capture_error(errmsg, please_report);
3418 if (capture_opts->saving_to_file) {
3419 /* close the output file */
3420 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3424 /* there might be packets not yet notified to the parent */
3425 /* (do this after closing the file, so all packets are already flushed) */
3426 if (global_ld.inpkts_to_sync_pipe) {
3428 report_packet_count(global_ld.inpkts_to_sync_pipe);
3429 global_ld.inpkts_to_sync_pipe = 0;
3432 /* If we've displayed a message about a write error, there's no point
3433 in displaying another message about an error on close. */
3434 if (!close_ok && write_ok) {
3435 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3437 report_capture_error(errmsg, "");
3441 * XXX We exhibit different behaviour between normal mode and sync mode
3442 * when the pipe is stdin and not already at EOF. If we're a child, the
3443 * parent's stdin isn't closed, so if the user starts another capture,
3444 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3445 * will say "Unrecognized libpcap format". On the other hand, in normal
3446 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3449 report_capture_count(TRUE);
3451 /* get packet drop statistics from pcap */
3452 for (i = 0; i < capture_opts->ifaces->len; i++) {
3454 guint32 pcap_dropped = 0;
3456 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3457 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3458 received = pcap_src->received;
3459 if (pcap_src->pcap_h != NULL) {
3460 g_assert(!pcap_src->from_cap_pipe);
3461 /* Get the capture statistics, so we know how many packets were dropped. */
3463 * Older versions of libpcap didn't set ps_ifdrop on some
3464 * platforms; initialize it to 0 to handle that.
3466 stats->ps_ifdrop = 0;
3467 if (pcap_stats(pcap_src->pcap_h, stats) >= 0) {
3468 *stats_known = TRUE;
3469 /* Let the parent process know. */
3470 pcap_dropped += stats->ps_drop;
3472 g_snprintf(errmsg, sizeof(errmsg),
3473 "Can't get packet-drop statistics: %s",
3474 pcap_geterr(pcap_src->pcap_h));
3475 report_capture_error(errmsg, please_report);
3478 report_packet_drops(received, pcap_dropped, pcap_src->dropped, pcap_src->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
3481 /* close the input file (pcap or capture pipe) */
3482 capture_loop_close_input(&global_ld);
3484 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
3486 /* ok, if the write and the close were successful. */
3487 return write_ok && close_ok;
3490 if (capture_opts->multi_files_on) {
3491 /* cleanup ringbuffer */
3492 ringbuf_error_cleanup();
3494 /* We can't use the save file, and we have no FILE * for the stream
3495 to close in order to close it, so close the FD directly. */
3496 if (global_ld.save_file_fd != -1) {
3497 ws_close(global_ld.save_file_fd);
3500 /* We couldn't even start the capture, so get rid of the capture
3502 if (capture_opts->save_file != NULL) {
3503 ws_unlink(capture_opts->save_file);
3504 g_free(capture_opts->save_file);
3507 capture_opts->save_file = NULL;
3509 report_cfilter_error(capture_opts, error_index, errmsg);
3511 report_capture_error(errmsg, secondary_errmsg);
3513 /* close the input file (pcap or cap_pipe) */
3514 capture_loop_close_input(&global_ld);
3516 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3523 capture_loop_stop(void)
3525 #ifdef HAVE_PCAP_BREAKLOOP
3527 capture_src *pcap_src;
3529 for (i = 0; i < global_ld.pcaps->len; i++) {
3530 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3531 if (pcap_src->pcap_h != NULL)
3532 pcap_breakloop(pcap_src->pcap_h);
3535 global_ld.go = FALSE;
3540 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3541 int err, gboolean is_close)
3546 g_snprintf(errmsg, errmsglen,
3547 "Not all the packets could be written to the file"
3548 " to which the capture was being saved\n"
3549 "(\"%s\") because there is no space left on the file system\n"
3550 "on which that file resides.",
3556 g_snprintf(errmsg, errmsglen,
3557 "Not all the packets could be written to the file"
3558 " to which the capture was being saved\n"
3559 "(\"%s\") because you are too close to, or over,"
3560 " your disk quota\n"
3561 "on the file system on which that file resides.",
3568 g_snprintf(errmsg, errmsglen,
3569 "The file to which the capture was being saved\n"
3570 "(\"%s\") could not be closed: %s.",
3571 fname, g_strerror(err));
3573 g_snprintf(errmsg, errmsglen,
3574 "An error occurred while writing to the file"
3575 " to which the capture was being saved\n"
3577 fname, g_strerror(err));
3584 /* one packet was captured, process it */
3586 capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
3589 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
3591 guint ts_mul = pcap_src->ts_nsec ? 1000000000 : 1000000;
3593 /* We may be called multiple times from pcap_dispatch(); if we've set
3594 the "stop capturing" flag, ignore this packet, as we're not
3595 supposed to be saving any more packets. */
3596 if (!global_ld.go) {
3597 pcap_src->flushed++;
3601 if (global_ld.pdh) {
3602 gboolean successful;
3604 /* We're supposed to write the packet to a file; do so.
3605 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3606 "ld->err" to the error. */
3607 if (global_capture_opts.use_pcapng) {
3608 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
3610 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3611 phdr->caplen, phdr->len,
3612 pcap_src->interface_id,
3615 &global_ld.bytes_written, &err);
3617 successful = libpcap_write_packet(global_ld.pdh,
3618 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3619 phdr->caplen, phdr->len,
3621 &global_ld.bytes_written, &err);
3624 global_ld.go = FALSE;
3625 global_ld.err = err;
3626 pcap_src->dropped++;
3628 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3629 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3630 "Wrote a packet of length %d captured on interface %u.",
3631 phdr->caplen, pcap_src->interface_id);
3633 global_ld.packet_count++;
3634 pcap_src->received++;
3635 /* if the user told us to stop after x packets, do we already have enough? */
3636 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
3637 global_ld.go = FALSE;
3643 /* one packet was captured, queue it */
3645 capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
3648 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
3649 pcap_queue_element *queue_element;
3650 gboolean limit_reached;
3652 /* We may be called multiple times from pcap_dispatch(); if we've set
3653 the "stop capturing" flag, ignore this packet, as we're not
3654 supposed to be saving any more packets. */
3655 if (!global_ld.go) {
3656 pcap_src->flushed++;
3660 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
3661 if (queue_element == NULL) {
3662 pcap_src->dropped++;
3665 queue_element->pcap_src = pcap_src;
3666 queue_element->phdr = *phdr;
3667 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
3668 if (queue_element->pd == NULL) {
3669 pcap_src->dropped++;
3670 g_free(queue_element);
3673 memcpy(queue_element->pd, pd, phdr->caplen);
3674 g_async_queue_lock(pcap_queue);
3675 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
3676 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
3677 limit_reached = FALSE;
3678 g_async_queue_push_unlocked(pcap_queue, queue_element);
3679 pcap_queue_bytes += phdr->caplen;
3680 pcap_queue_packets += 1;
3682 limit_reached = TRUE;
3684 g_async_queue_unlock(pcap_queue);
3685 if (limit_reached) {
3686 pcap_src->dropped++;
3687 g_free(queue_element->pd);
3688 g_free(queue_element);
3689 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3690 "Dropped a packet of length %d captured on interface %u.",
3691 phdr->caplen, pcap_src->interface_id);
3693 pcap_src->received++;
3694 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3695 "Queued a packet of length %d captured on interface %u.",
3696 phdr->caplen, pcap_src->interface_id);
3698 /* I don't want to hold the mutex over the debug output. So the
3699 output may be wrong */
3700 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3701 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
3702 pcap_queue_bytes, pcap_queue_packets);
3706 set_80211_channel(const char *iface, const char *opt)
3710 guint32 center_freq1 = 0;
3711 guint32 center_freq2 = 0;
3714 gchar **options = NULL;
3716 options = g_strsplit_set(opt, ",", 4);
3717 for (args = 0; options[args]; args++);
3720 freq = get_nonzero_guint32(options[0], "802.11 channel frequency");
3722 if (args >= 1 && options[1]) {
3723 type = ws80211_str_to_chan_type(options[1]);
3725 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
3731 if (args >= 2 && options[2])
3732 center_freq1 = get_nonzero_guint32(options[2], "VHT center frequency");
3734 if (args >= 3 && options[3])
3735 center_freq2 = get_nonzero_guint32(options[3], "VHT center frequency 2");
3737 ret = ws80211_init();
3739 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
3743 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
3746 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
3752 pipe_write_block(2, SP_SUCCESS, NULL);
3755 g_strfreev(options);
3760 get_dumpcap_compiled_info(GString *str)
3762 /* Capture libraries */
3763 g_string_append(str, ", ");
3764 get_compiled_caplibs_version(str);
3768 get_dumpcap_runtime_info(GString *str)
3770 /* Capture libraries */
3771 g_string_append(str, ", ");
3772 get_runtime_caplibs_version(str);
3775 /* And now our feature presentation... [ fade to music ] */
3777 main(int argc, char *argv[])
3779 GString *comp_info_str;
3780 GString *runtime_info_str;
3782 static const struct option long_options[] = {
3783 {"help", no_argument, NULL, 'h'},
3784 {"version", no_argument, NULL, 'v'},
3785 LONGOPT_CAPTURE_COMMON
3789 gboolean arg_error = FALSE;
3795 struct sigaction action, oldaction;
3798 gboolean start_capture = TRUE;
3799 gboolean stats_known;
3800 struct pcap_stat stats;
3801 GLogLevelFlags log_flags;
3802 gboolean list_interfaces = FALSE;
3803 gboolean list_link_layer_types = FALSE;
3804 #ifdef HAVE_BPF_IMAGE
3805 gboolean print_bpf_code = FALSE;
3807 gboolean set_chan = FALSE;
3808 gchar *set_chan_arg = NULL;
3809 gboolean machine_readable = FALSE;
3810 gboolean print_statistics = FALSE;
3811 int status, run_once_args = 0;
3814 #if defined(__APPLE__) && defined(__LP64__)
3815 struct utsname osinfo;
3819 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
3821 /* Get the compile-time version information string */
3822 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
3824 /* Get the run-time version information string */
3825 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
3827 /* Add it to the information to be reported on a crash. */
3828 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
3833 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
3834 g_string_free(comp_info_str, TRUE);
3835 g_string_free(runtime_info_str, TRUE);
3838 arg_list_utf_16to8(argc, argv);
3839 create_app_running_mutex();
3842 * Initialize our DLL search path. MUST be called before LoadLibrary
3845 ws_init_dll_search_path();
3848 #ifdef HAVE_BPF_IMAGE
3849 #define OPTSTRING_d "d"
3851 #define OPTSTRING_d ""
3854 #ifdef HAVE_PCAP_REMOTE
3855 #define OPTSTRING_r "r"
3856 #define OPTSTRING_u "u"
3858 #define OPTSTRING_r ""
3859 #define OPTSTRING_u ""
3862 #ifdef HAVE_PCAP_SETSAMPLING
3863 #define OPTSTRING_m "m:"
3865 #define OPTSTRING_m ""
3868 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
3870 #ifdef DEBUG_CHILD_DUMPCAP
3871 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3872 fprintf (stderr, "Unable to open debug log file .\n");
3877 #if defined(__APPLE__) && defined(__LP64__)
3879 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
3880 * a bug workaround - timeouts less than 1 second don't work with libpcap
3881 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3882 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
3883 * The problem is extremely unlikely to be reintroduced in a future
3886 if (uname(&osinfo) == 0) {
3888 * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
3889 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3890 * number of 10.0.0, not 10.1.0 - go figure).
3892 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
3893 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
3894 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
3895 need_timeout_workaround = TRUE;
3900 * Determine if dumpcap is being requested to run in a special
3901 * capture_child mode by going thru the command line args to see if
3902 * a -Z is present. (-Z is a hidden option).
3904 * The primary result of running in capture_child mode is that
3905 * all messages sent out on stderr are in a special type/len/string
3906 * format to allow message processing by type. These messages include
3907 * error messages if dumpcap fails to start the operation it was
3908 * requested to do, as well as various "status" messages which are sent
3909 * when an actual capture is in progress, and a "success" message sent
3910 * if dumpcap was requested to perform an operation other than a
3913 * Capture_child mode would normally be requested by a parent process
3914 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3915 * to which dumpcap stderr has been redirected. It might also have
3916 * another pipe to obtain dumpcap stdout output; for operations other
3917 * than a capture, that information is formatted specially for easier
3918 * parsing by the parent process.
3920 * Capture_child mode needs to be determined immediately upon
3921 * startup so that any messages generated by dumpcap in this mode
3922 * (eg: during initialization) will be formatted properly.
3925 for (i=1; i<argc; i++) {
3926 if (strcmp("-Z", argv[i]) == 0) {
3927 capture_child = TRUE;
3928 machine_readable = TRUE; /* request machine-readable output */
3930 /* set output pipe to binary mode, to avoid ugly text conversions */
3931 _setmode(2, O_BINARY);
3936 /* The default_log_handler will use stdout, which makes trouble in */
3937 /* capture child mode, as it uses stdout for its sync_pipe. */
3938 /* So: the filtering is done in the console_log_handler and not here.*/
3939 /* We set the log handlers right up front to make sure that any log */
3940 /* messages when running as child will be sent back to the parent */
3941 /* with the correct format. */
3946 G_LOG_LEVEL_CRITICAL|
3947 G_LOG_LEVEL_WARNING|
3948 G_LOG_LEVEL_MESSAGE|
3952 G_LOG_FLAG_RECURSION);
3954 g_log_set_handler(NULL,
3956 console_log_handler, NULL /* user_data */);
3957 g_log_set_handler(LOG_DOMAIN_MAIN,
3959 console_log_handler, NULL /* user_data */);
3960 g_log_set_handler(LOG_DOMAIN_CAPTURE,
3962 console_log_handler, NULL /* user_data */);
3963 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3965 console_log_handler, NULL /* user_data */);
3967 /* Initialize the pcaps list */
3968 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(capture_src *));
3970 #if !GLIB_CHECK_VERSION(2,31,0)
3971 /* Initialize the thread system */
3972 g_thread_init(NULL);
3976 /* Load wpcap if possible. Do this before collecting the run-time version information */
3979 /* ... and also load the packet.dll from wpcap */
3980 /* XXX - currently not required, may change later. */
3981 /*wpcap_packet_load();*/
3983 /* Start windows sockets */
3984 result = WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3987 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_ERROR,
3988 "ERROR: WSAStartup failed with error: %d", result);
3992 /* Set handler for Ctrl+C key */
3993 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3995 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3996 and exit. Do the same with SIGPIPE, in case, for example,
3997 we're writing to our standard output and it's a pipe.
3998 Do the same with SIGHUP if it's not being ignored (if we're
3999 being run under nohup, it might be ignored, in which case we
4000 should leave it ignored).
4002 XXX - apparently, Coverity complained that part of action
4003 wasn't initialized. Perhaps it's running on Linux, where
4004 struct sigaction has an ignored "sa_restorer" element and
4005 where "sa_handler" and "sa_sigaction" might not be two
4006 members of a union. */
4007 memset(&action, 0, sizeof(action));
4008 action.sa_handler = capture_cleanup_handler;
4010 * Arrange that system calls not get restarted, because when
4011 * our signal handler returns we don't want to restart
4012 * a call that was waiting for packets to arrive.
4014 action.sa_flags = 0;
4015 sigemptyset(&action.sa_mask);
4016 sigaction(SIGTERM, &action, NULL);
4017 sigaction(SIGINT, &action, NULL);
4018 sigaction(SIGPIPE, &action, NULL);
4019 sigaction(SIGHUP, NULL, &oldaction);
4020 if (oldaction.sa_handler == SIG_DFL)
4021 sigaction(SIGHUP, &action, NULL);
4024 /* Catch SIGINFO and, if we get it and we're capturing in
4025 quiet mode, report the number of packets we've captured. */
4026 action.sa_handler = report_counts_siginfo;
4027 action.sa_flags = SA_RESTART;
4028 sigemptyset(&action.sa_mask);
4029 sigaction(SIGINFO, &action, NULL);
4030 #endif /* SIGINFO */
4034 enable_kernel_bpf_jit_compiler();
4037 /* ----------------------------------------------------------------- */
4038 /* Privilege and capability handling */
4040 /* 1. Running not as root or suid root; no special capabilities. */
4043 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4046 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4048 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4049 /* capabilities; Drop all other capabilities; */
4050 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4051 /* else: after pcap_open_live() in capture_loop_open_input() */
4052 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4053 /* (Note: this means that the process, although logged in */
4054 /* as root, does not have various permissions such as the */
4055 /* ability to bypass file access permissions). */
4056 /* XXX: Should we just leave capabilities alone in this case */
4057 /* so that user gets expected effect that root can do */
4060 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4062 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4063 /* else: after pcap_open_live() in capture_loop_open_input() */
4064 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4065 /* pcap_open_live). */
4067 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4069 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4070 /* capabilities; Drop all other capabilities; */
4071 /* Drop suid privileges (euid=ruid); */
4072 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4073 /* else: after pcap_open_live() in capture_loop_open_input() */
4074 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4076 /* XXX: For some Linux versions/distros with capabilities */
4077 /* a 'normal' process with any capabilities cannot be */
4078 /* 'killed' (signaled) from another (same uid) non-privileged */
4080 /* For example: If (non-suid) Wireshark forks a */
4081 /* child suid dumpcap which acts as described here (case 5), */
4082 /* Wireshark will be unable to kill (signal) the child */
4083 /* dumpcap process until the capabilities have been dropped */
4084 /* (after pcap_open_live()). */
4085 /* This behaviour will apparently be changed in the kernel */
4086 /* to allow the kill (signal) in this case. */
4087 /* See the following for details: */
4088 /* https://www.mail-archive.com/ [wrapped] */
4089 /* linux-security-module@vger.kernel.org/msg02913.html */
4091 /* It is therefore conceivable that if dumpcap somehow hangs */
4092 /* in pcap_open_live or before that wireshark will not */
4093 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4094 /* In this case, exiting wireshark will kill the child */
4095 /* dumpcap process. */
4097 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4098 /* capabilities; Using libcap. Note: capset cmd (which see) */
4099 /* used to assign capabilities to file. */
4101 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4102 /* else: after pcap_open_live() in capture_loop_open_input() */
4103 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4105 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4106 /* longer required (similar to capture). */
4108 /* ----------------------------------------------------------------- */
4110 init_process_policies();
4113 /* If 'started with special privileges' (and using libcap) */
4114 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4115 /* Set euid/egid = ruid/rgid to remove suid privileges */
4116 relinquish_privs_except_capture();
4119 /* Set the initial values in the capture options. This might be overwritten
4120 by the command line parameters. */
4121 capture_opts_init(&global_capture_opts);
4122 /* We always save to a file - if no file was specified, we save to a
4124 global_capture_opts.saving_to_file = TRUE;
4125 global_capture_opts.has_ring_num_files = TRUE;
4127 /* Pass on capture_child mode for capture_opts */
4128 global_capture_opts.capture_child = capture_child;
4130 /* Now get our args */
4131 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4133 case 'h': /* Print help and exit */
4134 printf("Dumpcap (Wireshark) %s\n"
4135 "Capture network packets and dump them into a pcapng or pcap file.\n"
4136 "See https://www.wireshark.org for more information.\n",
4137 get_ws_vcs_version_info());
4138 print_usage(stdout);
4141 case 'v': /* Show version and exit */
4142 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4143 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4144 show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4145 g_string_free(comp_info_str, TRUE);
4146 g_string_free(runtime_info_str, TRUE);
4149 /*** capture option specific ***/
4150 case 'a': /* autostop criteria */
4151 case 'b': /* Ringbuffer option */
4152 case 'c': /* Capture x packets */
4153 case 'f': /* capture filter */
4154 case 'g': /* enable group read access on file(s) */
4155 case 'i': /* Use interface x */
4156 case 'n': /* Use pcapng format */
4157 case 'p': /* Don't capture in promiscuous mode */
4158 case 'P': /* Use pcap format */
4159 case 's': /* Set the snapshot (capture) length */
4160 case 'w': /* Write to capture file x */
4161 case 'y': /* Set the pcap data link type */
4162 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4163 #ifdef HAVE_PCAP_REMOTE
4164 case 'u': /* Use UDP for data transfer */
4165 case 'r': /* Capture own RPCAP traffic too */
4166 case 'A': /* Authentication */
4168 #ifdef HAVE_PCAP_SETSAMPLING
4169 case 'm': /* Sampling */
4171 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4172 case 'B': /* Buffer size */
4174 #ifdef HAVE_PCAP_CREATE
4175 case 'I': /* Monitor mode */
4177 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4182 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4184 capture_child = TRUE;
4186 /* set output pipe to binary mode, to avoid ugly text conversions */
4187 _setmode(2, O_BINARY);
4189 * optarg = the control ID, aka the PPID, currently used for the
4192 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4193 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4194 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4195 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4197 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4198 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4199 "Signal pipe: Unable to open %s. Dead parent?",
4207 case 'q': /* Quiet */
4213 /*** all non capture option specific ***/
4214 case 'D': /* Print a list of capture devices and exit */
4215 if (!list_interfaces) {
4216 list_interfaces = TRUE;
4220 case 'L': /* Print list of link-layer types and exit */
4221 if (!list_link_layer_types) {
4222 list_link_layer_types = TRUE;
4226 #ifdef HAVE_BPF_IMAGE
4227 case 'd': /* Print BPF code for capture filter and exit */
4228 if (!print_bpf_code) {
4229 print_bpf_code = TRUE;
4234 case 'S': /* Print interface statistics once a second */
4235 if (!print_statistics) {
4236 print_statistics = TRUE;
4240 case 'k': /* Set wireless channel */
4243 set_chan_arg = optarg;
4246 cmdarg_err("Only one -k flag may be specified");
4250 case 'M': /* For -D, -L, and -S, print machine-readable output */
4251 machine_readable = TRUE;
4254 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4257 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4260 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4262 case '?': /* Bad flag - print usage message */
4271 /* user specified file name as regular command-line argument */
4272 /* XXX - use it as the capture file name (or something else)? */
4278 * Extra command line arguments were specified; complain.
4279 * XXX - interpret as capture filter, as tcpdump and tshark do?
4281 cmdarg_err("Invalid argument: %s", argv[0]);
4286 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4289 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4290 /* Use some default if the user hasn't specified some */
4291 /* XXX: Are these defaults good enough? */
4292 pcap_queue_byte_limit = 1000 * 1000;
4293 pcap_queue_packet_limit = 1000;
4296 print_usage(stderr);
4300 if (run_once_args > 1) {
4301 #ifdef HAVE_BPF_IMAGE
4302 cmdarg_err("Only one of -D, -L, -d, -k, or -S may be supplied.");
4304 cmdarg_err("Only one of -D, -L, -k, or -S may be supplied.");
4307 } else if (run_once_args == 1) {
4308 /* We're supposed to print some information, rather than
4309 to capture traffic; did they specify a ring buffer option? */
4310 if (global_capture_opts.multi_files_on) {
4311 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4315 /* We're supposed to capture traffic; */
4317 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4318 if (global_capture_opts.ifaces->len > 1) {
4320 global_capture_opts.use_pcapng = TRUE;
4323 if (global_capture_opts.capture_comment &&
4324 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4325 /* XXX - for ringbuffer, should we apply the comment to each file? */
4326 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4330 /* Was the ring buffer option specified and, if so, does it make sense? */
4331 if (global_capture_opts.multi_files_on) {
4332 /* Ring buffer works only under certain conditions:
4333 a) ring buffer does not work with temporary files;
4334 b) it makes no sense to enable the ring buffer if the maximum
4335 file size is set to "infinite". */
4336 if (global_capture_opts.save_file == NULL) {
4337 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4338 global_capture_opts.multi_files_on = FALSE;
4340 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4341 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4343 /* XXX - this must be redesigned as the conditions changed */
4344 global_capture_opts.multi_files_on = FALSE;
4351 * "-D" requires no interface to be selected; it's supposed to list
4354 if (list_interfaces) {
4355 /* Get the list of interfaces */
4360 if_list = capture_interface_list(&err, &err_str,NULL);
4361 if (if_list == NULL) {
4364 * If we're being run by another program, just give them
4365 * an empty list of interfaces, don't report this as
4366 * an error; that lets them decide whether to report
4367 * this as an error or not.
4369 if (!machine_readable) {
4370 cmdarg_err("There are no interfaces on which a capture can be done");
4374 cmdarg_err("%s", err_str);
4380 if (machine_readable) /* tab-separated values to stdout */
4381 print_machine_readable_interfaces(if_list);
4383 capture_opts_print_interfaces(if_list);
4384 free_interface_list(if_list);
4389 * "-S" requires no interface to be selected; it gives statistics
4390 * for all interfaces.
4392 if (print_statistics) {
4393 status = print_statistics_loop(machine_readable);
4398 interface_options interface_opts;
4400 if (global_capture_opts.ifaces->len != 1) {
4401 cmdarg_err("Need one interface");
4405 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4406 status = set_80211_channel(interface_opts.name, set_chan_arg);
4411 * "-L", "-d", and capturing act on a particular interface, so we have to
4412 * have an interface; if none was specified, pick a default.
4414 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4416 /* cmdarg_err() already called .... */
4420 if (list_link_layer_types) {
4421 /* Get the list of link-layer types for the capture device. */
4422 if_capabilities_t *caps;
4426 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4427 interface_options interface_opts;
4429 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4431 caps = get_if_capabilities(&interface_opts, &err_str);
4433 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4434 "Please check to make sure you have sufficient permissions, and that\n"
4435 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4439 if (caps->data_link_types == NULL) {
4440 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4443 if (machine_readable) /* tab-separated values to stdout */
4444 /* XXX: We need to change the format and adopt consumers */
4445 print_machine_readable_if_capabilities(caps);
4447 /* XXX: We might want to print also the interface name */
4448 capture_opts_print_if_capabilities(caps, interface_opts.name,
4449 interface_opts.monitor_mode);
4450 free_if_capabilities(caps);
4455 /* We're supposed to do a capture, or print the BPF code for a filter. */
4457 /* Let the user know what interfaces were chosen. */
4458 if (capture_child) {
4459 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4460 interface_options interface_opts;
4462 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4463 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4464 interface_opts.name);
4467 str = g_string_new("");
4469 if (global_capture_opts.ifaces->len < 2)
4471 if (global_capture_opts.ifaces->len < 4)
4474 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4475 interface_options interface_opts;
4477 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4479 if (global_capture_opts.ifaces->len > 2) {
4480 g_string_append_printf(str, ",");
4482 g_string_append_printf(str, " ");
4483 if (j == global_capture_opts.ifaces->len - 1) {
4484 g_string_append_printf(str, "and ");
4487 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4490 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4492 fprintf(stderr, "Capturing on %s\n", str->str);
4493 g_string_free(str, TRUE);
4496 /* Process the snapshot length, as that affects the generated BPF code. */
4497 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4499 #ifdef HAVE_BPF_IMAGE
4500 if (print_bpf_code) {
4501 show_filter_code(&global_capture_opts);
4506 /* We're supposed to do a capture. Process the ring buffer arguments. */
4507 capture_opts_trim_ring_num_files(&global_capture_opts);
4509 /* flush stderr prior to starting the main capture loop */
4512 /* Now start the capture. */
4513 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4517 /* capture failed */
4520 return 0; /* never here, make compiler happy */
4525 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4526 const char *message, gpointer user_data _U_)
4533 /* ignore log message, if log_level isn't interesting */
4534 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4535 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4540 switch(log_level & G_LOG_LEVEL_MASK) {
4541 case G_LOG_LEVEL_ERROR:
4544 case G_LOG_LEVEL_CRITICAL:
4547 case G_LOG_LEVEL_WARNING:
4550 case G_LOG_LEVEL_MESSAGE:
4553 case G_LOG_LEVEL_INFO:
4556 case G_LOG_LEVEL_DEBUG:
4560 fprintf(stderr, "unknown log_level %d\n", log_level);
4562 g_assert_not_reached();
4565 /* Generate the output message */
4566 if (log_level & G_LOG_LEVEL_MESSAGE) {
4567 /* normal user messages without additional infos */
4568 msg = g_strdup_printf("%s\n", message);
4570 /* create a "timestamp" */
4572 today = localtime(&curr);
4574 /* info/debug messages with additional infos */
4576 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4577 today->tm_hour, today->tm_min, today->tm_sec,
4578 log_domain != NULL ? log_domain : "",
4581 msg = g_strdup_printf("Time not representable %8s %s %s\n",
4582 log_domain != NULL ? log_domain : "",
4586 /* DEBUG & INFO msgs (if we're debugging today) */
4587 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4588 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4589 #ifdef DEBUG_DUMPCAP
4590 fprintf(stderr, "%s", msg);
4593 #ifdef DEBUG_CHILD_DUMPCAP
4594 fprintf(debug_log, "%s", msg);
4602 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4603 /* to parent especially formatted if dumpcap running as child. */
4604 if (capture_child) {
4605 sync_pipe_errmsg_to_parent(2, msg, "");
4607 fprintf(stderr, "%s", msg);
4614 /****************************************************************************************************************/
4615 /* indication report routines */
4619 report_packet_count(unsigned int packet_count)
4621 char tmp[SP_DECISIZE+1+1];
4622 static unsigned int count = 0;
4624 if (capture_child) {
4625 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
4626 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4627 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4629 count += packet_count;
4630 fprintf(stderr, "\rPackets: %u ", count);
4631 /* stderr could be line buffered */
4637 report_new_capture_file(const char *filename)
4639 if (capture_child) {
4640 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4641 pipe_write_block(2, SP_FILE, filename);
4645 * Prevent a SIGINFO handler from writing to the standard error
4646 * while we're doing so; instead, have it just set a flag telling
4647 * us to print that information when we're done.
4650 #endif /* SIGINFO */
4651 fprintf(stderr, "File: %s\n", filename);
4652 /* stderr could be line buffered */
4657 * Allow SIGINFO handlers to write.
4662 * If a SIGINFO handler asked us to write out capture counts, do so.
4665 report_counts_for_siginfo();
4666 #endif /* SIGINFO */
4671 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4673 interface_options interface_opts;
4674 char tmp[MSG_MAX_LENGTH+1+6];
4676 if (i < capture_opts->ifaces->len) {
4677 if (capture_child) {
4678 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4679 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4680 pipe_write_block(2, SP_BAD_FILTER, tmp);
4683 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
4684 * the error message below.
4686 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
4688 "Invalid capture filter \"%s\" for interface '%s'.\n"
4690 "That string isn't a valid capture filter (%s).\n"
4691 "See the User's Guide for a description of the capture filter syntax.",
4692 interface_opts.cfilter, interface_opts.name, errmsg);
4698 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4700 if (capture_child) {
4701 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4702 "Primary Error: %s", error_msg);
4703 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4704 "Secondary Error: %s", secondary_error_msg);
4705 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4707 cmdarg_err("%s", error_msg);
4708 if (secondary_error_msg[0] != '\0')
4709 cmdarg_err_cont("%s", secondary_error_msg);
4714 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
4716 char tmp[SP_DECISIZE+1+1];
4717 guint32 total_drops = pcap_drops + drops + flushed;
4719 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
4721 if (capture_child) {
4722 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4723 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
4724 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
4725 /* XXX: Need to provide interface id, changes to consumers required. */
4726 pipe_write_block(2, SP_DROPS, tmp);
4729 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
4730 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
4731 received ? 100.0 * received / (received + total_drops) : 0.0);
4732 /* stderr could be line buffered */
4738 /************************************************************************************************/
4739 /* signal_pipe handling */
4744 signal_pipe_check_running(void)
4746 /* any news from our parent? -> just stop the capture */
4750 /* if we are running standalone, no check required */
4751 if (!capture_child) {
4755 if (!sig_pipe_name || !sig_pipe_handle) {
4756 /* This shouldn't happen */
4757 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4758 "Signal pipe: No name or handle");
4763 * XXX - We should have the process ID of the parent (from the "-Z" flag)
4764 * at this point. Should we check to see if the parent is still alive,
4765 * e.g. by using OpenProcess?
4768 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
4770 if (!result || avail > 0) {
4771 /* peek failed or some bytes really available */
4772 /* (if not piping from stdin this would fail) */
4773 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4774 "Signal pipe: Stop capture: %s", sig_pipe_name);
4775 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4776 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
4777 sig_pipe_handle, result, avail);
4780 /* pipe ok and no bytes available */
4787 * Editor modelines - https://www.wireshark.org/tools/modelines.html
4792 * indent-tabs-mode: nil
4795 * vi: set shiftwidth=4 tabstop=8 expandtab:
4796 * :indentSize=4:tabSize=8:noTabs=true: