3 * Wireshark - Network traffic analyzer
4 * By Gerald Combs <gerald@wireshark.org>
5 * Copyright 1998 Gerald Combs
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include <stdlib.h> /* for exit() */
30 #ifdef HAVE_SYS_TYPES_H
31 # include <sys/types.h>
34 #ifdef HAVE_SYS_SOCKET_H
35 #include <sys/socket.h>
38 #ifdef HAVE_NETINET_IN_H
39 #include <netinet/in.h>
46 #ifdef HAVE_ARPA_INET_H
47 #include <arpa/inet.h>
50 #if defined(__APPLE__) && defined(__LP64__)
51 #include <sys/utsname.h>
57 #include <wsutil/cmdarg_err.h>
58 #include <wsutil/crash_info.h>
59 #include <wsutil/strtoi.h>
60 #include <ws_version_info.h>
62 #ifndef HAVE_GETOPT_LONG
63 #include "wsutil/wsgetopt.h"
71 # include <sys/prctl.h>
72 # include <sys/capability.h>
75 #include "ringbuffer.h"
77 #include "caputils/capture_ifinfo.h"
78 #include "caputils/capture-pcap-util.h"
79 #include "caputils/capture-pcap-util-int.h"
81 #include "caputils/capture-wpcap.h"
84 #include "writecap/pcapio.h"
87 #include <wsutil/unicode-utils.h>
94 #include <wsutil/clopts_common.h>
95 #include <wsutil/privileges.h>
97 #include "sync_pipe.h"
99 #include "capture_opts.h"
100 #include <capchild/capture_session.h>
101 #include <capchild/capture_sync.h>
103 #include "conditions.h"
104 #include "capture_stop_conditions.h"
106 #include "wsutil/tempfile.h"
108 #include "wsutil/file_util.h"
109 #include "wsutil/cpu_info.h"
110 #include "wsutil/os_version_info.h"
111 #include "wsutil/str_util.h"
112 #include "wsutil/inet_addr.h"
114 #include "caputils/ws80211_utils.h"
121 * Get information about libpcap format from "wiretap/libpcap.h".
122 * Get information about pcapng format from "wiretap/pcapng_module.h".
123 * XXX - can we just use pcap_open_offline() to read the pipe?
125 #include "wiretap/libpcap.h"
126 #include "wiretap/pcapng_module.h"
128 /**#define DEBUG_DUMPCAP**/
129 /**#define DEBUG_CHILD_DUMPCAP**/
133 #include <conio.h> /* _getch() */
137 #ifdef DEBUG_CHILD_DUMPCAP
138 FILE *debug_log; /* for logging debug messages to */
139 /* a file if DEBUG_CHILD_DUMPCAP */
143 static GAsyncQueue *pcap_queue;
144 static gint64 pcap_queue_bytes;
145 static gint64 pcap_queue_packets;
146 static gint64 pcap_queue_byte_limit = 0;
147 static gint64 pcap_queue_packet_limit = 0;
149 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
151 static gchar *sig_pipe_name = NULL;
152 static HANDLE sig_pipe_handle = NULL;
153 static gboolean signal_pipe_check_running(void);
157 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
158 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
161 /** Stop a low-level capture (stops the capture child). */
162 static void capture_loop_stop(void);
163 /** Close a pipe, or socket if \a from_socket is TRUE */
164 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
168 * Enable kernel BPF JIT compiler if available.
169 * If any calls fail, just drive on - the JIT compiler might not be
170 * enabled, but filtering will still work, and it's not clear what
171 * we could do if the calls fail; should we just report the error
172 * and not continue to capture, should we report it as a warning, or
176 enable_kernel_bpf_jit_compiler(void)
180 static const char file[] = "/proc/sys/net/core/bpf_jit_enable";
182 fd = ws_open(file, O_WRONLY);
186 written = ws_write(fd, "1", strlen("1"));
192 #if !defined (__linux__)
193 #ifndef HAVE_PCAP_BREAKLOOP
195 * We don't have pcap_breakloop(), which is the only way to ensure that
196 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
197 * won't, if the call to read the next packet or batch of packets is
198 * is interrupted by a signal on UN*X, just go back and try again to
201 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
202 * the signal handler, set a flag to stop capturing; however, without
203 * a guarantee of that sort, we can't guarantee that we'll stop capturing
204 * if the read will be retried and won't time out if no packets arrive.
206 * Therefore, on at least some platforms, we work around the lack of
207 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
208 * to wait for packets to arrive, so that we're probably going to be
209 * blocked in the select() when the signal arrives, and can just bail
210 * out of the loop at that point.
212 * However, we don't want to do that on BSD (because "select()" doesn't work
213 * correctly on BPF devices on at least some releases of some flavors of
214 * BSD), and we don't want to do it on Windows (because "select()" is
215 * something for sockets, not for arbitrary handles). (Note that "Windows"
216 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
217 * using WinPcap, not a UNIX libpcap.)
219 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
220 * on BSD times out even if no packets have arrived, so we'll eventually
221 * exit pcap_dispatch() with an indication that no packets have arrived,
222 * and will break out of the capture loop at that point.
224 * On Windows, we can't send a SIGINT to stop capturing, so none of this
225 * applies in any case.
227 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
228 * want to include it if it's not present on this platform, however.
230 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
231 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
233 # define MUST_DO_SELECT
234 # endif /* avoid select */
235 #endif /* HAVE_PCAP_BREAKLOOP */
237 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
238 * in pcap_dispatch(); on the other hand, select() works just fine there.
239 * Hence we use a select for that come what may.
241 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
242 * internally, and, with TPACKET_V3, once that's supported, it'll
243 * support timeouts, at least as I understand the way the code works.
245 #define MUST_DO_SELECT
248 /** init the capture filter */
251 INITFILTER_BAD_FILTER,
252 INITFILTER_OTHER_ERROR
253 } initfilter_status_t;
256 STATE_EXPECT_REC_HDR,
269 typedef struct _pcap_options {
274 #ifdef MUST_DO_SELECT
275 int pcap_fd; /**< pcap file descriptor */
282 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
283 /**< capture pipe (unix only "input file") */
284 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
285 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
286 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
287 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
289 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
291 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
292 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
293 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
295 char * cap_pipe_buf; /**< Pointer to the data buffer we read into */
296 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
297 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
299 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
300 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
302 cap_pipe_state_t cap_pipe_state;
303 cap_pipe_err_t cap_pipe_err;
306 GMutex *cap_pipe_read_mtx;
307 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
311 typedef struct _loop_data {
313 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
314 int err; /**< if non-zero, error seen while capturing */
315 gint packet_count; /**< Number of packets we have already captured */
316 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
317 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
319 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
325 guint64 bytes_written;
326 guint32 autostop_files;
329 typedef struct _pcap_queue_element {
330 pcap_options *pcap_opts;
331 struct pcap_pkthdr phdr;
333 } pcap_queue_element;
336 * Standard secondary message for unexpected errors.
338 static const char please_report[] =
339 "Please report this to the Wireshark developers.\n"
340 "https://bugs.wireshark.org/\n"
341 "(This is not a crash; please do not report it as such.)";
344 * This needs to be static, so that the SIGINT handler can clear the "go"
347 static loop_data global_ld;
350 * Timeout, in milliseconds, for reads from the stream of captured packets
351 * from a capture device.
353 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
354 * 64-bit applications, with sub-second timeouts not to work. The bug is
355 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
357 #if defined(__APPLE__) && defined(__LP64__)
358 static gboolean need_timeout_workaround;
360 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
362 #define CAP_READ_TIMEOUT 250
366 * Timeout, in microseconds, for reads from the stream of captured packets
367 * from a pipe. Pipes don't have the same problem that BPF devices do
368 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
369 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
370 * of the offending versions of Snow Leopard.
372 * On Windows this value is converted to milliseconds and passed to
373 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
374 * will return immediately.
377 #define PIPE_READ_TIMEOUT 100000
379 #define PIPE_READ_TIMEOUT 250000
382 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
385 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
386 const char *message, gpointer user_data _U_);
388 /* capture related options */
389 static capture_options global_capture_opts;
390 static gboolean quiet = FALSE;
391 static gboolean use_threads = FALSE;
392 static guint64 start_time;
394 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
396 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
398 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
399 int err, gboolean is_close);
401 static void WS_NORETURN exit_main(int err);
403 static void report_new_capture_file(const char *filename);
404 static void report_packet_count(unsigned int packet_count);
405 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
406 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
407 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
409 #define MSG_MAX_LENGTH 4096
411 /* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
413 create_timestamp(void) {
423 * Current time, represented as 100-nanosecond intervals since
424 * January 1, 1601, 00:00:00 UTC.
426 * I think DWORD might be signed, so cast both parts of "now"
427 * to guint32 so that the sign bit doesn't get treated specially.
429 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
430 * might want to use instead.
432 GetSystemTimeAsFileTime(&now);
433 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
434 (guint32)now.dwLowDateTime;
437 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
443 * Subtract difference, in microseconds, between January 1, 1601
444 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
446 timestamp -= G_GUINT64_CONSTANT(11644473600000000);
449 * Current time, represented as seconds and microseconds since
450 * January 1, 1970, 00:00:00 UTC.
452 gettimeofday(&now, NULL);
455 * Convert to delta in microseconds.
457 timestamp = (guint64)(now.tv_sec) * 1000000 +
458 (guint64)(now.tv_usec);
464 print_usage(FILE *output)
466 fprintf(output, "\nUsage: dumpcap [options] ...\n");
467 fprintf(output, "\n");
468 fprintf(output, "Capture interface:\n");
469 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
470 " or for remote capturing, use one of these formats:\n"
471 " rpcap://<host>/<interface>\n"
472 " TCP@<host>:<port>\n");
473 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
474 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
475 fprintf(output, " -p don't capture in promiscuous mode\n");
476 #ifdef HAVE_PCAP_CREATE
477 fprintf(output, " -I capture in monitor mode, if available\n");
479 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
480 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
482 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
483 fprintf(output, " -D print list of interfaces and exit\n");
484 fprintf(output, " -L print list of link-layer types of iface and exit\n");
485 #ifdef HAVE_BPF_IMAGE
486 fprintf(output, " -d print generated BPF code for capture filter\n");
488 fprintf(output, " -k set channel on wifi interface:\n"
489 " <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
490 fprintf(output, " -S print statistics for each interface once per second\n");
491 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
492 fprintf(output, "\n");
493 #ifdef HAVE_PCAP_REMOTE
494 fprintf(output, "RPCAP options:\n");
495 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
496 fprintf(output, " -u use UDP for RPCAP data transfer\n");
497 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
498 #ifdef HAVE_PCAP_SETSAMPLING
499 fprintf(output, " -m <sampling type> use packet sampling\n");
500 fprintf(output, " count:NUM - capture one packet of every NUM\n");
501 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
504 fprintf(output, "Stop conditions:\n");
505 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
506 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
507 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
508 fprintf(output, " files:NUM - stop after NUM files\n");
509 /*fprintf(output, "\n");*/
510 fprintf(output, "Output (files):\n");
511 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
512 fprintf(output, " -g enable group read access on the output file(s)\n");
513 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
514 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
515 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
516 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
517 fprintf(output, " -P use libpcap format instead of pcapng\n");
518 fprintf(output, " --capture-comment <comment>\n");
519 fprintf(output, " add a capture comment to the output file\n");
520 fprintf(output, " (only for pcapng)\n");
521 fprintf(output, "\n");
522 fprintf(output, "Miscellaneous:\n");
523 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
524 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
525 fprintf(output, " within dumpcap\n");
526 fprintf(output, " -t use a separate thread per interface\n");
527 fprintf(output, " -q don't report packet capture counts\n");
528 fprintf(output, " -v print version information and exit\n");
529 fprintf(output, " -h display this help and exit\n");
530 fprintf(output, "\n");
532 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
533 fprintf(output, "You might want to reset it\n");
534 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
535 fprintf(output, "\n");
537 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
538 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
539 fprintf(output, "\n");
540 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
544 * Report an error in command-line arguments.
545 * If we're a capture child, send a message back to the parent, otherwise
549 dumpcap_cmdarg_err(const char *fmt, va_list ap)
553 /* Generate a 'special format' message back to parent */
554 msg = g_strdup_vprintf(fmt, ap);
555 sync_pipe_errmsg_to_parent(2, msg, "");
558 fprintf(stderr, "dumpcap: ");
559 vfprintf(stderr, fmt, ap);
560 fprintf(stderr, "\n");
565 * Report additional information for an error in command-line arguments.
566 * If we're a capture child, send a message back to the parent, otherwise
570 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
574 msg = g_strdup_vprintf(fmt, ap);
575 sync_pipe_errmsg_to_parent(2, msg, "");
578 vfprintf(stderr, fmt, ap);
579 fprintf(stderr, "\n");
585 #if 0 /* Set to enable capability debugging */
586 /* see 'man cap_to_text()' for explanation of output */
587 /* '=' means 'all= ' ie: no capabilities */
588 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
590 print_caps(const char *pfx) {
591 cap_t caps = cap_get_proc();
592 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
593 "%s: EUID: %d Capabilities: %s", pfx,
594 geteuid(), cap_to_text(caps, NULL));
597 print_caps(const char *pfx _U_) {
602 relinquish_all_capabilities(void)
604 /* Drop any and all capabilities this process may have. */
605 /* Allowed whether or not process has any privileges. */
606 cap_t caps = cap_init(); /* all capabilities initialized to off */
607 print_caps("Pre-clear");
608 if (cap_set_proc(caps)) {
609 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
611 print_caps("Post-clear");
617 get_capture_device_open_failure_messages(const char *open_err_str,
619 char *errmsg, size_t errmsg_len,
620 char *secondary_errmsg,
621 size_t secondary_errmsg_len)
624 const char *libpcap_warn;
625 static const char ppamsg[] = "can't find PPA for ";
628 g_snprintf(errmsg, (gulong) errmsg_len,
629 "The capture session could not be initiated on interface '%s' (%s).",
630 iface, open_err_str);
633 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
635 "In order to capture packets, WinPcap must be installed; see\n"
637 " https://www.winpcap.org/\n"
639 "for a downloadable version of WinPcap and for instructions on how to install\n"
642 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
644 "Please check that \"%s\" is the proper interface.\n"
647 "Help can be found at:\n"
649 " https://wiki.wireshark.org/WinPcap\n"
650 " https://wiki.wireshark.org/CaptureSetup\n",
654 /* If we got a "can't find PPA for X" message, warn the user (who
655 is running dumpcap on HP-UX) that they don't have a version of
656 libpcap that properly handles HP-UX (libpcap 0.6.x and later
657 versions, which properly handle HP-UX, say "can't find /dev/dlpi
658 PPA for X" rather than "can't find PPA for X"). */
659 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
662 "You are running (T)Wireshark with a version of the libpcap library\n"
663 "that doesn't handle HP-UX network devices well; this means that\n"
664 "(T)Wireshark may not be able to capture packets.\n"
666 "To fix this, you should install libpcap 0.6.2, or a later version\n"
667 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
668 "packaged binary form from the Software Porting And Archive Centre\n"
669 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
670 "at the URL lists a number of mirror sites.";
674 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
675 "Please check to make sure you have sufficient permissions, and that you have "
676 "the proper interface or pipe specified.%s", libpcap_warn);
681 compile_capture_filter(const char *iface, pcap_t *pcap_h,
682 struct bpf_program *fcode, const char *cfilter)
684 bpf_u_int32 netnum, netmask;
685 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
687 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
689 * Well, we can't get the netmask for this interface; it's used
690 * only for filters that check for broadcast IP addresses, so
691 * we just punt and use 0. It might be nice to warn the user,
692 * but that's a pain in a GUI application, as it'd involve popping
693 * up a message box, and it's not clear how often this would make
694 * a difference (only filters that check for IP broadcast addresses
698 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
703 * Sigh. Older versions of libpcap don't properly declare the
704 * third argument to pcap_compile() as a const pointer. Cast
708 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
714 #ifdef HAVE_BPF_IMAGE
716 show_filter_code(capture_options *capture_opts)
718 interface_options interface_opts;
720 gchar open_err_str[PCAP_ERRBUF_SIZE];
721 char errmsg[MSG_MAX_LENGTH+1];
722 char secondary_errmsg[MSG_MAX_LENGTH+1];
723 struct bpf_program fcode;
724 struct bpf_insn *insn;
728 for (j = 0; j < capture_opts->ifaces->len; j++) {
729 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
730 pcap_h = open_capture_device(capture_opts, &interface_opts,
731 CAP_READ_TIMEOUT, &open_err_str);
732 if (pcap_h == NULL) {
733 /* Open failed; get messages */
734 get_capture_device_open_failure_messages(open_err_str,
736 errmsg, sizeof errmsg,
738 sizeof secondary_errmsg);
739 /* And report them */
740 report_capture_error(errmsg, secondary_errmsg);
744 /* Set the link-layer type. */
745 if (!set_pcap_datalink(pcap_h, interface_opts.linktype, interface_opts.name,
746 errmsg, sizeof errmsg,
747 secondary_errmsg, sizeof secondary_errmsg)) {
749 report_capture_error(errmsg, secondary_errmsg);
753 /* OK, try to compile the capture filter. */
754 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
755 interface_opts.cfilter)) {
757 report_cfilter_error(capture_opts, j, errmsg);
762 /* Now print the filter code. */
763 insn = fcode.bf_insns;
765 for (i = 0; i < fcode.bf_len; insn++, i++)
766 printf("%s\n", bpf_image(insn, i));
768 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
769 /* to remove any suid privileges. */
770 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
771 /* (euid/egid have already previously been set to ruid/rgid. */
772 /* (See comment in main() for details) */
774 relinquish_special_privs_perm();
776 relinquish_all_capabilities();
779 /* Let our parent know we succeeded. */
780 pipe_write_block(2, SP_SUCCESS, NULL);
787 * capture_interface_list() is expected to do the right thing to get
788 * a list of interfaces.
790 * In most of the programs in the Wireshark suite, "the right thing"
791 * is to run dumpcap and ask it for the list, because dumpcap may
792 * be the only program in the suite with enough privileges to get
795 * In dumpcap itself, however, we obviously can't run dumpcap to
796 * ask for the list. Therefore, our capture_interface_list() should
797 * just call get_interface_list().
800 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
802 return get_interface_list(err, err_str);
805 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
807 * Output a machine readable list of the interfaces
808 * This list is retrieved by the sync_interface_list_open() function
809 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
812 print_machine_readable_interfaces(GList *if_list)
819 char addr_str[ADDRSTRLEN];
822 /* Let our parent know we succeeded. */
823 pipe_write_block(2, SP_SUCCESS, NULL);
826 i = 1; /* Interface id number */
827 for (if_entry = g_list_first(if_list); if_entry != NULL;
828 if_entry = g_list_next(if_entry)) {
829 if_info = (if_info_t *)if_entry->data;
830 printf("%d. %s\t", i++, if_info->name);
833 * Print the contents of the if_entry struct in a parseable format.
834 * Each if_entry element is tab-separated. Addresses are comma-
837 /* XXX - Make sure our description doesn't contain a tab */
838 if (if_info->vendor_description != NULL)
839 printf("%s\t", if_info->vendor_description);
843 /* XXX - Make sure our friendly name doesn't contain a tab */
844 if (if_info->friendly_name != NULL)
845 printf("%s\t", if_info->friendly_name);
849 printf("%i\t", if_info->type);
851 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
852 addr = g_slist_next(addr)) {
853 if (addr != g_slist_nth(if_info->addrs, 0))
856 if_addr = (if_addr_t *)addr->data;
857 switch(if_addr->ifat_type) {
859 if (ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str,
861 printf("%s", addr_str);
863 printf("<unknown IPv4>");
867 if (ws_inet_ntop6(&if_addr->addr.ip6_addr,
868 addr_str, ADDRSTRLEN)) {
869 printf("%s", addr_str);
871 printf("<unknown IPv6>");
875 printf("<type unknown %i>", if_addr->ifat_type);
879 if (if_info->loopback)
880 printf("\tloopback");
884 printf("\t%s", if_info->extcap);
891 * If you change the machine-readable output format of this function,
892 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
895 print_machine_readable_if_capabilities(if_capabilities_t *caps)
898 data_link_info_t *data_link_info;
899 const gchar *desc_str;
902 /* Let our parent know we succeeded. */
903 pipe_write_block(2, SP_SUCCESS, NULL);
906 if (caps->can_set_rfmon)
910 for (lt_entry = caps->data_link_types; lt_entry != NULL;
911 lt_entry = g_list_next(lt_entry)) {
912 data_link_info = (data_link_info_t *)lt_entry->data;
913 if (data_link_info->description != NULL)
914 desc_str = data_link_info->description;
916 desc_str = "(not supported)";
917 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
927 /* Print the number of packets captured for each interface until we're killed. */
929 print_statistics_loop(gboolean machine_readable)
931 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
937 char errbuf[PCAP_ERRBUF_SIZE];
940 if_list = get_interface_list(&err, &err_str);
941 if (if_list == NULL) {
943 cmdarg_err("There are no interfaces on which a capture can be done");
945 cmdarg_err("%s", err_str);
951 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
952 if_info = (if_info_t *)if_entry->data;
955 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
956 * connections. We avoid collecting stats on them.
958 if (!strncmp(if_info->name, "nf", 2)) {
959 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
965 #ifdef HAVE_PCAP_OPEN
966 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
968 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
972 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
973 if_stat->name = g_strdup(if_info->name);
975 stat_list = g_list_append(stat_list, if_stat);
980 cmdarg_err("There are no interfaces on which a capture can be done");
985 /* Let our parent know we succeeded. */
986 pipe_write_block(2, SP_SUCCESS, NULL);
989 if (!machine_readable) {
990 printf("%-15s %10s %10s\n", "Interface", "Received",
995 while (global_ld.go) {
996 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
997 if_stat = (if_stat_t *)stat_entry->data;
998 pcap_stats(if_stat->pch, &ps);
1000 if (!machine_readable) {
1001 printf("%-15s %10u %10u\n", if_stat->name,
1002 ps.ps_recv, ps.ps_drop);
1004 printf("%s\t%u\t%u\n", if_stat->name,
1005 ps.ps_recv, ps.ps_drop);
1010 /* If we have a dummy signal pipe check it */
1011 if (!signal_pipe_check_running()) {
1012 global_ld.go = FALSE;
1020 /* XXX - Not reached. Should we look for 'q' in stdin? */
1021 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1022 if_stat = (if_stat_t *)stat_entry->data;
1023 pcap_close(if_stat->pch);
1024 g_free(if_stat->name);
1027 g_list_free(stat_list);
1028 free_interface_list(if_list);
1036 capture_cleanup_handler(DWORD dwCtrlType)
1038 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1039 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1040 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1041 like SIGTERM at least when the machine's shutting down.
1043 For now, if we're running as a command rather than a capture child,
1044 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1045 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1046 in that way on UN*X.
1048 If we're not running as a capture child, we might be running as
1049 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1050 user logs out. (XXX - can we explicitly check whether we're
1051 running as a service?) */
1053 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1054 "Console: Control signal");
1055 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1056 "Console: Control signal, CtrlType: %u", dwCtrlType);
1058 /* Keep capture running if we're a service and a user logs off */
1059 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1060 capture_loop_stop();
1068 capture_cleanup_handler(int signum _U_)
1070 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1071 SIGTERM. We assume that if the user wanted it to keep running
1072 after they logged out, they'd have nohupped it. */
1074 /* Note: don't call g_log() in the signal handler: if we happened to be in
1075 * g_log() in process context when the signal came in, g_log will detect
1076 * the "recursion" and abort.
1079 capture_loop_stop();
1085 report_capture_count(gboolean reportit)
1087 /* Don't print this if we're a capture child. */
1088 if (!capture_child && reportit) {
1089 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packet_count);
1090 /* stderr could be line buffered */
1098 report_counts_for_siginfo(void)
1100 report_capture_count(quiet);
1101 infoprint = FALSE; /* we just reported it */
1105 report_counts_siginfo(int signum _U_)
1107 int sav_errno = errno;
1109 /* If we've been told to delay printing, just set a flag asking
1110 that we print counts (if we're supposed to), otherwise print
1111 the count of packets captured (if we're supposed to). */
1115 report_counts_for_siginfo();
1118 #endif /* SIGINFO */
1121 exit_main(int status)
1124 /* Shutdown windows sockets */
1127 /* can be helpful for debugging */
1128 #ifdef DEBUG_DUMPCAP
1129 printf("Press any key\n");
1140 * If we were linked with libcap (not related to libpcap), make sure we have
1141 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1142 * (See comment in main() for details)
1145 relinquish_privs_except_capture(void)
1147 /* If 'started_with_special_privs' (ie: suid) then enable for
1148 * ourself the NET_ADMIN and NET_RAW capabilities and then
1149 * drop our suid privileges.
1151 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1152 * stuff we don't need (and shouldn't have).
1153 * CAP_NET_RAW: Packet capture (raw sockets).
1156 if (started_with_special_privs()) {
1157 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1158 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1160 cap_t caps = cap_init(); /* all capabilities initialized to off */
1162 print_caps("Pre drop, pre set");
1164 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1165 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1168 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1169 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1171 if (cap_set_proc(caps)) {
1172 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1174 print_caps("Pre drop, post set");
1176 relinquish_special_privs_perm();
1178 print_caps("Post drop, pre set");
1179 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1180 if (cap_set_proc(caps)) {
1181 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1183 print_caps("Post drop, post set");
1189 #endif /* HAVE_LIBCAP */
1191 /* Take care of byte order in the libpcap headers read from pipes.
1192 * (function taken from wiretap/libpcap.c) */
1194 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1197 /* Byte-swap the record header fields. */
1198 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1199 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1200 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1201 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1204 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1205 swapped, in order to match the BPF header layout.
1207 Unfortunately, some files were, according to a comment in the "libpcap"
1208 source, written with version 2.3 in their headers but without the
1209 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1210 would make no sense - we assume that we need to swap them. */
1211 if (hdr->version_major == 2 &&
1212 (hdr->version_minor < 3 ||
1213 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1216 temp = rechdr->orig_len;
1217 rechdr->orig_len = rechdr->incl_len;
1218 rechdr->incl_len = temp;
1222 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1226 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1230 return recv(pipe_fd, buf, (int)sz, 0);
1235 return ws_read(pipe_fd, buf, sz);
1241 * Thread function that reads from a pipe and pushes the data
1242 * to the main application thread.
1245 * XXX Right now we use async queues for basic signaling. The main thread
1246 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1247 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1248 * Iff the read is successful cap_pipe_read pushes an item onto
1249 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1250 * the queues themselves (yet).
1252 * We might want to move some of the cap_pipe_dispatch logic here so that
1253 * we can let cap_thread_read run independently, queuing up multiple reads
1254 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1256 static void *cap_thread_read(void *arg)
1258 pcap_options *pcap_opts;
1261 DWORD b, last_err, bytes_read;
1267 pcap_opts = (pcap_options *)arg;
1268 while (pcap_opts->cap_pipe_err == PIPOK) {
1269 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1270 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1272 while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1273 if ((pcap_opts->from_cap_socket)
1279 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1280 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1283 pcap_opts->cap_pipe_err = PIPEOF;
1287 pcap_opts->cap_pipe_err = PIPERR;
1298 /* If we try to use read() on a named pipe on Windows with partial
1299 * data it appears to return EOF.
1301 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1302 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1307 last_err = GetLastError();
1308 if (last_err == ERROR_MORE_DATA) {
1310 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1311 pcap_opts->cap_pipe_err = PIPEOF;
1315 pcap_opts->cap_pipe_err = PIPERR;
1318 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1319 pcap_opts->cap_pipe_err = PIPEOF;
1326 pcap_opts->cap_pipe_bytes_read = bytes_read;
1327 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1328 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1330 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1336 /* Provide select() functionality for a single file descriptor
1337 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1339 * Returns the same values as select.
1342 cap_pipe_select(int pipe_fd)
1345 struct timeval timeout;
1348 FD_SET(pipe_fd, &rfds);
1350 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1351 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1353 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1356 #define DEF_TCP_PORT 19000
1359 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1361 char *sockname = pipename + 4;
1362 struct sockaddr_in sa;
1369 memset(&sa, 0, sizeof(sa));
1371 p = strchr(sockname, ':');
1373 len = strlen(sockname);
1374 port = DEF_TCP_PORT;
1378 port = strtoul(p + 1, &p, 10);
1379 if (*p || port > 65535) {
1388 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1390 if (!ws_inet_pton4(buf, (guint32 *)&sa.sin_addr)) {
1394 sa.sin_family = AF_INET;
1395 sa.sin_port = g_htons((u_short)port);
1397 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1398 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1400 LPTSTR errorText = NULL;
1403 lastError = WSAGetLastError();
1404 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1405 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1406 FORMAT_MESSAGE_IGNORE_INSERTS,
1407 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1408 (LPTSTR)&errorText, 0, NULL);
1410 g_snprintf(errmsg, errmsgl,
1411 "The capture session could not be initiated due to the socket error: \n"
1413 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1415 LocalFree(errorText);
1417 " %d: %s", errno, g_strerror(errno));
1419 pcap_opts->cap_pipe_err = PIPERR;
1422 cap_pipe_close(fd, TRUE);
1426 pcap_opts->from_cap_socket = TRUE;
1430 g_snprintf(errmsg, errmsgl,
1431 "The capture session could not be initiated because\n"
1432 "\"%s\" is not a valid socket specification", pipename);
1433 pcap_opts->cap_pipe_err = PIPERR;
1437 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1441 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1445 closesocket(pipe_fd);
1452 /* Mimic pcap_open_live() for pipe captures
1454 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1455 * open it, and read the header.
1457 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1458 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1460 cap_pipe_open_live(char *pipename,
1461 pcap_options *pcap_opts,
1462 struct pcap_hdr *hdr,
1463 char *errmsg, int errmsgl)
1466 ws_statb64 pipe_stat;
1467 struct sockaddr_un sa;
1472 char* extcap_pipe_name;
1476 gboolean extcap_pipe = FALSE;
1477 interface_options interface_opts;
1480 int fd = -1, sel_ret;
1483 pcap_opts->cap_pipe_fd = -1;
1485 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1488 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1491 * XXX - this blocks until a pcap per-file header has been written to
1492 * the pipe, so it could block indefinitely.
1494 if (strcmp(pipename, "-") == 0) {
1496 fd = 0; /* read from stdin */
1498 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1500 } else if (!strncmp(pipename, "TCP@", 4)) {
1501 if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
1507 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
1512 if ( g_strrstr(interface_opts.name, EXTCAP_PIPE_PREFIX) != NULL )
1516 if (ws_stat64(pipename, &pipe_stat) < 0) {
1517 if (errno == ENOENT || errno == ENOTDIR)
1518 pcap_opts->cap_pipe_err = PIPNEXIST;
1520 g_snprintf(errmsg, errmsgl,
1521 "The capture session could not be initiated "
1522 "due to error getting information on pipe/socket: %s.", g_strerror(errno));
1523 pcap_opts->cap_pipe_err = PIPERR;
1527 if (S_ISFIFO(pipe_stat.st_mode)) {
1528 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1530 g_snprintf(errmsg, errmsgl,
1531 "The capture session could not be initiated "
1532 "due to error on pipe open: %s.", g_strerror(errno));
1533 pcap_opts->cap_pipe_err = PIPERR;
1536 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1537 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1539 g_snprintf(errmsg, errmsgl,
1540 "The capture session could not be initiated "
1541 "due to error on socket create: %s.", g_strerror(errno));
1542 pcap_opts->cap_pipe_err = PIPERR;
1545 sa.sun_family = AF_UNIX;
1547 * The Single UNIX Specification says:
1549 * The size of sun_path has intentionally been left undefined.
1550 * This is because different implementations use different sizes.
1551 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1552 * of 104. Since most implementations originate from BSD versions,
1553 * the size is typically in the range 92 to 108.
1555 * Applications should not assume a particular length for sun_path
1556 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1560 * The <sys/un.h> header shall define the sockaddr_un structure,
1561 * which shall include at least the following members:
1563 * sa_family_t sun_family Address family.
1564 * char sun_path[] Socket pathname.
1566 * so we assume that it's an array, with a specified size,
1567 * and that the size reflects the maximum path length.
1569 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1570 /* Path name too long */
1571 g_snprintf(errmsg, errmsgl,
1572 "The capture session coud not be initiated "
1573 "due to error on socket connect: Path name too long.");
1574 pcap_opts->cap_pipe_err = PIPERR;
1578 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1580 g_snprintf(errmsg, errmsgl,
1581 "The capture session coud not be initiated "
1582 "due to error on socket connect: %s.", g_strerror(errno));
1583 pcap_opts->cap_pipe_err = PIPERR;
1588 if (S_ISCHR(pipe_stat.st_mode)) {
1590 * Assume the user specified an interface on a system where
1591 * interfaces are in /dev. Pretend we haven't seen it.
1593 pcap_opts->cap_pipe_err = PIPNEXIST;
1595 g_snprintf(errmsg, errmsgl,
1596 "The capture session could not be initiated because\n"
1597 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1598 pcap_opts->cap_pipe_err = PIPERR;
1604 #define PIPE_STR "\\pipe\\"
1605 /* Under Windows, named pipes _must_ have the form
1606 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1608 pncopy = g_strdup(pipename);
1609 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1610 pos = strchr(pncopy + 3, '\\');
1611 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1618 g_snprintf(errmsg, errmsgl,
1619 "The capture session could not be initiated because\n"
1620 "\"%s\" is neither an interface nor a pipe.", pipename);
1621 pcap_opts->cap_pipe_err = PIPNEXIST;
1625 extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
1626 extcap_pipe = strstr(interface_opts.name, extcap_pipe_name) ? TRUE : FALSE;
1627 g_free(extcap_pipe_name);
1630 /* Wait for the pipe to appear */
1635 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1638 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1639 OPEN_EXISTING, 0, NULL);
1641 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
1644 if (GetLastError() != ERROR_PIPE_BUSY) {
1645 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1646 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1647 g_snprintf(errmsg, errmsgl,
1648 "The capture session on \"%s\" could not be started "
1649 "due to error on pipe open: %s (error %d).",
1650 pipename, utf_16to8(err_str), GetLastError());
1652 pcap_opts->cap_pipe_err = PIPERR;
1656 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1657 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1658 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1659 g_snprintf(errmsg, errmsgl,
1660 "The capture session on \"%s\" timed out during "
1661 "pipe open: %s (error %d).",
1662 pipename, utf_16to8(err_str), GetLastError());
1664 pcap_opts->cap_pipe_err = PIPERR;
1671 pcap_opts->from_cap_pipe = TRUE;
1674 if (pcap_opts->from_cap_socket)
1677 /* read the pcap header */
1679 while (bytes_read < sizeof magic) {
1681 g_snprintf(errmsg, errmsgl, "Invalid file descriptor.");
1685 sel_ret = cap_pipe_select(fd);
1687 g_snprintf(errmsg, errmsgl,
1688 "Unexpected error from select: %s.", g_strerror(errno));
1690 } else if (sel_ret > 0) {
1691 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1692 sizeof magic-bytes_read,
1693 pcap_opts->from_cap_socket);
1695 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1696 if (extcap_pipe && b <= 0)
1701 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1703 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1713 #if GLIB_CHECK_VERSION(2,31,0)
1714 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
1716 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
1719 pcap_opts->cap_pipe_buf = (char *) &magic;
1720 pcap_opts->cap_pipe_bytes_read = 0;
1721 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
1722 /* We don't have to worry about cap_pipe_read_mtx here */
1723 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1724 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
1725 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1726 if (pcap_opts->cap_pipe_bytes_read <= 0 && extcap_pipe)
1729 if (pcap_opts->cap_pipe_bytes_read <= 0) {
1730 if (pcap_opts->cap_pipe_bytes_read == 0)
1731 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1733 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1742 case PCAP_NSEC_MAGIC:
1743 /* Host that wrote it has our byte order, and was running
1744 a program using either standard or ss990417 libpcap. */
1745 pcap_opts->cap_pipe_byte_swapped = FALSE;
1746 pcap_opts->cap_pipe_modified = FALSE;
1747 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
1749 case PCAP_MODIFIED_MAGIC:
1750 /* Host that wrote it has our byte order, but was running
1751 a program using either ss990915 or ss991029 libpcap. */
1752 pcap_opts->cap_pipe_byte_swapped = FALSE;
1753 pcap_opts->cap_pipe_modified = TRUE;
1755 case PCAP_SWAPPED_MAGIC:
1756 case PCAP_SWAPPED_NSEC_MAGIC:
1757 /* Host that wrote it has a byte order opposite to ours,
1758 and was running a program using either standard or
1759 ss990417 libpcap. */
1760 pcap_opts->cap_pipe_byte_swapped = TRUE;
1761 pcap_opts->cap_pipe_modified = FALSE;
1762 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
1764 case PCAP_SWAPPED_MODIFIED_MAGIC:
1765 /* Host that wrote it out has a byte order opposite to
1766 ours, and was running a program using either ss990915
1767 or ss991029 libpcap. */
1768 pcap_opts->cap_pipe_byte_swapped = TRUE;
1769 pcap_opts->cap_pipe_modified = TRUE;
1771 case BLOCK_TYPE_SHB:
1772 /* This isn't pcap, it's pcapng. We don't yet support
1774 g_snprintf(errmsg, errmsgl, "Capturing from a pipe doesn't support pcapng format.");
1777 /* Not a pcap type we know about, or not pcap at all. */
1778 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format or not libpcap data.");
1783 if (pcap_opts->from_cap_socket)
1786 /* Read the rest of the header */
1788 while (bytes_read < sizeof(struct pcap_hdr)) {
1789 sel_ret = cap_pipe_select(fd);
1791 g_snprintf(errmsg, errmsgl,
1792 "Unexpected error from select: %s.", g_strerror(errno));
1794 } else if (sel_ret > 0) {
1795 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
1796 sizeof(struct pcap_hdr) - bytes_read,
1797 pcap_opts->from_cap_socket);
1800 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1802 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s.",
1812 pcap_opts->cap_pipe_buf = (char *) hdr;
1813 pcap_opts->cap_pipe_bytes_read = 0;
1814 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1815 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1816 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
1817 if (pcap_opts->cap_pipe_bytes_read <= 0) {
1818 if (pcap_opts->cap_pipe_bytes_read == 0)
1819 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1821 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s.",
1828 if (pcap_opts->cap_pipe_byte_swapped) {
1829 /* Byte-swap the header fields about which we care. */
1830 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
1831 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
1832 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
1833 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
1835 pcap_opts->linktype = hdr->network;
1837 if (hdr->version_major < 2) {
1838 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1842 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
1843 pcap_opts->cap_pipe_err = PIPOK;
1844 pcap_opts->cap_pipe_fd = fd;
1848 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1849 pcap_opts->cap_pipe_err = PIPERR;
1850 cap_pipe_close(fd, pcap_opts->from_cap_socket);
1851 pcap_opts->cap_pipe_fd = -1;
1855 /* We read one record from the pipe, take care of byte order in the record
1856 * header, write the record to the capture file, and update capture statistics. */
1858 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
1860 struct pcap_pkthdr phdr;
1861 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1864 #if !GLIB_CHECK_VERSION(2,31,18)
1872 #ifdef LOG_CAPTURE_VERBOSE
1873 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1876 switch (pcap_opts->cap_pipe_state) {
1878 case STATE_EXPECT_REC_HDR:
1880 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
1883 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
1884 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
1885 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1886 pcap_opts->cap_pipe_bytes_read = 0;
1889 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
1890 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1891 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1896 case STATE_READ_REC_HDR:
1898 if (pcap_opts->from_cap_socket)
1901 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
1902 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
1905 result = PD_PIPE_EOF;
1907 result = PD_PIPE_ERR;
1910 pcap_opts->cap_pipe_bytes_read += b;
1914 #if GLIB_CHECK_VERSION(2,31,18)
1915 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
1917 g_get_current_time(&wait_time);
1918 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
1919 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
1921 if (pcap_opts->cap_pipe_err == PIPEOF) {
1922 result = PD_PIPE_EOF;
1924 } else if (pcap_opts->cap_pipe_err == PIPERR) {
1925 result = PD_PIPE_ERR;
1933 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
1935 result = PD_REC_HDR_READ;
1938 case STATE_EXPECT_DATA:
1940 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
1943 pcap_opts->cap_pipe_state = STATE_READ_DATA;
1944 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
1945 pcap_opts->cap_pipe_bytes_read = 0;
1948 pcap_opts->cap_pipe_buf = (char *) data;
1949 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1950 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1955 case STATE_READ_DATA:
1957 if (pcap_opts->from_cap_socket)
1960 b = cap_pipe_read(pcap_opts->cap_pipe_fd,
1961 data+pcap_opts->cap_pipe_bytes_read,
1962 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
1963 pcap_opts->from_cap_socket);
1966 result = PD_PIPE_EOF;
1968 result = PD_PIPE_ERR;
1971 pcap_opts->cap_pipe_bytes_read += b;
1976 #if GLIB_CHECK_VERSION(2,31,18)
1977 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
1979 g_get_current_time(&wait_time);
1980 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
1981 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
1982 #endif /* GLIB_CHECK_VERSION(2,31,18) */
1983 if (pcap_opts->cap_pipe_err == PIPEOF) {
1984 result = PD_PIPE_EOF;
1986 } else if (pcap_opts->cap_pipe_err == PIPERR) {
1987 result = PD_PIPE_ERR;
1995 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
1997 result = PD_DATA_READ;
2001 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2004 } /* switch (pcap_opts->cap_pipe_state) */
2007 * We've now read as much data as we were expecting, so process it.
2011 case PD_REC_HDR_READ:
2012 /* We've read the header. Take care of byte order. */
2013 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2014 &pcap_opts->cap_pipe_rechdr.hdr);
2015 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2016 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2017 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2021 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2022 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2025 /* no data to read? fall through */
2028 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2029 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2030 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2031 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2032 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2035 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2037 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2039 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2043 pcap_opts->cap_pipe_err = PIPEOF;
2048 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2049 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2050 g_snprintf(errmsg, errmsgl,
2051 "Error reading from pipe: %s (error %d)",
2052 utf_16to8(err_str), GetLastError());
2055 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2063 pcap_opts->cap_pipe_err = PIPERR;
2064 /* Return here rather than inside the switch to prevent GCC warning */
2069 /** Open the capture input file (pcap or capture pipe).
2070 * Returns TRUE if it succeeds, FALSE otherwise. */
2072 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2073 char *errmsg, size_t errmsg_len,
2074 char *secondary_errmsg, size_t secondary_errmsg_len)
2076 gchar open_err_str[PCAP_ERRBUF_SIZE];
2077 gchar *sync_msg_str;
2078 interface_options interface_opts;
2079 pcap_options *pcap_opts;
2083 WORD wVersionRequested;
2087 /* XXX - opening Winsock on tshark? */
2089 /* Initialize Windows Socket if we are in a Win32 OS
2090 This needs to be done before querying the interface for network/netmask */
2092 /* XXX - do we really require 1.1 or earlier?
2093 Are there any versions that support only 2.0 or higher? */
2094 wVersionRequested = MAKEWORD(1, 1);
2095 err = WSAStartup(wVersionRequested, &wsaData);
2099 case WSASYSNOTREADY:
2100 g_snprintf(errmsg, (gulong) errmsg_len,
2101 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2104 case WSAVERNOTSUPPORTED:
2105 g_snprintf(errmsg, (gulong) errmsg_len,
2106 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2107 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2110 case WSAEINPROGRESS:
2111 g_snprintf(errmsg, (gulong) errmsg_len,
2112 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2116 g_snprintf(errmsg, (gulong) errmsg_len,
2117 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2121 g_snprintf(errmsg, (gulong) errmsg_len,
2122 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2126 g_snprintf(errmsg, (gulong) errmsg_len,
2127 "Couldn't initialize Windows Sockets: error %d", err);
2130 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2134 if ((use_threads == FALSE) &&
2135 (capture_opts->ifaces->len > 1)) {
2136 g_snprintf(errmsg, (gulong) errmsg_len,
2137 "Using threads is required for capturing on multiple interfaces.");
2141 for (i = 0; i < capture_opts->ifaces->len; i++) {
2142 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2143 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2144 if (pcap_opts == NULL) {
2145 g_snprintf(errmsg, (gulong) errmsg_len,
2146 "Could not allocate memory.");
2149 pcap_opts->received = 0;
2150 pcap_opts->dropped = 0;
2151 pcap_opts->flushed = 0;
2152 pcap_opts->pcap_h = NULL;
2153 #ifdef MUST_DO_SELECT
2154 pcap_opts->pcap_fd = -1;
2156 pcap_opts->pcap_err = FALSE;
2157 pcap_opts->interface_id = i;
2158 pcap_opts->tid = NULL;
2159 pcap_opts->snaplen = 0;
2160 pcap_opts->linktype = -1;
2161 pcap_opts->ts_nsec = FALSE;
2162 pcap_opts->from_cap_pipe = FALSE;
2163 pcap_opts->from_cap_socket = FALSE;
2164 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2165 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2167 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2169 pcap_opts->cap_pipe_fd = -1;
2170 pcap_opts->cap_pipe_modified = FALSE;
2171 pcap_opts->cap_pipe_byte_swapped = FALSE;
2173 pcap_opts->cap_pipe_buf = NULL;
2175 pcap_opts->cap_pipe_bytes_to_read = 0;
2176 pcap_opts->cap_pipe_bytes_read = 0;
2177 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2178 pcap_opts->cap_pipe_err = PIPOK;
2180 #if GLIB_CHECK_VERSION(2,31,0)
2181 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2182 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2184 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2186 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2187 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2189 g_array_append_val(ld->pcaps, pcap_opts);
2191 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2192 pcap_opts->pcap_h = open_capture_device(capture_opts, &interface_opts,
2193 CAP_READ_TIMEOUT, &open_err_str);
2195 if (pcap_opts->pcap_h != NULL) {
2196 /* we've opened "iface" as a network device */
2198 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2199 /* Find out if we're getting nanosecond-precision time stamps */
2200 pcap_opts->ts_nsec = have_high_resolution_timestamp(pcap_opts->pcap_h);
2203 #if defined(HAVE_PCAP_SETSAMPLING)
2204 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2205 struct pcap_samp *samp;
2207 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2208 switch (interface_opts.sampling_method) {
2209 case CAPTURE_SAMP_BY_COUNT:
2210 samp->method = PCAP_SAMP_1_EVERY_N;
2213 case CAPTURE_SAMP_BY_TIMER:
2214 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2218 sync_msg_str = g_strdup_printf(
2219 "Unknown sampling method %d specified,\n"
2220 "continue without packet sampling",
2221 interface_opts.sampling_method);
2222 report_capture_error("Couldn't set the capture "
2223 "sampling", sync_msg_str);
2224 g_free(sync_msg_str);
2226 samp->value = interface_opts.sampling_param;
2228 report_capture_error("Couldn't set the capture sampling",
2229 "Cannot get packet sampling data structure");
2234 /* setting the data link type only works on real interfaces */
2235 if (!set_pcap_datalink(pcap_opts->pcap_h, interface_opts.linktype,
2236 interface_opts.name,
2238 secondary_errmsg, secondary_errmsg_len)) {
2241 pcap_opts->linktype = get_pcap_datalink(pcap_opts->pcap_h, interface_opts.name);
2243 /* We couldn't open "iface" as a network device. */
2244 /* Try to open it as a pipe */
2245 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2248 if (pcap_opts->cap_pipe_fd == -1) {
2250 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2252 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2254 * We tried opening as an interface, and that failed,
2255 * so we tried to open it as a pipe, but the pipe
2256 * doesn't exist. Report the error message for
2259 get_capture_device_open_failure_messages(open_err_str,
2260 interface_opts.name,
2264 secondary_errmsg_len);
2267 * Else pipe (or file) does exist and cap_pipe_open_live() has
2272 /* cap_pipe_open_live() succeeded; don't want
2273 error message from pcap_open_live() */
2274 open_err_str[0] = '\0';
2278 /* XXX - will this work for tshark? */
2279 #ifdef MUST_DO_SELECT
2280 if (!pcap_opts->from_cap_pipe) {
2281 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2282 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2284 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2289 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2290 returned a warning; print it, but keep capturing. */
2291 if (open_err_str[0] != '\0') {
2292 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2293 report_capture_error(sync_msg_str, "");
2294 g_free(sync_msg_str);
2296 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2297 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2300 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2301 /* to remove any suid privileges. */
2302 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2303 /* (euid/egid have already previously been set to ruid/rgid. */
2304 /* (See comment in main() for details) */
2306 relinquish_special_privs_perm();
2308 relinquish_all_capabilities();
2313 /* close the capture input file (pcap or capture pipe) */
2314 static void capture_loop_close_input(loop_data *ld)
2317 pcap_options *pcap_opts;
2319 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2321 for (i = 0; i < ld->pcaps->len; i++) {
2322 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2323 /* if open, close the capture pipe "input file" */
2324 if (pcap_opts->cap_pipe_fd >= 0) {
2325 g_assert(pcap_opts->from_cap_pipe);
2326 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2327 pcap_opts->cap_pipe_fd = -1;
2330 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2331 CloseHandle(pcap_opts->cap_pipe_h);
2332 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2335 /* if open, close the pcap "input file" */
2336 if (pcap_opts->pcap_h != NULL) {
2337 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2338 pcap_close(pcap_opts->pcap_h);
2339 pcap_opts->pcap_h = NULL;
2346 /* Shut down windows sockets */
2352 /* init the capture filter */
2353 static initfilter_status_t
2354 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2355 const gchar * name, const gchar * cfilter)
2357 struct bpf_program fcode;
2359 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2361 /* capture filters only work on real interfaces */
2362 if (cfilter && !from_cap_pipe) {
2363 /* A capture filter was specified; set it up. */
2364 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2365 /* Treat this specially - our caller might try to compile this
2366 as a display filter and, if that succeeds, warn the user that
2367 the display and capture filter syntaxes are different. */
2368 return INITFILTER_BAD_FILTER;
2370 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2371 #ifdef HAVE_PCAP_FREECODE
2372 pcap_freecode(&fcode);
2374 return INITFILTER_OTHER_ERROR;
2376 #ifdef HAVE_PCAP_FREECODE
2377 pcap_freecode(&fcode);
2381 return INITFILTER_NO_ERROR;
2385 /* set up to write to the already-opened capture output file/files */
2387 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2391 pcap_options *pcap_opts;
2392 interface_options interface_opts;
2393 gboolean successful;
2395 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2397 if ((capture_opts->use_pcapng == FALSE) &&
2398 (capture_opts->ifaces->len > 1)) {
2399 g_snprintf(errmsg, errmsg_len,
2400 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
2404 /* Set up to write to the capture file. */
2405 if (capture_opts->multi_files_on) {
2406 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2408 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2409 if (ld->pdh == NULL) {
2414 if (capture_opts->use_pcapng) {
2416 GString *cpu_info_str;
2417 GString *os_info_str;
2419 cpu_info_str = g_string_new("");
2420 os_info_str = g_string_new("");
2421 get_cpu_info(cpu_info_str);
2422 get_os_version_info(os_info_str);
2424 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2425 successful = pcapng_write_session_header_block(ld->pdh,
2426 (const char *)capture_opts->capture_comment, /* Comment */
2427 cpu_info_str->str, /* HW */
2428 os_info_str->str, /* OS */
2430 -1, /* section_length */
2435 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2436 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2437 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2438 if (pcap_opts->from_cap_pipe) {
2439 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2441 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2443 successful = pcapng_write_interface_description_block(global_ld.pdh,
2444 NULL, /* OPT_COMMENT 1 */
2445 interface_opts.name, /* IDB_NAME 2 */
2446 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2447 interface_opts.cfilter, /* IDB_FILTER 11 */
2448 os_info_str->str, /* IDB_OS 12 */
2449 pcap_opts->linktype,
2451 &(global_ld.bytes_written),
2452 0, /* IDB_IF_SPEED 8 */
2453 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2457 g_string_free(os_info_str, TRUE);
2460 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2461 if (pcap_opts->from_cap_pipe) {
2462 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2464 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2466 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2467 pcap_opts->ts_nsec, &ld->bytes_written, &err);
2475 if (ld->pdh == NULL) {
2476 /* We couldn't set up to write to the capture file. */
2477 /* XXX - use cf_open_error_message from tshark instead? */
2482 g_snprintf(errmsg, errmsg_len,
2483 "The file to which the capture would be"
2484 " saved (\"%s\") could not be opened: Error %d.",
2485 capture_opts->save_file, err);
2487 g_snprintf(errmsg, errmsg_len,
2488 "The file to which the capture would be"
2489 " saved (\"%s\") could not be opened: %s.",
2490 capture_opts->save_file, g_strerror(err));
2502 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2506 pcap_options *pcap_opts;
2507 guint64 end_time = create_timestamp();
2509 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2511 if (capture_opts->multi_files_on) {
2512 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2514 if (capture_opts->use_pcapng) {
2515 for (i = 0; i < global_ld.pcaps->len; i++) {
2516 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2517 if (!pcap_opts->from_cap_pipe) {
2518 guint64 isb_ifrecv, isb_ifdrop;
2519 struct pcap_stat stats;
2521 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
2522 isb_ifrecv = pcap_opts->received;
2523 isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
2525 isb_ifrecv = G_MAXUINT64;
2526 isb_ifdrop = G_MAXUINT64;
2528 pcapng_write_interface_statistics_block(ld->pdh,
2531 "Counters provided by dumpcap",
2540 if (fclose(ld->pdh) == EOF) {
2541 if (err_close != NULL) {
2551 /* dispatch incoming packets (pcap or capture pipe)
2553 * Waits for incoming packets to be available, and calls pcap_dispatch()
2554 * to cause them to be processed.
2556 * Returns the number of packets which were processed.
2558 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2559 * packet-batching behaviour does not cause packets to get held back
2563 capture_loop_dispatch(loop_data *ld,
2564 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
2567 gint packet_count_before;
2568 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2573 packet_count_before = ld->packet_count;
2574 if (pcap_opts->from_cap_pipe) {
2575 /* dispatch from capture pipe */
2576 #ifdef LOG_CAPTURE_VERBOSE
2577 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2580 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
2582 if (sel_ret < 0 && errno != EINTR) {
2583 g_snprintf(errmsg, errmsg_len,
2584 "Unexpected error from select: %s", g_strerror(errno));
2585 report_capture_error(errmsg, please_report);
2590 * "select()" says we can read from the pipe without blocking
2593 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
2603 /* dispatch from pcap */
2604 #ifdef MUST_DO_SELECT
2606 * If we have "pcap_get_selectable_fd()", we use it to get the
2607 * descriptor on which to select; if that's -1, it means there
2608 * is no descriptor on which you can do a "select()" (perhaps
2609 * because you're capturing on a special device, and that device's
2610 * driver unfortunately doesn't support "select()", in which case
2611 * we don't do the select - which means it might not be possible
2612 * to stop a capture until a packet arrives. If that's unacceptable,
2613 * plead with whoever supplies the software for that device to add
2614 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2615 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2616 * later, so it can use pcap_breakloop().
2618 #ifdef LOG_CAPTURE_VERBOSE
2619 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2621 if (pcap_opts->pcap_fd != -1) {
2622 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
2625 * "select()" says we can read from it without blocking; go for
2628 * We don't have pcap_breakloop(), so we only process one packet
2629 * per pcap_dispatch() call, to allow a signal to stop the
2630 * processing immediately, rather than processing all packets
2631 * in a batch before quitting.
2634 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2636 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2640 /* Error, rather than pcap_breakloop(). */
2641 pcap_opts->pcap_err = TRUE;
2643 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2646 if (sel_ret < 0 && errno != EINTR) {
2647 g_snprintf(errmsg, errmsg_len,
2648 "Unexpected error from select: %s", g_strerror(errno));
2649 report_capture_error(errmsg, please_report);
2655 #endif /* MUST_DO_SELECT */
2657 /* dispatch from pcap without select */
2659 #ifdef LOG_CAPTURE_VERBOSE
2660 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2664 * On Windows, we don't support asynchronously telling a process to
2665 * stop capturing; instead, we check for an indication on a pipe
2666 * after processing packets. We therefore process only one packet
2667 * at a time, so that we can check the pipe after every packet.
2670 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2672 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2676 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2678 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2683 /* Error, rather than pcap_breakloop(). */
2684 pcap_opts->pcap_err = TRUE;
2686 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2688 #else /* pcap_next_ex */
2689 #ifdef LOG_CAPTURE_VERBOSE
2690 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2692 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2695 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2696 * see https://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
2697 * This should be fixed in the WinPcap 4.0 alpha release.
2699 * For reference, an example remote interface:
2700 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2703 /* emulate dispatch from pcap */
2706 struct pcap_pkthdr *pkt_header;
2711 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
2713 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2715 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2720 pcap_opts->pcap_err = TRUE;
2724 #endif /* pcap_next_ex */
2728 #ifdef LOG_CAPTURE_VERBOSE
2729 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2732 return ld->packet_count - packet_count_before;
2736 /* Isolate the Universally Unique Identifier from the interface. Basically, we
2737 * want to grab only the characters between the '{' and '}' delimiters.
2739 * Returns a GString that must be freed with g_string_free(). */
2741 isolate_uuid(const char *iface)
2746 ptr = strchr(iface, '{');
2748 return g_string_new(iface);
2749 gstr = g_string_new(ptr + 1);
2751 ptr = strchr(gstr->str, '}');
2755 gstr = g_string_truncate(gstr, ptr - gstr->str);
2760 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2761 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2763 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2764 char *errmsg, int errmsg_len)
2767 gchar *capfile_name;
2768 gchar *prefix, *suffix;
2769 gboolean is_tempfile;
2771 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2772 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
2774 if (capture_opts->save_file != NULL) {
2775 /* We return to the caller while the capture is in progress.
2776 * Therefore we need to take a copy of save_file in
2777 * case the caller destroys it after we return.
2779 capfile_name = g_strdup(capture_opts->save_file);
2781 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2782 if (capture_opts->multi_files_on) {
2783 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2784 g_snprintf(errmsg, errmsg_len,
2785 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2786 g_free(capfile_name);
2789 if (strcmp(capfile_name, "-") == 0) {
2790 /* write to stdout */
2793 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2794 _setmode(1, O_BINARY);
2797 } /* if (...output_to_pipe ... */
2800 if (capture_opts->multi_files_on) {
2801 /* ringbuffer is enabled */
2802 *save_file_fd = ringbuf_init(capfile_name,
2803 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
2804 capture_opts->group_read_access);
2806 /* we need the ringbuf name */
2807 if (*save_file_fd != -1) {
2808 g_free(capfile_name);
2809 capfile_name = g_strdup(ringbuf_current_filename());
2812 /* Try to open/create the specified file for use as a capture buffer. */
2813 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2814 (capture_opts->group_read_access) ? 0640 : 0600);
2817 is_tempfile = FALSE;
2819 /* Choose a random name for the temporary capture buffer */
2820 if (global_capture_opts.ifaces->len > 1) {
2821 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
2822 if (capture_opts->use_pcapng) {
2829 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
2831 /* use the generic portion of the interface guid to form the basis of the filename */
2832 if (strncmp("NPF_{", basename, 5)==0)
2834 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
2836 iface = isolate_uuid(basename);
2838 basename = g_strdup(iface->str);
2839 g_string_free(iface, TRUE);
2842 /* generate the temp file name prefix and suffix */
2843 if (capture_opts->use_pcapng) {
2844 prefix = g_strconcat("wireshark_", basename, NULL);
2847 prefix = g_strconcat("wireshark_", basename, NULL);
2852 *save_file_fd = create_tempfile(&tmpname, prefix, suffix);
2854 capfile_name = g_strdup(tmpname);
2858 /* did we fail to open the output file? */
2859 if (*save_file_fd == -1) {
2861 g_snprintf(errmsg, errmsg_len,
2862 "The temporary file to which the capture would be saved (\"%s\") "
2863 "could not be opened: %s.", capfile_name, g_strerror(errno));
2865 if (capture_opts->multi_files_on) {
2866 ringbuf_error_cleanup();
2869 g_snprintf(errmsg, errmsg_len,
2870 "The file to which the capture would be saved (\"%s\") "
2871 "could not be opened: %s.", capfile_name,
2874 g_free(capfile_name);
2878 if (capture_opts->save_file != NULL) {
2879 g_free(capture_opts->save_file);
2881 capture_opts->save_file = capfile_name;
2882 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2883 "g_free(capfile_name)". */
2889 /* Do the work of handling either the file size or file duration capture
2890 conditions being reached, and switching files or stopping. */
2892 do_file_switch_or_stop(capture_options *capture_opts,
2893 condition *cnd_autostop_files,
2894 condition *cnd_autostop_size,
2895 condition *cnd_file_duration)
2898 pcap_options *pcap_opts;
2899 interface_options interface_opts;
2900 gboolean successful;
2902 if (capture_opts->multi_files_on) {
2903 if (cnd_autostop_files != NULL &&
2904 cnd_eval(cnd_autostop_files, (guint64)++global_ld.autostop_files)) {
2905 /* no files left: stop here */
2906 global_ld.go = FALSE;
2910 /* Switch to the next ringbuffer file */
2911 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2912 &global_ld.save_file_fd, &global_ld.err)) {
2914 /* File switch succeeded: reset the conditions */
2915 global_ld.bytes_written = 0;
2916 if (capture_opts->use_pcapng) {
2918 GString *cpu_info_str;
2919 GString *os_info_str;
2921 cpu_info_str = g_string_new("");
2922 os_info_str = g_string_new("");
2923 get_cpu_info(cpu_info_str);
2924 get_os_version_info(os_info_str);
2926 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2927 successful = pcapng_write_session_header_block(global_ld.pdh,
2928 (const char *)capture_opts->capture_comment, /* Comment */
2929 cpu_info_str->str, /* HW */
2930 os_info_str->str, /* OS */
2932 -1, /* section_length */
2933 &(global_ld.bytes_written),
2937 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2938 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2939 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2940 successful = pcapng_write_interface_description_block(global_ld.pdh,
2941 NULL, /* OPT_COMMENT 1 */
2942 interface_opts.name, /* IDB_NAME 2 */
2943 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2944 interface_opts.cfilter, /* IDB_FILTER 11 */
2945 os_info_str->str, /* IDB_OS 12 */
2946 pcap_opts->linktype,
2948 &(global_ld.bytes_written),
2949 0, /* IDB_IF_SPEED 8 */
2950 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2954 g_string_free(os_info_str, TRUE);
2957 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
2958 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
2959 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
2962 fclose(global_ld.pdh);
2963 global_ld.pdh = NULL;
2964 global_ld.go = FALSE;
2967 if (cnd_autostop_size)
2968 cnd_reset(cnd_autostop_size);
2969 if (cnd_file_duration)
2970 cnd_reset(cnd_file_duration);
2971 fflush(global_ld.pdh);
2973 report_packet_count(global_ld.inpkts_to_sync_pipe);
2974 global_ld.inpkts_to_sync_pipe = 0;
2975 report_new_capture_file(capture_opts->save_file);
2977 /* File switch failed: stop here */
2978 global_ld.go = FALSE;
2982 /* single file, stop now */
2983 global_ld.go = FALSE;
2990 pcap_read_handler(void* arg)
2992 pcap_options *pcap_opts;
2993 char errmsg[MSG_MAX_LENGTH+1];
2995 pcap_opts = (pcap_options *)arg;
2997 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
2998 pcap_opts->interface_id);
3000 while (global_ld.go) {
3001 /* dispatch incoming packets */
3002 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3004 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3005 pcap_opts->interface_id);
3006 g_thread_exit(NULL);
3010 /* Do the low-level work of a capture.
3011 Returns TRUE if it succeeds, FALSE otherwise. */
3013 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3016 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3018 struct timeval upd_time, cur_time;
3022 condition *cnd_file_duration = NULL;
3023 condition *cnd_autostop_files = NULL;
3024 condition *cnd_autostop_size = NULL;
3025 condition *cnd_autostop_duration = NULL;
3028 gboolean cfilter_error = FALSE;
3029 char errmsg[MSG_MAX_LENGTH+1];
3030 char secondary_errmsg[MSG_MAX_LENGTH+1];
3031 pcap_options *pcap_opts;
3032 interface_options interface_opts;
3033 guint i, error_index = 0;
3036 *secondary_errmsg = '\0';
3038 /* init the loop data */
3039 global_ld.go = TRUE;
3040 global_ld.packet_count = 0;
3042 global_ld.report_packet_count = FALSE;
3044 if (capture_opts->has_autostop_packets)
3045 global_ld.packet_max = capture_opts->autostop_packets;
3047 global_ld.packet_max = 0; /* no limit */
3048 global_ld.inpkts_to_sync_pipe = 0;
3049 global_ld.err = 0; /* no error seen yet */
3050 global_ld.pdh = NULL;
3051 global_ld.autostop_files = 0;
3052 global_ld.save_file_fd = -1;
3054 /* We haven't yet gotten the capture statistics. */
3055 *stats_known = FALSE;
3057 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3058 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3060 /* open the "input file" from network interface or capture pipe */
3061 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3062 secondary_errmsg, sizeof(secondary_errmsg))) {
3065 for (i = 0; i < capture_opts->ifaces->len; i++) {
3066 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3067 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3068 /* init the input filter from the network interface (capture pipe will do nothing) */
3070 * When remote capturing WinPCap crashes when the capture filter
3071 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3074 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3075 interface_opts.name,
3076 interface_opts.cfilter?interface_opts.cfilter:"")) {
3078 case INITFILTER_NO_ERROR:
3081 case INITFILTER_BAD_FILTER:
3082 cfilter_error = TRUE;
3084 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3087 case INITFILTER_OTHER_ERROR:
3088 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3089 pcap_geterr(pcap_opts->pcap_h));
3090 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3095 /* If we're supposed to write to a capture file, open it for output
3096 (temporary/specified name/ringbuffer) */
3097 if (capture_opts->saving_to_file) {
3098 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3099 errmsg, sizeof(errmsg))) {
3103 /* set up to write to the already-opened capture output file/files */
3104 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3109 /* XXX - capture SIGTERM and close the capture, in case we're on a
3110 Linux 2.0[.x] system and you have to explicitly close the capture
3111 stream in order to turn promiscuous mode off? We need to do that
3112 in other places as well - and I don't think that works all the
3113 time in any case, due to libpcap bugs. */
3115 /* Well, we should be able to start capturing.
3117 Sync out the capture file, so the header makes it to the file system,
3118 and send a "capture started successfully and capture file created"
3119 message to our parent so that they'll open the capture file and
3120 update its windows to indicate that we have a live capture in
3122 fflush(global_ld.pdh);
3123 report_new_capture_file(capture_opts->save_file);
3126 /* initialize capture stop (and alike) conditions */
3127 init_capture_stop_conditions();
3128 /* create stop conditions */
3129 if (capture_opts->has_autostop_filesize) {
3130 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3131 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3134 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3136 if (capture_opts->has_autostop_duration)
3137 cnd_autostop_duration =
3138 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3140 if (capture_opts->multi_files_on) {
3141 if (capture_opts->has_file_duration)
3143 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3145 if (capture_opts->has_autostop_files)
3146 cnd_autostop_files =
3147 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_files);
3150 /* init the time values */
3152 upd_time = GetTickCount();
3154 gettimeofday(&upd_time, NULL);
3156 start_time = create_timestamp();
3157 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3159 /* WOW, everything is prepared! */
3160 /* please fasten your seat belts, we will enter now the actual capture loop */
3162 pcap_queue = g_async_queue_new();
3163 pcap_queue_bytes = 0;
3164 pcap_queue_packets = 0;
3165 for (i = 0; i < global_ld.pcaps->len; i++) {
3166 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3167 #if GLIB_CHECK_VERSION(2,31,0)
3168 /* XXX - Add an interface name here? */
3169 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3171 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3175 while (global_ld.go) {
3176 /* dispatch incoming packets */
3178 pcap_queue_element *queue_element;
3179 #if GLIB_CHECK_VERSION(2,31,18)
3181 g_async_queue_lock(pcap_queue);
3182 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3184 GTimeVal write_thread_time;
3186 g_get_current_time(&write_thread_time);
3187 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3188 g_async_queue_lock(pcap_queue);
3189 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3191 if (queue_element) {
3192 pcap_queue_bytes -= queue_element->phdr.caplen;
3193 pcap_queue_packets -= 1;
3195 g_async_queue_unlock(pcap_queue);
3196 if (queue_element) {
3197 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3198 "Dequeued a packet of length %d captured on interface %d.",
3199 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3201 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3202 &queue_element->phdr,
3204 g_free(queue_element->pd);
3205 g_free(queue_element);
3211 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3212 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3213 sizeof(errmsg), pcap_opts);
3216 /* Were we asked to print packet counts by the SIGINFO handler? */
3217 if (global_ld.report_packet_count) {
3218 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3219 plurality(global_ld.packet_count, "", "s"));
3220 global_ld.report_packet_count = FALSE;
3225 /* any news from our parent (signal pipe)? -> just stop the capture */
3226 if (!signal_pipe_check_running()) {
3227 global_ld.go = FALSE;
3232 global_ld.inpkts_to_sync_pipe += inpkts;
3234 /* check capture size condition */
3235 if (cnd_autostop_size != NULL &&
3236 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3237 /* Capture size limit reached, do we have another file? */
3238 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3239 cnd_autostop_size, cnd_file_duration))
3241 } /* cnd_autostop_size */
3242 if (capture_opts->output_to_pipe) {
3243 fflush(global_ld.pdh);
3247 /* Only update once every 500ms so as not to overload slow displays.
3248 * This also prevents too much context-switching between the dumpcap
3249 * and wireshark processes.
3251 #define DUMPCAP_UPD_TIME 500
3254 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3255 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3257 gettimeofday(&cur_time, NULL);
3258 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3259 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3262 upd_time = cur_time;
3265 if (pcap_stats(pch, stats) >= 0) {
3266 *stats_known = TRUE;
3269 /* Let the parent process know. */
3270 if (global_ld.inpkts_to_sync_pipe) {
3272 fflush(global_ld.pdh);
3274 /* Send our parent a message saying we've written out
3275 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3277 report_packet_count(global_ld.inpkts_to_sync_pipe);
3279 global_ld.inpkts_to_sync_pipe = 0;
3282 /* check capture duration condition */
3283 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3284 /* The maximum capture time has elapsed; stop the capture. */
3285 global_ld.go = FALSE;
3289 /* check capture file duration condition */
3290 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3291 /* duration limit reached, do we have another file? */
3292 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3293 cnd_autostop_size, cnd_file_duration))
3295 } /* cnd_file_duration */
3299 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3301 pcap_queue_element *queue_element;
3303 for (i = 0; i < global_ld.pcaps->len; i++) {
3304 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3305 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3306 pcap_opts->interface_id);
3307 g_thread_join(pcap_opts->tid);
3308 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3309 pcap_opts->interface_id);
3312 g_async_queue_lock(pcap_queue);
3313 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3314 if (queue_element) {
3315 pcap_queue_bytes -= queue_element->phdr.caplen;
3316 pcap_queue_packets -= 1;
3318 g_async_queue_unlock(pcap_queue);
3319 if (queue_element == NULL) {
3322 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3323 "Dequeued a packet of length %d captured on interface %d.",
3324 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3325 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3326 &queue_element->phdr,
3328 g_free(queue_element->pd);
3329 g_free(queue_element);
3330 global_ld.inpkts_to_sync_pipe += 1;
3331 if (capture_opts->output_to_pipe) {
3332 fflush(global_ld.pdh);
3338 /* delete stop conditions */
3339 if (cnd_file_duration != NULL)
3340 cnd_delete(cnd_file_duration);
3341 if (cnd_autostop_files != NULL)
3342 cnd_delete(cnd_autostop_files);
3343 if (cnd_autostop_size != NULL)
3344 cnd_delete(cnd_autostop_size);
3345 if (cnd_autostop_duration != NULL)
3346 cnd_delete(cnd_autostop_duration);
3348 /* did we have a pcap (input) error? */
3349 for (i = 0; i < capture_opts->ifaces->len; i++) {
3350 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3351 if (pcap_opts->pcap_err) {
3352 /* On Linux, if an interface goes down while you're capturing on it,
3353 you'll get a "recvfrom: Network is down" or
3354 "The interface went down" error (ENETDOWN).
3355 (At least you will if g_strerror() doesn't show a local translation
3358 On FreeBSD and OS X, if a network adapter disappears while
3359 you're capturing on it, you'll get a "read: Device not configured"
3360 error (ENXIO). (See previous parenthetical note.)
3362 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3364 These should *not* be reported to the Wireshark developers. */
3367 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3368 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3369 strcmp(cap_err_str, "The interface went down") == 0 ||
3370 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3371 strcmp(cap_err_str, "read: I/O error") == 0 ||
3372 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3373 report_capture_error("The network adapter on which the capture was being done "
3374 "is no longer running; the capture has stopped.",
3377 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3379 report_capture_error(errmsg, please_report);
3382 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3383 report_capture_error(errmsg, "");
3387 /* did we have an output error while capturing? */
3388 if (global_ld.err == 0) {
3391 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3392 global_ld.err, FALSE);
3393 report_capture_error(errmsg, please_report);
3397 if (capture_opts->saving_to_file) {
3398 /* close the output file */
3399 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3403 /* there might be packets not yet notified to the parent */
3404 /* (do this after closing the file, so all packets are already flushed) */
3405 if (global_ld.inpkts_to_sync_pipe) {
3407 report_packet_count(global_ld.inpkts_to_sync_pipe);
3408 global_ld.inpkts_to_sync_pipe = 0;
3411 /* If we've displayed a message about a write error, there's no point
3412 in displaying another message about an error on close. */
3413 if (!close_ok && write_ok) {
3414 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3416 report_capture_error(errmsg, "");
3420 * XXX We exhibit different behaviour between normal mode and sync mode
3421 * when the pipe is stdin and not already at EOF. If we're a child, the
3422 * parent's stdin isn't closed, so if the user starts another capture,
3423 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3424 * will say "Unrecognized libpcap format". On the other hand, in normal
3425 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3428 report_capture_count(TRUE);
3430 /* get packet drop statistics from pcap */
3431 for (i = 0; i < capture_opts->ifaces->len; i++) {
3433 guint32 pcap_dropped = 0;
3435 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3436 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3437 received = pcap_opts->received;
3438 if (pcap_opts->pcap_h != NULL) {
3439 g_assert(!pcap_opts->from_cap_pipe);
3440 /* Get the capture statistics, so we know how many packets were dropped. */
3442 * Older versions of libpcap didn't set ps_ifdrop on some
3443 * platforms; initialize it to 0 to handle that.
3445 stats->ps_ifdrop = 0;
3446 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3447 *stats_known = TRUE;
3448 /* Let the parent process know. */
3449 pcap_dropped += stats->ps_drop;
3451 g_snprintf(errmsg, sizeof(errmsg),
3452 "Can't get packet-drop statistics: %s",
3453 pcap_geterr(pcap_opts->pcap_h));
3454 report_capture_error(errmsg, please_report);
3457 report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
3460 /* close the input file (pcap or capture pipe) */
3461 capture_loop_close_input(&global_ld);
3463 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
3465 /* ok, if the write and the close were successful. */
3466 return write_ok && close_ok;
3469 if (capture_opts->multi_files_on) {
3470 /* cleanup ringbuffer */
3471 ringbuf_error_cleanup();
3473 /* We can't use the save file, and we have no FILE * for the stream
3474 to close in order to close it, so close the FD directly. */
3475 if (global_ld.save_file_fd != -1) {
3476 ws_close(global_ld.save_file_fd);
3479 /* We couldn't even start the capture, so get rid of the capture
3481 if (capture_opts->save_file != NULL) {
3482 ws_unlink(capture_opts->save_file);
3483 g_free(capture_opts->save_file);
3486 capture_opts->save_file = NULL;
3488 report_cfilter_error(capture_opts, error_index, errmsg);
3490 report_capture_error(errmsg, secondary_errmsg);
3492 /* close the input file (pcap or cap_pipe) */
3493 capture_loop_close_input(&global_ld);
3495 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3502 capture_loop_stop(void)
3504 #ifdef HAVE_PCAP_BREAKLOOP
3506 pcap_options *pcap_opts;
3508 for (i = 0; i < global_ld.pcaps->len; i++) {
3509 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3510 if (pcap_opts->pcap_h != NULL)
3511 pcap_breakloop(pcap_opts->pcap_h);
3514 global_ld.go = FALSE;
3519 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3520 int err, gboolean is_close)
3525 g_snprintf(errmsg, errmsglen,
3526 "Not all the packets could be written to the file"
3527 " to which the capture was being saved\n"
3528 "(\"%s\") because there is no space left on the file system\n"
3529 "on which that file resides.",
3535 g_snprintf(errmsg, errmsglen,
3536 "Not all the packets could be written to the file"
3537 " to which the capture was being saved\n"
3538 "(\"%s\") because you are too close to, or over,"
3539 " your disk quota\n"
3540 "on the file system on which that file resides.",
3547 g_snprintf(errmsg, errmsglen,
3548 "The file to which the capture was being saved\n"
3549 "(\"%s\") could not be closed: %s.",
3550 fname, g_strerror(err));
3552 g_snprintf(errmsg, errmsglen,
3553 "An error occurred while writing to the file"
3554 " to which the capture was being saved\n"
3556 fname, g_strerror(err));
3563 /* one packet was captured, process it */
3565 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3568 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3570 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
3572 /* We may be called multiple times from pcap_dispatch(); if we've set
3573 the "stop capturing" flag, ignore this packet, as we're not
3574 supposed to be saving any more packets. */
3575 if (!global_ld.go) {
3576 pcap_opts->flushed++;
3580 if (global_ld.pdh) {
3581 gboolean successful;
3583 /* We're supposed to write the packet to a file; do so.
3584 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3585 "ld->err" to the error. */
3586 if (global_capture_opts.use_pcapng) {
3587 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
3589 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3590 phdr->caplen, phdr->len,
3591 pcap_opts->interface_id,
3594 &global_ld.bytes_written, &err);
3596 successful = libpcap_write_packet(global_ld.pdh,
3597 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3598 phdr->caplen, phdr->len,
3600 &global_ld.bytes_written, &err);
3603 global_ld.go = FALSE;
3604 global_ld.err = err;
3605 pcap_opts->dropped++;
3607 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3608 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3609 "Wrote a packet of length %d captured on interface %u.",
3610 phdr->caplen, pcap_opts->interface_id);
3612 global_ld.packet_count++;
3613 pcap_opts->received++;
3614 /* if the user told us to stop after x packets, do we already have enough? */
3615 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
3616 global_ld.go = FALSE;
3622 /* one packet was captured, queue it */
3624 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3627 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3628 pcap_queue_element *queue_element;
3629 gboolean limit_reached;
3631 /* We may be called multiple times from pcap_dispatch(); if we've set
3632 the "stop capturing" flag, ignore this packet, as we're not
3633 supposed to be saving any more packets. */
3634 if (!global_ld.go) {
3635 pcap_opts->flushed++;
3639 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
3640 if (queue_element == NULL) {
3641 pcap_opts->dropped++;
3644 queue_element->pcap_opts = pcap_opts;
3645 queue_element->phdr = *phdr;
3646 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
3647 if (queue_element->pd == NULL) {
3648 pcap_opts->dropped++;
3649 g_free(queue_element);
3652 memcpy(queue_element->pd, pd, phdr->caplen);
3653 g_async_queue_lock(pcap_queue);
3654 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
3655 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
3656 limit_reached = FALSE;
3657 g_async_queue_push_unlocked(pcap_queue, queue_element);
3658 pcap_queue_bytes += phdr->caplen;
3659 pcap_queue_packets += 1;
3661 limit_reached = TRUE;
3663 g_async_queue_unlock(pcap_queue);
3664 if (limit_reached) {
3665 pcap_opts->dropped++;
3666 g_free(queue_element->pd);
3667 g_free(queue_element);
3668 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3669 "Dropped a packet of length %d captured on interface %u.",
3670 phdr->caplen, pcap_opts->interface_id);
3672 pcap_opts->received++;
3673 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3674 "Queued a packet of length %d captured on interface %u.",
3675 phdr->caplen, pcap_opts->interface_id);
3677 /* I don't want to hold the mutex over the debug output. So the
3678 output may be wrong */
3679 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3680 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
3681 pcap_queue_bytes, pcap_queue_packets);
3685 set_80211_channel(const char *iface, const char *opt)
3689 guint32 center_freq1 = 0;
3690 guint32 center_freq2 = 0;
3693 gchar **options = NULL;
3695 options = g_strsplit_set(opt, ",", 4);
3696 for (args = 0; options[args]; args++);
3699 freq = get_nonzero_guint32(options[0], "802.11 channel frequency");
3701 if (args >= 1 && options[1]) {
3702 type = ws80211_str_to_chan_type(options[1]);
3704 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
3710 if (args >= 2 && options[2])
3711 center_freq1 = get_nonzero_guint32(options[2], "VHT center frequency");
3713 if (args >= 3 && options[3])
3714 center_freq2 = get_nonzero_guint32(options[3], "VHT center frequency 2");
3716 ret = ws80211_init();
3718 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
3722 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
3725 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
3731 pipe_write_block(2, SP_SUCCESS, NULL);
3734 g_strfreev(options);
3739 get_dumpcap_compiled_info(GString *str)
3741 /* Capture libraries */
3742 g_string_append(str, ", ");
3743 get_compiled_caplibs_version(str);
3747 get_dumpcap_runtime_info(GString *str)
3749 /* Capture libraries */
3750 g_string_append(str, ", ");
3751 get_runtime_caplibs_version(str);
3754 /* And now our feature presentation... [ fade to music ] */
3756 main(int argc, char *argv[])
3758 GString *comp_info_str;
3759 GString *runtime_info_str;
3761 static const struct option long_options[] = {
3762 {"help", no_argument, NULL, 'h'},
3763 {"version", no_argument, NULL, 'v'},
3764 LONGOPT_CAPTURE_COMMON
3768 gboolean arg_error = FALSE;
3773 struct sigaction action, oldaction;
3776 gboolean start_capture = TRUE;
3777 gboolean stats_known;
3778 struct pcap_stat stats;
3779 GLogLevelFlags log_flags;
3780 gboolean list_interfaces = FALSE;
3781 gboolean list_link_layer_types = FALSE;
3782 #ifdef HAVE_BPF_IMAGE
3783 gboolean print_bpf_code = FALSE;
3785 gboolean set_chan = FALSE;
3786 gchar *set_chan_arg = NULL;
3787 gboolean machine_readable = FALSE;
3788 gboolean print_statistics = FALSE;
3789 int status, run_once_args = 0;
3792 #if defined(__APPLE__) && defined(__LP64__)
3793 struct utsname osinfo;
3797 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
3799 /* Get the compile-time version information string */
3800 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
3802 /* Get the run-time version information string */
3803 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
3805 /* Add it to the information to be reported on a crash. */
3806 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
3811 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
3812 g_string_free(comp_info_str, TRUE);
3813 g_string_free(runtime_info_str, TRUE);
3816 arg_list_utf_16to8(argc, argv);
3817 create_app_running_mutex();
3820 * Initialize our DLL search path. MUST be called before LoadLibrary
3823 ws_init_dll_search_path();
3826 #ifdef HAVE_BPF_IMAGE
3827 #define OPTSTRING_d "d"
3829 #define OPTSTRING_d ""
3832 #ifdef HAVE_PCAP_REMOTE
3833 #define OPTSTRING_r "r"
3834 #define OPTSTRING_u "u"
3836 #define OPTSTRING_r ""
3837 #define OPTSTRING_u ""
3840 #ifdef HAVE_PCAP_SETSAMPLING
3841 #define OPTSTRING_m "m:"
3843 #define OPTSTRING_m ""
3846 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
3848 #ifdef DEBUG_CHILD_DUMPCAP
3849 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3850 fprintf (stderr, "Unable to open debug log file .\n");
3855 #if defined(__APPLE__) && defined(__LP64__)
3857 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
3858 * a bug workaround - timeouts less than 1 second don't work with libpcap
3859 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3860 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
3861 * The problem is extremely unlikely to be reintroduced in a future
3864 if (uname(&osinfo) == 0) {
3866 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
3867 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3868 * number of 10.0.0, not 10.1.0 - go figure).
3870 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
3871 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
3872 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
3873 need_timeout_workaround = TRUE;
3878 * Determine if dumpcap is being requested to run in a special
3879 * capture_child mode by going thru the command line args to see if
3880 * a -Z is present. (-Z is a hidden option).
3882 * The primary result of running in capture_child mode is that
3883 * all messages sent out on stderr are in a special type/len/string
3884 * format to allow message processing by type. These messages include
3885 * error messages if dumpcap fails to start the operation it was
3886 * requested to do, as well as various "status" messages which are sent
3887 * when an actual capture is in progress, and a "success" message sent
3888 * if dumpcap was requested to perform an operation other than a
3891 * Capture_child mode would normally be requested by a parent process
3892 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3893 * to which dumpcap stderr has been redirected. It might also have
3894 * another pipe to obtain dumpcap stdout output; for operations other
3895 * than a capture, that information is formatted specially for easier
3896 * parsing by the parent process.
3898 * Capture_child mode needs to be determined immediately upon
3899 * startup so that any messages generated by dumpcap in this mode
3900 * (eg: during initialization) will be formatted properly.
3903 for (i=1; i<argc; i++) {
3904 if (strcmp("-Z", argv[i]) == 0) {
3905 capture_child = TRUE;
3906 machine_readable = TRUE; /* request machine-readable output */
3908 /* set output pipe to binary mode, to avoid ugly text conversions */
3909 _setmode(2, O_BINARY);
3914 /* The default_log_handler will use stdout, which makes trouble in */
3915 /* capture child mode, as it uses stdout for its sync_pipe. */
3916 /* So: the filtering is done in the console_log_handler and not here.*/
3917 /* We set the log handlers right up front to make sure that any log */
3918 /* messages when running as child will be sent back to the parent */
3919 /* with the correct format. */
3924 G_LOG_LEVEL_CRITICAL|
3925 G_LOG_LEVEL_WARNING|
3926 G_LOG_LEVEL_MESSAGE|
3930 G_LOG_FLAG_RECURSION);
3932 g_log_set_handler(NULL,
3934 console_log_handler, NULL /* user_data */);
3935 g_log_set_handler(LOG_DOMAIN_MAIN,
3937 console_log_handler, NULL /* user_data */);
3938 g_log_set_handler(LOG_DOMAIN_CAPTURE,
3940 console_log_handler, NULL /* user_data */);
3941 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3943 console_log_handler, NULL /* user_data */);
3945 /* Initialize the pcaps list */
3946 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
3948 #if !GLIB_CHECK_VERSION(2,31,0)
3949 /* Initialize the thread system */
3950 g_thread_init(NULL);
3954 /* Load wpcap if possible. Do this before collecting the run-time version information */
3957 /* ... and also load the packet.dll from wpcap */
3958 /* XXX - currently not required, may change later. */
3959 /*wpcap_packet_load();*/
3961 /* Start windows sockets */
3962 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3964 /* Set handler for Ctrl+C key */
3965 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3967 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3968 and exit. Do the same with SIGPIPE, in case, for example,
3969 we're writing to our standard output and it's a pipe.
3970 Do the same with SIGHUP if it's not being ignored (if we're
3971 being run under nohup, it might be ignored, in which case we
3972 should leave it ignored).
3974 XXX - apparently, Coverity complained that part of action
3975 wasn't initialized. Perhaps it's running on Linux, where
3976 struct sigaction has an ignored "sa_restorer" element and
3977 where "sa_handler" and "sa_sigaction" might not be two
3978 members of a union. */
3979 memset(&action, 0, sizeof(action));
3980 action.sa_handler = capture_cleanup_handler;
3982 * Arrange that system calls not get restarted, because when
3983 * our signal handler returns we don't want to restart
3984 * a call that was waiting for packets to arrive.
3986 action.sa_flags = 0;
3987 sigemptyset(&action.sa_mask);
3988 sigaction(SIGTERM, &action, NULL);
3989 sigaction(SIGINT, &action, NULL);
3990 sigaction(SIGPIPE, &action, NULL);
3991 sigaction(SIGHUP, NULL, &oldaction);
3992 if (oldaction.sa_handler == SIG_DFL)
3993 sigaction(SIGHUP, &action, NULL);
3996 /* Catch SIGINFO and, if we get it and we're capturing in
3997 quiet mode, report the number of packets we've captured. */
3998 action.sa_handler = report_counts_siginfo;
3999 action.sa_flags = SA_RESTART;
4000 sigemptyset(&action.sa_mask);
4001 sigaction(SIGINFO, &action, NULL);
4002 #endif /* SIGINFO */
4006 enable_kernel_bpf_jit_compiler();
4009 /* ----------------------------------------------------------------- */
4010 /* Privilege and capability handling */
4012 /* 1. Running not as root or suid root; no special capabilities. */
4015 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4018 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4020 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4021 /* capabilities; Drop all other capabilities; */
4022 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4023 /* else: after pcap_open_live() in capture_loop_open_input() */
4024 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4025 /* (Note: this means that the process, although logged in */
4026 /* as root, does not have various permissions such as the */
4027 /* ability to bypass file access permissions). */
4028 /* XXX: Should we just leave capabilities alone in this case */
4029 /* so that user gets expected effect that root can do */
4032 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4034 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4035 /* else: after pcap_open_live() in capture_loop_open_input() */
4036 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4037 /* pcap_open_live). */
4039 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4041 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4042 /* capabilities; Drop all other capabilities; */
4043 /* Drop suid privileges (euid=ruid); */
4044 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4045 /* else: after pcap_open_live() in capture_loop_open_input() */
4046 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4048 /* XXX: For some Linux versions/distros with capabilities */
4049 /* a 'normal' process with any capabilities cannot be */
4050 /* 'killed' (signaled) from another (same uid) non-privileged */
4052 /* For example: If (non-suid) Wireshark forks a */
4053 /* child suid dumpcap which acts as described here (case 5), */
4054 /* Wireshark will be unable to kill (signal) the child */
4055 /* dumpcap process until the capabilities have been dropped */
4056 /* (after pcap_open_live()). */
4057 /* This behaviour will apparently be changed in the kernel */
4058 /* to allow the kill (signal) in this case. */
4059 /* See the following for details: */
4060 /* https://www.mail-archive.com/ [wrapped] */
4061 /* linux-security-module@vger.kernel.org/msg02913.html */
4063 /* It is therefore conceivable that if dumpcap somehow hangs */
4064 /* in pcap_open_live or before that wireshark will not */
4065 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4066 /* In this case, exiting wireshark will kill the child */
4067 /* dumpcap process. */
4069 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4070 /* capabilities; Using libcap. Note: capset cmd (which see) */
4071 /* used to assign capabilities to file. */
4073 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4074 /* else: after pcap_open_live() in capture_loop_open_input() */
4075 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4077 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4078 /* longer required (similar to capture). */
4080 /* ----------------------------------------------------------------- */
4082 init_process_policies();
4085 /* If 'started with special privileges' (and using libcap) */
4086 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4087 /* Set euid/egid = ruid/rgid to remove suid privileges */
4088 relinquish_privs_except_capture();
4091 /* Set the initial values in the capture options. This might be overwritten
4092 by the command line parameters. */
4093 capture_opts_init(&global_capture_opts);
4094 /* We always save to a file - if no file was specified, we save to a
4096 global_capture_opts.saving_to_file = TRUE;
4097 global_capture_opts.has_ring_num_files = TRUE;
4099 /* Pass on capture_child mode for capture_opts */
4100 global_capture_opts.capture_child = capture_child;
4102 /* Now get our args */
4103 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4105 case 'h': /* Print help and exit */
4106 printf("Dumpcap (Wireshark) %s\n"
4107 "Capture network packets and dump them into a pcapng or pcap file.\n"
4108 "See https://www.wireshark.org for more information.\n",
4109 get_ws_vcs_version_info());
4110 print_usage(stdout);
4113 case 'v': /* Show version and exit */
4114 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4115 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4116 show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4117 g_string_free(comp_info_str, TRUE);
4118 g_string_free(runtime_info_str, TRUE);
4121 /*** capture option specific ***/
4122 case 'a': /* autostop criteria */
4123 case 'b': /* Ringbuffer option */
4124 case 'c': /* Capture x packets */
4125 case 'f': /* capture filter */
4126 case 'g': /* enable group read access on file(s) */
4127 case 'i': /* Use interface x */
4128 case 'n': /* Use pcapng format */
4129 case 'p': /* Don't capture in promiscuous mode */
4130 case 'P': /* Use pcap format */
4131 case 's': /* Set the snapshot (capture) length */
4132 case 'w': /* Write to capture file x */
4133 case 'y': /* Set the pcap data link type */
4134 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4135 #ifdef HAVE_PCAP_REMOTE
4136 case 'u': /* Use UDP for data transfer */
4137 case 'r': /* Capture own RPCAP traffic too */
4138 case 'A': /* Authentication */
4140 #ifdef HAVE_PCAP_SETSAMPLING
4141 case 'm': /* Sampling */
4143 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4144 case 'B': /* Buffer size */
4146 #ifdef HAVE_PCAP_CREATE
4147 case 'I': /* Monitor mode */
4149 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4154 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4156 capture_child = TRUE;
4158 /* set output pipe to binary mode, to avoid ugly text conversions */
4159 _setmode(2, O_BINARY);
4161 * optarg = the control ID, aka the PPID, currently used for the
4164 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4165 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4166 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4167 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4169 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4170 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4171 "Signal pipe: Unable to open %s. Dead parent?",
4179 case 'q': /* Quiet */
4185 /*** all non capture option specific ***/
4186 case 'D': /* Print a list of capture devices and exit */
4187 if (!list_interfaces) {
4188 list_interfaces = TRUE;
4192 case 'L': /* Print list of link-layer types and exit */
4193 if (!list_link_layer_types) {
4194 list_link_layer_types = TRUE;
4198 #ifdef HAVE_BPF_IMAGE
4199 case 'd': /* Print BPF code for capture filter and exit */
4200 if (!print_bpf_code) {
4201 print_bpf_code = TRUE;
4206 case 'S': /* Print interface statistics once a second */
4207 if (!print_statistics) {
4208 print_statistics = TRUE;
4212 case 'k': /* Set wireless channel */
4215 set_chan_arg = optarg;
4218 cmdarg_err("Only one -k flag may be specified");
4222 case 'M': /* For -D, -L, and -S, print machine-readable output */
4223 machine_readable = TRUE;
4226 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4229 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4232 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4234 case '?': /* Bad flag - print usage message */
4243 /* user specified file name as regular command-line argument */
4244 /* XXX - use it as the capture file name (or something else)? */
4250 * Extra command line arguments were specified; complain.
4251 * XXX - interpret as capture filter, as tcpdump and tshark do?
4253 cmdarg_err("Invalid argument: %s", argv[0]);
4258 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4261 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4262 /* Use some default if the user hasn't specified some */
4263 /* XXX: Are these defaults good enough? */
4264 pcap_queue_byte_limit = 1000 * 1000;
4265 pcap_queue_packet_limit = 1000;
4268 print_usage(stderr);
4272 if (run_once_args > 1) {
4273 #ifdef HAVE_BPF_IMAGE
4274 cmdarg_err("Only one of -D, -L, -d, -k, or -S may be supplied.");
4276 cmdarg_err("Only one of -D, -L, -k, or -S may be supplied.");
4279 } else if (run_once_args == 1) {
4280 /* We're supposed to print some information, rather than
4281 to capture traffic; did they specify a ring buffer option? */
4282 if (global_capture_opts.multi_files_on) {
4283 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4287 /* We're supposed to capture traffic; */
4289 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4290 if (global_capture_opts.ifaces->len > 1) {
4292 global_capture_opts.use_pcapng = TRUE;
4295 if (global_capture_opts.capture_comment &&
4296 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4297 /* XXX - for ringbuffer, should we apply the comment to each file? */
4298 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4302 /* Was the ring buffer option specified and, if so, does it make sense? */
4303 if (global_capture_opts.multi_files_on) {
4304 /* Ring buffer works only under certain conditions:
4305 a) ring buffer does not work with temporary files;
4306 b) it makes no sense to enable the ring buffer if the maximum
4307 file size is set to "infinite". */
4308 if (global_capture_opts.save_file == NULL) {
4309 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4310 global_capture_opts.multi_files_on = FALSE;
4312 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4313 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4315 /* XXX - this must be redesigned as the conditions changed */
4316 global_capture_opts.multi_files_on = FALSE;
4323 * "-D" requires no interface to be selected; it's supposed to list
4326 if (list_interfaces) {
4327 /* Get the list of interfaces */
4332 if_list = capture_interface_list(&err, &err_str,NULL);
4333 if (if_list == NULL) {
4336 * If we're being run by another program, just give them
4337 * an empty list of interfaces, don't report this as
4338 * an error; that lets them decide whether to report
4339 * this as an error or not.
4341 if (!machine_readable) {
4342 cmdarg_err("There are no interfaces on which a capture can be done");
4346 cmdarg_err("%s", err_str);
4352 if (machine_readable) /* tab-separated values to stdout */
4353 print_machine_readable_interfaces(if_list);
4355 capture_opts_print_interfaces(if_list);
4356 free_interface_list(if_list);
4361 * "-S" requires no interface to be selected; it gives statistics
4362 * for all interfaces.
4364 if (print_statistics) {
4365 status = print_statistics_loop(machine_readable);
4370 interface_options interface_opts;
4372 if (global_capture_opts.ifaces->len != 1) {
4373 cmdarg_err("Need one interface");
4377 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4378 status = set_80211_channel(interface_opts.name, set_chan_arg);
4383 * "-L", "-d", and capturing act on a particular interface, so we have to
4384 * have an interface; if none was specified, pick a default.
4386 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4388 /* cmdarg_err() already called .... */
4392 if (list_link_layer_types) {
4393 /* Get the list of link-layer types for the capture device. */
4394 if_capabilities_t *caps;
4398 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4399 interface_options interface_opts;
4401 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4403 caps = get_if_capabilities(&interface_opts, &err_str);
4405 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4406 "Please check to make sure you have sufficient permissions, and that\n"
4407 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4411 if (caps->data_link_types == NULL) {
4412 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4415 if (machine_readable) /* tab-separated values to stdout */
4416 /* XXX: We need to change the format and adopt consumers */
4417 print_machine_readable_if_capabilities(caps);
4419 /* XXX: We might want to print also the interface name */
4420 capture_opts_print_if_capabilities(caps, interface_opts.name,
4421 interface_opts.monitor_mode);
4422 free_if_capabilities(caps);
4427 /* We're supposed to do a capture, or print the BPF code for a filter. */
4429 /* Let the user know what interfaces were chosen. */
4430 if (capture_child) {
4431 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4432 interface_options interface_opts;
4434 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4435 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4436 interface_opts.name);
4439 str = g_string_new("");
4441 if (global_capture_opts.ifaces->len < 2)
4443 if (global_capture_opts.ifaces->len < 4)
4446 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4447 interface_options interface_opts;
4449 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4451 if (global_capture_opts.ifaces->len > 2) {
4452 g_string_append_printf(str, ",");
4454 g_string_append_printf(str, " ");
4455 if (j == global_capture_opts.ifaces->len - 1) {
4456 g_string_append_printf(str, "and ");
4459 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4462 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4464 fprintf(stderr, "Capturing on %s\n", str->str);
4465 g_string_free(str, TRUE);
4468 /* Process the snapshot length, as that affects the generated BPF code. */
4469 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4471 #ifdef HAVE_BPF_IMAGE
4472 if (print_bpf_code) {
4473 show_filter_code(&global_capture_opts);
4478 /* We're supposed to do a capture. Process the ring buffer arguments. */
4479 capture_opts_trim_ring_num_files(&global_capture_opts);
4481 /* flush stderr prior to starting the main capture loop */
4484 /* Now start the capture. */
4485 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4489 /* capture failed */
4492 return 0; /* never here, make compiler happy */
4497 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4498 const char *message, gpointer user_data _U_)
4505 /* ignore log message, if log_level isn't interesting */
4506 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4507 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4512 switch(log_level & G_LOG_LEVEL_MASK) {
4513 case G_LOG_LEVEL_ERROR:
4516 case G_LOG_LEVEL_CRITICAL:
4519 case G_LOG_LEVEL_WARNING:
4522 case G_LOG_LEVEL_MESSAGE:
4525 case G_LOG_LEVEL_INFO:
4528 case G_LOG_LEVEL_DEBUG:
4532 fprintf(stderr, "unknown log_level %d\n", log_level);
4534 g_assert_not_reached();
4537 /* Generate the output message */
4538 if (log_level & G_LOG_LEVEL_MESSAGE) {
4539 /* normal user messages without additional infos */
4540 msg = g_strdup_printf("%s\n", message);
4542 /* create a "timestamp" */
4544 today = localtime(&curr);
4546 /* info/debug messages with additional infos */
4548 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4549 today->tm_hour, today->tm_min, today->tm_sec,
4550 log_domain != NULL ? log_domain : "",
4553 msg = g_strdup_printf("Time not representable %8s %s %s\n",
4554 log_domain != NULL ? log_domain : "",
4558 /* DEBUG & INFO msgs (if we're debugging today) */
4559 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4560 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4561 #ifdef DEBUG_DUMPCAP
4562 fprintf(stderr, "%s", msg);
4565 #ifdef DEBUG_CHILD_DUMPCAP
4566 fprintf(debug_log, "%s", msg);
4574 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4575 /* to parent especially formatted if dumpcap running as child. */
4576 if (capture_child) {
4577 sync_pipe_errmsg_to_parent(2, msg, "");
4579 fprintf(stderr, "%s", msg);
4586 /****************************************************************************************************************/
4587 /* indication report routines */
4591 report_packet_count(unsigned int packet_count)
4593 char tmp[SP_DECISIZE+1+1];
4594 static unsigned int count = 0;
4596 if (capture_child) {
4597 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
4598 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4599 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4601 count += packet_count;
4602 fprintf(stderr, "\rPackets: %u ", count);
4603 /* stderr could be line buffered */
4609 report_new_capture_file(const char *filename)
4611 if (capture_child) {
4612 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4613 pipe_write_block(2, SP_FILE, filename);
4617 * Prevent a SIGINFO handler from writing to the standard error
4618 * while we're doing so; instead, have it just set a flag telling
4619 * us to print that information when we're done.
4622 #endif /* SIGINFO */
4623 fprintf(stderr, "File: %s\n", filename);
4624 /* stderr could be line buffered */
4629 * Allow SIGINFO handlers to write.
4634 * If a SIGINFO handler asked us to write out capture counts, do so.
4637 report_counts_for_siginfo();
4638 #endif /* SIGINFO */
4643 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4645 interface_options interface_opts;
4646 char tmp[MSG_MAX_LENGTH+1+6];
4648 if (i < capture_opts->ifaces->len) {
4649 if (capture_child) {
4650 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4651 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4652 pipe_write_block(2, SP_BAD_FILTER, tmp);
4655 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
4656 * the error message below.
4658 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
4660 "Invalid capture filter \"%s\" for interface '%s'.\n"
4662 "That string isn't a valid capture filter (%s).\n"
4663 "See the User's Guide for a description of the capture filter syntax.",
4664 interface_opts.cfilter, interface_opts.name, errmsg);
4670 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4672 if (capture_child) {
4673 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4674 "Primary Error: %s", error_msg);
4675 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4676 "Secondary Error: %s", secondary_error_msg);
4677 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4679 cmdarg_err("%s", error_msg);
4680 if (secondary_error_msg[0] != '\0')
4681 cmdarg_err_cont("%s", secondary_error_msg);
4686 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
4688 char tmp[SP_DECISIZE+1+1];
4689 guint32 total_drops = pcap_drops + drops + flushed;
4691 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
4693 if (capture_child) {
4694 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4695 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
4696 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
4697 /* XXX: Need to provide interface id, changes to consumers required. */
4698 pipe_write_block(2, SP_DROPS, tmp);
4701 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
4702 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
4703 received ? 100.0 * received / (received + total_drops) : 0.0);
4704 /* stderr could be line buffered */
4710 /************************************************************************************************/
4711 /* signal_pipe handling */
4716 signal_pipe_check_running(void)
4718 /* any news from our parent? -> just stop the capture */
4722 /* if we are running standalone, no check required */
4723 if (!capture_child) {
4727 if (!sig_pipe_name || !sig_pipe_handle) {
4728 /* This shouldn't happen */
4729 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4730 "Signal pipe: No name or handle");
4735 * XXX - We should have the process ID of the parent (from the "-Z" flag)
4736 * at this point. Should we check to see if the parent is still alive,
4737 * e.g. by using OpenProcess?
4740 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
4742 if (!result || avail > 0) {
4743 /* peek failed or some bytes really available */
4744 /* (if not piping from stdin this would fail) */
4745 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4746 "Signal pipe: Stop capture: %s", sig_pipe_name);
4747 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4748 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
4749 sig_pipe_handle, result, avail);
4752 /* pipe ok and no bytes available */
4759 * Editor modelines - https://www.wireshark.org/tools/modelines.html
4764 * indent-tabs-mode: nil
4767 * vi: set shiftwidth=4 tabstop=8 expandtab:
4768 * :indentSize=4:tabSize=8:noTabs=true: