3 * Wireshark - Network traffic analyzer
4 * By Gerald Combs <gerald@wireshark.org>
5 * Copyright 1998 Gerald Combs
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include <stdlib.h> /* for exit() */
30 #ifdef HAVE_SYS_TYPES_H
31 # include <sys/types.h>
34 #ifdef HAVE_SYS_SOCKET_H
35 #include <sys/socket.h>
38 #ifdef HAVE_NETINET_IN_H
39 #include <netinet/in.h>
46 #ifdef HAVE_ARPA_INET_H
47 #include <arpa/inet.h>
50 #if defined(__APPLE__) && defined(__LP64__)
51 #include <sys/utsname.h>
57 #include <wsutil/cmdarg_err.h>
58 #include <wsutil/crash_info.h>
59 #include <wsutil/strtoi.h>
60 #include <ws_version_info.h>
62 #ifndef HAVE_GETOPT_LONG
63 #include "wsutil/wsgetopt.h"
71 # include <sys/prctl.h>
72 # include <sys/capability.h>
75 #include "ringbuffer.h"
77 #include "caputils/capture_ifinfo.h"
78 #include "caputils/capture-pcap-util.h"
79 #include "caputils/capture-pcap-util-int.h"
81 #include "caputils/capture-wpcap.h"
84 #include "writecap/pcapio.h"
87 #include <wsutil/unicode-utils.h>
94 #include <wsutil/clopts_common.h>
95 #include <wsutil/privileges.h>
97 #include "sync_pipe.h"
99 #include "capture_opts.h"
100 #include <capchild/capture_session.h>
101 #include <capchild/capture_sync.h>
103 #include "conditions.h"
104 #include "capture_stop_conditions.h"
106 #include "wsutil/tempfile.h"
108 #include "wsutil/file_util.h"
109 #include "wsutil/cpu_info.h"
110 #include "wsutil/os_version_info.h"
111 #include "wsutil/str_util.h"
112 #include "wsutil/inet_addr.h"
114 #include "caputils/ws80211_utils.h"
121 * Get information about libpcap format from "wiretap/libpcap.h".
122 * Get information about pcapng format from "wiretap/pcapng_module.h".
123 * XXX - can we just use pcap_open_offline() to read the pipe?
125 #include "wiretap/libpcap.h"
126 #include "wiretap/pcapng_module.h"
128 /**#define DEBUG_DUMPCAP**/
129 /**#define DEBUG_CHILD_DUMPCAP**/
133 #include <conio.h> /* _getch() */
137 #ifdef DEBUG_CHILD_DUMPCAP
138 FILE *debug_log; /* for logging debug messages to */
139 /* a file if DEBUG_CHILD_DUMPCAP */
143 static GAsyncQueue *pcap_queue;
144 static gint64 pcap_queue_bytes;
145 static gint64 pcap_queue_packets;
146 static gint64 pcap_queue_byte_limit = 0;
147 static gint64 pcap_queue_packet_limit = 0;
149 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
151 static gchar *sig_pipe_name = NULL;
152 static HANDLE sig_pipe_handle = NULL;
153 static gboolean signal_pipe_check_running(void);
157 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
158 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
161 /** Stop a low-level capture (stops the capture child). */
162 static void capture_loop_stop(void);
163 /** Close a pipe, or socket if \a from_socket is TRUE */
164 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
168 * Enable kernel BPF JIT compiler if available.
169 * If any calls fail, just drive on - the JIT compiler might not be
170 * enabled, but filtering will still work, and it's not clear what
171 * we could do if the calls fail; should we just report the error
172 * and not continue to capture, should we report it as a warning, or
176 enable_kernel_bpf_jit_compiler(void)
180 static const char file[] = "/proc/sys/net/core/bpf_jit_enable";
182 fd = ws_open(file, O_WRONLY);
186 written = ws_write(fd, "1", strlen("1"));
192 #if !defined (__linux__)
193 #ifndef HAVE_PCAP_BREAKLOOP
195 * We don't have pcap_breakloop(), which is the only way to ensure that
196 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
197 * won't, if the call to read the next packet or batch of packets is
198 * is interrupted by a signal on UN*X, just go back and try again to
201 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
202 * the signal handler, set a flag to stop capturing; however, without
203 * a guarantee of that sort, we can't guarantee that we'll stop capturing
204 * if the read will be retried and won't time out if no packets arrive.
206 * Therefore, on at least some platforms, we work around the lack of
207 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
208 * to wait for packets to arrive, so that we're probably going to be
209 * blocked in the select() when the signal arrives, and can just bail
210 * out of the loop at that point.
212 * However, we don't want to do that on BSD (because "select()" doesn't work
213 * correctly on BPF devices on at least some releases of some flavors of
214 * BSD), and we don't want to do it on Windows (because "select()" is
215 * something for sockets, not for arbitrary handles). (Note that "Windows"
216 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
217 * using WinPcap, not a UNIX libpcap.)
219 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
220 * on BSD times out even if no packets have arrived, so we'll eventually
221 * exit pcap_dispatch() with an indication that no packets have arrived,
222 * and will break out of the capture loop at that point.
224 * On Windows, we can't send a SIGINT to stop capturing, so none of this
225 * applies in any case.
227 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
228 * want to include it if it's not present on this platform, however.
230 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
231 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
233 # define MUST_DO_SELECT
234 # endif /* avoid select */
235 #endif /* HAVE_PCAP_BREAKLOOP */
237 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
238 * in pcap_dispatch(); on the other hand, select() works just fine there.
239 * Hence we use a select for that come what may.
241 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
242 * internally, and, with TPACKET_V3, once that's supported, it'll
243 * support timeouts, at least as I understand the way the code works.
245 #define MUST_DO_SELECT
248 /** init the capture filter */
251 INITFILTER_BAD_FILTER,
252 INITFILTER_OTHER_ERROR
253 } initfilter_status_t;
256 STATE_EXPECT_REC_HDR,
270 * A source of packets from which we're capturing.
272 typedef struct _capture_src {
277 #ifdef MUST_DO_SELECT
278 int pcap_fd; /**< pcap file descriptor */
285 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
286 /**< capture pipe (unix only "input file") */
287 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
288 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
289 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
290 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
292 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
294 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
295 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
296 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
298 char * cap_pipe_buf; /**< Pointer to the data buffer we read into */
299 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
300 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
302 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
303 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
305 cap_pipe_state_t cap_pipe_state;
306 cap_pipe_err_t cap_pipe_err;
309 GMutex *cap_pipe_read_mtx;
310 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
315 * Global capture loop state.
317 typedef struct _loop_data {
319 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
320 int err; /**< if non-zero, error seen while capturing */
321 gint packet_count; /**< Number of packets we have already captured */
322 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
323 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
325 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
327 GArray *pcaps; /**< Array of capture_src's on which we're capturing */
331 guint64 bytes_written;
332 guint32 autostop_files;
335 typedef struct _pcap_queue_element {
336 capture_src *pcap_src;
337 struct pcap_pkthdr phdr;
339 } pcap_queue_element;
342 * Standard secondary message for unexpected errors.
344 static const char please_report[] =
345 "Please report this to the Wireshark developers.\n"
346 "https://bugs.wireshark.org/\n"
347 "(This is not a crash; please do not report it as such.)";
350 * This needs to be static, so that the SIGINT handler can clear the "go"
353 static loop_data global_ld;
356 * Timeout, in milliseconds, for reads from the stream of captured packets
357 * from a capture device.
359 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
360 * 64-bit applications, with sub-second timeouts not to work. The bug is
361 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
363 #if defined(__APPLE__) && defined(__LP64__)
364 static gboolean need_timeout_workaround;
366 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
368 #define CAP_READ_TIMEOUT 250
372 * Timeout, in microseconds, for reads from the stream of captured packets
373 * from a pipe. Pipes don't have the same problem that BPF devices do
374 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
375 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
376 * of the offending versions of Snow Leopard.
378 * On Windows this value is converted to milliseconds and passed to
379 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
380 * will return immediately.
383 #define PIPE_READ_TIMEOUT 100000
385 #define PIPE_READ_TIMEOUT 250000
388 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
391 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
392 const char *message, gpointer user_data _U_);
394 /* capture related options */
395 static capture_options global_capture_opts;
396 static gboolean quiet = FALSE;
397 static gboolean use_threads = FALSE;
398 static guint64 start_time;
400 static void capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
402 static void capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
404 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
405 int err, gboolean is_close);
407 static void WS_NORETURN exit_main(int err);
409 static void report_new_capture_file(const char *filename);
410 static void report_packet_count(unsigned int packet_count);
411 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
412 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
413 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
415 #define MSG_MAX_LENGTH 4096
417 /* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
419 create_timestamp(void) {
429 * Current time, represented as 100-nanosecond intervals since
430 * January 1, 1601, 00:00:00 UTC.
432 * I think DWORD might be signed, so cast both parts of "now"
433 * to guint32 so that the sign bit doesn't get treated specially.
435 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
436 * might want to use instead.
438 GetSystemTimeAsFileTime(&now);
439 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
440 (guint32)now.dwLowDateTime;
443 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
449 * Subtract difference, in microseconds, between January 1, 1601
450 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
452 timestamp -= G_GUINT64_CONSTANT(11644473600000000);
455 * Current time, represented as seconds and microseconds since
456 * January 1, 1970, 00:00:00 UTC.
458 gettimeofday(&now, NULL);
461 * Convert to delta in microseconds.
463 timestamp = (guint64)(now.tv_sec) * 1000000 +
464 (guint64)(now.tv_usec);
470 print_usage(FILE *output)
472 fprintf(output, "\nUsage: dumpcap [options] ...\n");
473 fprintf(output, "\n");
474 fprintf(output, "Capture interface:\n");
475 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
476 " or for remote capturing, use one of these formats:\n"
477 " rpcap://<host>/<interface>\n"
478 " TCP@<host>:<port>\n");
479 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
480 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
481 fprintf(output, " -p don't capture in promiscuous mode\n");
482 #ifdef HAVE_PCAP_CREATE
483 fprintf(output, " -I capture in monitor mode, if available\n");
485 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
486 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
488 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
489 fprintf(output, " -D print list of interfaces and exit\n");
490 fprintf(output, " -L print list of link-layer types of iface and exit\n");
491 #ifdef HAVE_BPF_IMAGE
492 fprintf(output, " -d print generated BPF code for capture filter\n");
494 fprintf(output, " -k set channel on wifi interface:\n"
495 " <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
496 fprintf(output, " -S print statistics for each interface once per second\n");
497 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
498 fprintf(output, "\n");
499 #ifdef HAVE_PCAP_REMOTE
500 fprintf(output, "RPCAP options:\n");
501 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
502 fprintf(output, " -u use UDP for RPCAP data transfer\n");
503 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
504 #ifdef HAVE_PCAP_SETSAMPLING
505 fprintf(output, " -m <sampling type> use packet sampling\n");
506 fprintf(output, " count:NUM - capture one packet of every NUM\n");
507 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
510 fprintf(output, "Stop conditions:\n");
511 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
512 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
513 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
514 fprintf(output, " files:NUM - stop after NUM files\n");
515 /*fprintf(output, "\n");*/
516 fprintf(output, "Output (files):\n");
517 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
518 fprintf(output, " -g enable group read access on the output file(s)\n");
519 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
520 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
521 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
522 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
523 fprintf(output, " -P use libpcap format instead of pcapng\n");
524 fprintf(output, " --capture-comment <comment>\n");
525 fprintf(output, " add a capture comment to the output file\n");
526 fprintf(output, " (only for pcapng)\n");
527 fprintf(output, "\n");
528 fprintf(output, "Miscellaneous:\n");
529 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
530 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
531 fprintf(output, " within dumpcap\n");
532 fprintf(output, " -t use a separate thread per interface\n");
533 fprintf(output, " -q don't report packet capture counts\n");
534 fprintf(output, " -v print version information and exit\n");
535 fprintf(output, " -h display this help and exit\n");
536 fprintf(output, "\n");
538 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
539 fprintf(output, "You might want to reset it\n");
540 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
541 fprintf(output, "\n");
543 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
544 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
545 fprintf(output, "\n");
546 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
550 * Report an error in command-line arguments.
551 * If we're a capture child, send a message back to the parent, otherwise
555 dumpcap_cmdarg_err(const char *fmt, va_list ap)
559 /* Generate a 'special format' message back to parent */
560 msg = g_strdup_vprintf(fmt, ap);
561 sync_pipe_errmsg_to_parent(2, msg, "");
564 fprintf(stderr, "dumpcap: ");
565 vfprintf(stderr, fmt, ap);
566 fprintf(stderr, "\n");
571 * Report additional information for an error in command-line arguments.
572 * If we're a capture child, send a message back to the parent, otherwise
576 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
580 msg = g_strdup_vprintf(fmt, ap);
581 sync_pipe_errmsg_to_parent(2, msg, "");
584 vfprintf(stderr, fmt, ap);
585 fprintf(stderr, "\n");
591 #if 0 /* Set to enable capability debugging */
592 /* see 'man cap_to_text()' for explanation of output */
593 /* '=' means 'all= ' ie: no capabilities */
594 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
596 print_caps(const char *pfx) {
597 cap_t caps = cap_get_proc();
598 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
599 "%s: EUID: %d Capabilities: %s", pfx,
600 geteuid(), cap_to_text(caps, NULL));
603 print_caps(const char *pfx _U_) {
608 relinquish_all_capabilities(void)
610 /* Drop any and all capabilities this process may have. */
611 /* Allowed whether or not process has any privileges. */
612 cap_t caps = cap_init(); /* all capabilities initialized to off */
613 print_caps("Pre-clear");
614 if (cap_set_proc(caps)) {
615 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
617 print_caps("Post-clear");
623 get_capture_device_open_failure_messages(const char *open_err_str,
625 char *errmsg, size_t errmsg_len,
626 char *secondary_errmsg,
627 size_t secondary_errmsg_len)
630 const char *libpcap_warn;
631 static const char ppamsg[] = "can't find PPA for ";
634 g_snprintf(errmsg, (gulong) errmsg_len,
635 "The capture session could not be initiated on interface '%s' (%s).",
636 iface, open_err_str);
639 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
641 "In order to capture packets, WinPcap must be installed; see\n"
643 " https://www.winpcap.org/\n"
645 "for a downloadable version of WinPcap and for instructions on how to install\n"
648 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
650 "Please check that \"%s\" is the proper interface.\n"
653 "Help can be found on the following pages:\n"
655 " https://wiki.wireshark.org/WinPcap\n"
656 " https://wiki.wireshark.org/CaptureSetup\n",
660 /* If we got a "can't find PPA for X" message, warn the user (who
661 is running dumpcap on HP-UX) that they don't have a version of
662 libpcap that properly handles HP-UX (libpcap 0.6.x and later
663 versions, which properly handle HP-UX, say "can't find /dev/dlpi
664 PPA for X" rather than "can't find PPA for X"). */
665 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
668 "You are running (T)Wireshark with a version of the libpcap library\n"
669 "that doesn't handle HP-UX network devices well; this means that\n"
670 "(T)Wireshark may not be able to capture packets.\n"
672 "To fix this, you should install libpcap 0.6.2, or a later version\n"
673 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
674 "packaged binary form from the Software Porting And Archive Centre\n"
675 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
676 "at the URL lists a number of mirror sites.";
680 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
681 "Please check to make sure you have sufficient permissions, and that you have "
682 "the proper interface or pipe specified.%s", libpcap_warn);
687 compile_capture_filter(const char *iface, pcap_t *pcap_h,
688 struct bpf_program *fcode, const char *cfilter)
690 bpf_u_int32 netnum, netmask;
691 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
693 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
695 * Well, we can't get the netmask for this interface; it's used
696 * only for filters that check for broadcast IP addresses, so
697 * we just punt and use 0. It might be nice to warn the user,
698 * but that's a pain in a GUI application, as it'd involve popping
699 * up a message box, and it's not clear how often this would make
700 * a difference (only filters that check for IP broadcast addresses
704 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
709 * Sigh. Older versions of libpcap don't properly declare the
710 * third argument to pcap_compile() as a const pointer. Cast
714 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
720 #ifdef HAVE_BPF_IMAGE
722 show_filter_code(capture_options *capture_opts)
724 interface_options interface_opts;
726 gchar open_err_str[PCAP_ERRBUF_SIZE];
727 char errmsg[MSG_MAX_LENGTH+1];
728 char secondary_errmsg[MSG_MAX_LENGTH+1];
729 struct bpf_program fcode;
730 struct bpf_insn *insn;
734 for (j = 0; j < capture_opts->ifaces->len; j++) {
735 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
736 pcap_h = open_capture_device(capture_opts, &interface_opts,
737 CAP_READ_TIMEOUT, &open_err_str);
738 if (pcap_h == NULL) {
739 /* Open failed; get messages */
740 get_capture_device_open_failure_messages(open_err_str,
742 errmsg, sizeof errmsg,
744 sizeof secondary_errmsg);
745 /* And report them */
746 report_capture_error(errmsg, secondary_errmsg);
750 /* Set the link-layer type. */
751 if (!set_pcap_datalink(pcap_h, interface_opts.linktype, interface_opts.name,
752 errmsg, sizeof errmsg,
753 secondary_errmsg, sizeof secondary_errmsg)) {
755 report_capture_error(errmsg, secondary_errmsg);
759 /* OK, try to compile the capture filter. */
760 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
761 interface_opts.cfilter)) {
763 report_cfilter_error(capture_opts, j, errmsg);
768 /* Now print the filter code. */
769 insn = fcode.bf_insns;
771 for (i = 0; i < fcode.bf_len; insn++, i++)
772 printf("%s\n", bpf_image(insn, i));
774 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
775 /* to remove any suid privileges. */
776 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
777 /* (euid/egid have already previously been set to ruid/rgid. */
778 /* (See comment in main() for details) */
780 relinquish_special_privs_perm();
782 relinquish_all_capabilities();
785 /* Let our parent know we succeeded. */
786 pipe_write_block(2, SP_SUCCESS, NULL);
793 * capture_interface_list() is expected to do the right thing to get
794 * a list of interfaces.
796 * In most of the programs in the Wireshark suite, "the right thing"
797 * is to run dumpcap and ask it for the list, because dumpcap may
798 * be the only program in the suite with enough privileges to get
801 * In dumpcap itself, however, we obviously can't run dumpcap to
802 * ask for the list. Therefore, our capture_interface_list() should
803 * just call get_interface_list().
806 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
808 return get_interface_list(err, err_str);
811 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
813 * Output a machine readable list of the interfaces
814 * This list is retrieved by the sync_interface_list_open() function
815 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
818 print_machine_readable_interfaces(GList *if_list)
825 char addr_str[ADDRSTRLEN];
828 /* Let our parent know we succeeded. */
829 pipe_write_block(2, SP_SUCCESS, NULL);
832 i = 1; /* Interface id number */
833 for (if_entry = g_list_first(if_list); if_entry != NULL;
834 if_entry = g_list_next(if_entry)) {
835 if_info = (if_info_t *)if_entry->data;
836 printf("%d. %s\t", i++, if_info->name);
839 * Print the contents of the if_entry struct in a parseable format.
840 * Each if_entry element is tab-separated. Addresses are comma-
843 /* XXX - Make sure our description doesn't contain a tab */
844 if (if_info->vendor_description != NULL)
845 printf("%s\t", if_info->vendor_description);
849 /* XXX - Make sure our friendly name doesn't contain a tab */
850 if (if_info->friendly_name != NULL)
851 printf("%s\t", if_info->friendly_name);
855 printf("%i\t", if_info->type);
857 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
858 addr = g_slist_next(addr)) {
859 if (addr != g_slist_nth(if_info->addrs, 0))
862 if_addr = (if_addr_t *)addr->data;
863 switch(if_addr->ifat_type) {
865 if (ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str,
867 printf("%s", addr_str);
869 printf("<unknown IPv4>");
873 if (ws_inet_ntop6(&if_addr->addr.ip6_addr,
874 addr_str, ADDRSTRLEN)) {
875 printf("%s", addr_str);
877 printf("<unknown IPv6>");
881 printf("<type unknown %i>", if_addr->ifat_type);
885 if (if_info->loopback)
886 printf("\tloopback");
890 printf("\t%s", if_info->extcap);
897 * If you change the machine-readable output format of this function,
898 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
901 print_machine_readable_if_capabilities(if_capabilities_t *caps)
904 data_link_info_t *data_link_info;
905 const gchar *desc_str;
908 /* Let our parent know we succeeded. */
909 pipe_write_block(2, SP_SUCCESS, NULL);
912 if (caps->can_set_rfmon)
916 for (lt_entry = caps->data_link_types; lt_entry != NULL;
917 lt_entry = g_list_next(lt_entry)) {
918 data_link_info = (data_link_info_t *)lt_entry->data;
919 if (data_link_info->description != NULL)
920 desc_str = data_link_info->description;
922 desc_str = "(not supported)";
923 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
933 /* Print the number of packets captured for each interface until we're killed. */
935 print_statistics_loop(gboolean machine_readable)
937 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
943 char errbuf[PCAP_ERRBUF_SIZE];
946 if_list = get_interface_list(&err, &err_str);
947 if (if_list == NULL) {
949 cmdarg_err("There are no interfaces on which a capture can be done");
951 cmdarg_err("%s", err_str);
957 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
958 if_info = (if_info_t *)if_entry->data;
961 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
962 * connections. We avoid collecting stats on them.
964 if (!strncmp(if_info->name, "nf", 2)) {
965 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
971 #ifdef HAVE_PCAP_OPEN
972 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
974 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
978 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
979 if_stat->name = g_strdup(if_info->name);
981 stat_list = g_list_append(stat_list, if_stat);
986 cmdarg_err("There are no interfaces on which a capture can be done");
991 /* Let our parent know we succeeded. */
992 pipe_write_block(2, SP_SUCCESS, NULL);
995 if (!machine_readable) {
996 printf("%-15s %10s %10s\n", "Interface", "Received",
1000 global_ld.go = TRUE;
1001 while (global_ld.go) {
1002 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1003 if_stat = (if_stat_t *)stat_entry->data;
1004 pcap_stats(if_stat->pch, &ps);
1006 if (!machine_readable) {
1007 printf("%-15s %10u %10u\n", if_stat->name,
1008 ps.ps_recv, ps.ps_drop);
1010 printf("%s\t%u\t%u\n", if_stat->name,
1011 ps.ps_recv, ps.ps_drop);
1016 /* If we have a dummy signal pipe check it */
1017 if (!signal_pipe_check_running()) {
1018 global_ld.go = FALSE;
1026 /* XXX - Not reached. Should we look for 'q' in stdin? */
1027 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1028 if_stat = (if_stat_t *)stat_entry->data;
1029 pcap_close(if_stat->pch);
1030 g_free(if_stat->name);
1033 g_list_free(stat_list);
1034 free_interface_list(if_list);
1042 capture_cleanup_handler(DWORD dwCtrlType)
1044 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1045 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1046 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1047 like SIGTERM at least when the machine's shutting down.
1049 For now, if we're running as a command rather than a capture child,
1050 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1051 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1052 in that way on UN*X.
1054 If we're not running as a capture child, we might be running as
1055 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1056 user logs out. (XXX - can we explicitly check whether we're
1057 running as a service?) */
1059 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1060 "Console: Control signal");
1061 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1062 "Console: Control signal, CtrlType: %u", dwCtrlType);
1064 /* Keep capture running if we're a service and a user logs off */
1065 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1066 capture_loop_stop();
1074 capture_cleanup_handler(int signum _U_)
1076 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1077 SIGTERM. We assume that if the user wanted it to keep running
1078 after they logged out, they'd have nohupped it. */
1080 /* Note: don't call g_log() in the signal handler: if we happened to be in
1081 * g_log() in process context when the signal came in, g_log will detect
1082 * the "recursion" and abort.
1085 capture_loop_stop();
1091 report_capture_count(gboolean reportit)
1093 /* Don't print this if we're a capture child. */
1094 if (!capture_child && reportit) {
1095 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packet_count);
1096 /* stderr could be line buffered */
1104 report_counts_for_siginfo(void)
1106 report_capture_count(quiet);
1107 infoprint = FALSE; /* we just reported it */
1111 report_counts_siginfo(int signum _U_)
1113 int sav_errno = errno;
1115 /* If we've been told to delay printing, just set a flag asking
1116 that we print counts (if we're supposed to), otherwise print
1117 the count of packets captured (if we're supposed to). */
1121 report_counts_for_siginfo();
1124 #endif /* SIGINFO */
1127 exit_main(int status)
1130 /* Shutdown windows sockets */
1133 /* can be helpful for debugging */
1134 #ifdef DEBUG_DUMPCAP
1135 printf("Press any key\n");
1141 capture_opts_cleanup(&global_capture_opts);
1147 * If we were linked with libcap (not related to libpcap), make sure we have
1148 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1149 * (See comment in main() for details)
1152 relinquish_privs_except_capture(void)
1154 /* If 'started_with_special_privs' (ie: suid) then enable for
1155 * ourself the NET_ADMIN and NET_RAW capabilities and then
1156 * drop our suid privileges.
1158 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1159 * stuff we don't need (and shouldn't have).
1160 * CAP_NET_RAW: Packet capture (raw sockets).
1163 if (started_with_special_privs()) {
1164 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1165 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1167 cap_t caps = cap_init(); /* all capabilities initialized to off */
1169 print_caps("Pre drop, pre set");
1171 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1172 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1175 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1176 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1178 if (cap_set_proc(caps)) {
1179 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1181 print_caps("Pre drop, post set");
1183 relinquish_special_privs_perm();
1185 print_caps("Post drop, pre set");
1186 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1187 if (cap_set_proc(caps)) {
1188 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1190 print_caps("Post drop, post set");
1196 #endif /* HAVE_LIBCAP */
1198 /* Take care of byte order in the libpcap headers read from pipes.
1199 * (function taken from wiretap/libpcap.c) */
1201 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1204 /* Byte-swap the record header fields. */
1205 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1206 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1207 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1208 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1211 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1212 swapped, in order to match the BPF header layout.
1214 Unfortunately, some files were, according to a comment in the "libpcap"
1215 source, written with version 2.3 in their headers but without the
1216 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1217 would make no sense - we assume that we need to swap them. */
1218 if (hdr->version_major == 2 &&
1219 (hdr->version_minor < 3 ||
1220 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1223 temp = rechdr->orig_len;
1224 rechdr->orig_len = rechdr->incl_len;
1225 rechdr->incl_len = temp;
1229 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1233 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1237 return recv(pipe_fd, buf, (int)sz, 0);
1242 return ws_read(pipe_fd, buf, sz);
1248 * Thread function that reads from a pipe and pushes the data
1249 * to the main application thread.
1252 * XXX Right now we use async queues for basic signaling. The main thread
1253 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1254 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1255 * Iff the read is successful cap_pipe_read pushes an item onto
1256 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1257 * the queues themselves (yet).
1259 * We might want to move some of the cap_pipe_dispatch logic here so that
1260 * we can let cap_thread_read run independently, queuing up multiple reads
1261 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1263 static void *cap_thread_read(void *arg)
1265 capture_src *pcap_src;
1268 DWORD b, last_err, bytes_read;
1274 pcap_src = (capture_src *)arg;
1275 while (pcap_src->cap_pipe_err == PIPOK) {
1276 g_async_queue_pop(pcap_src->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1277 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1279 while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1280 if ((pcap_src->from_cap_socket)
1286 b = cap_pipe_read(pcap_src->cap_pipe_fd, pcap_src->cap_pipe_buf+bytes_read,
1287 pcap_src->cap_pipe_bytes_to_read - bytes_read, pcap_src->from_cap_socket);
1290 pcap_src->cap_pipe_err = PIPEOF;
1294 pcap_src->cap_pipe_err = PIPERR;
1305 /* If we try to use read() on a named pipe on Windows with partial
1306 * data it appears to return EOF.
1308 res = ReadFile(pcap_src->cap_pipe_h, pcap_src->cap_pipe_buf+bytes_read,
1309 pcap_src->cap_pipe_bytes_to_read - bytes_read,
1314 last_err = GetLastError();
1315 if (last_err == ERROR_MORE_DATA) {
1317 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1318 pcap_src->cap_pipe_err = PIPEOF;
1322 pcap_src->cap_pipe_err = PIPERR;
1325 } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1326 pcap_src->cap_pipe_err = PIPEOF;
1333 pcap_src->cap_pipe_bytes_read = bytes_read;
1334 if (pcap_src->cap_pipe_bytes_read >= pcap_src->cap_pipe_bytes_to_read) {
1335 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1337 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1343 /* Provide select() functionality for a single file descriptor
1344 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1346 * Returns the same values as select.
1349 cap_pipe_select(int pipe_fd)
1352 struct timeval timeout;
1355 FD_SET(pipe_fd, &rfds);
1357 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1358 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1360 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1363 #define DEF_TCP_PORT 19000
1366 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, int errmsgl)
1368 char *sockname = pipename + 4;
1369 struct sockaddr_in sa;
1376 memset(&sa, 0, sizeof(sa));
1378 p = strchr(sockname, ':');
1380 len = strlen(sockname);
1381 port = DEF_TCP_PORT;
1385 port = strtoul(p + 1, &p, 10);
1386 if (*p || port > 65535) {
1395 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1397 if (!ws_inet_pton4(buf, (guint32 *)&sa.sin_addr)) {
1401 sa.sin_family = AF_INET;
1402 sa.sin_port = g_htons((u_short)port);
1404 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1405 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1407 LPTSTR errorText = NULL;
1410 lastError = WSAGetLastError();
1411 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1412 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1413 FORMAT_MESSAGE_IGNORE_INSERTS,
1414 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1415 (LPTSTR)&errorText, 0, NULL);
1417 g_snprintf(errmsg, errmsgl,
1418 "The capture session could not be initiated due to the socket error: \n"
1420 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1422 LocalFree(errorText);
1424 " %d: %s", errno, g_strerror(errno));
1426 pcap_src->cap_pipe_err = PIPERR;
1429 cap_pipe_close(fd, TRUE);
1433 pcap_src->from_cap_socket = TRUE;
1437 g_snprintf(errmsg, errmsgl,
1438 "The capture session could not be initiated because\n"
1439 "\"%s\" is not a valid socket specification", pipename);
1440 pcap_src->cap_pipe_err = PIPERR;
1444 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1448 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1452 closesocket(pipe_fd);
1459 /* Mimic pcap_open_live() for pipe captures
1461 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1462 * open it, and read the header.
1464 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1465 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1467 cap_pipe_open_live(char *pipename,
1468 capture_src *pcap_src,
1469 struct pcap_hdr *hdr,
1470 char *errmsg, int errmsgl)
1473 ws_statb64 pipe_stat;
1474 struct sockaddr_un sa;
1479 char* extcap_pipe_name;
1483 gboolean extcap_pipe = FALSE;
1484 interface_options interface_opts;
1487 int fd = -1, sel_ret;
1490 pcap_src->cap_pipe_fd = -1;
1492 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1495 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1498 * XXX - this blocks until a pcap per-file header has been written to
1499 * the pipe, so it could block indefinitely.
1501 if (strcmp(pipename, "-") == 0) {
1503 fd = 0; /* read from stdin */
1505 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1507 } else if (!strncmp(pipename, "TCP@", 4)) {
1508 if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1514 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
1519 if ( g_strrstr(interface_opts.name, EXTCAP_PIPE_PREFIX) != NULL )
1523 if (ws_stat64(pipename, &pipe_stat) < 0) {
1524 if (errno == ENOENT || errno == ENOTDIR)
1525 pcap_src->cap_pipe_err = PIPNEXIST;
1527 g_snprintf(errmsg, errmsgl,
1528 "The capture session could not be initiated "
1529 "due to error getting information on pipe/socket: %s.", g_strerror(errno));
1530 pcap_src->cap_pipe_err = PIPERR;
1534 if (S_ISFIFO(pipe_stat.st_mode)) {
1535 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1537 g_snprintf(errmsg, errmsgl,
1538 "The capture session could not be initiated "
1539 "due to error on pipe open: %s.", g_strerror(errno));
1540 pcap_src->cap_pipe_err = PIPERR;
1543 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1544 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1546 g_snprintf(errmsg, errmsgl,
1547 "The capture session could not be initiated "
1548 "due to error on socket create: %s.", g_strerror(errno));
1549 pcap_src->cap_pipe_err = PIPERR;
1552 sa.sun_family = AF_UNIX;
1554 * The Single UNIX Specification says:
1556 * The size of sun_path has intentionally been left undefined.
1557 * This is because different implementations use different sizes.
1558 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1559 * of 104. Since most implementations originate from BSD versions,
1560 * the size is typically in the range 92 to 108.
1562 * Applications should not assume a particular length for sun_path
1563 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1567 * The <sys/un.h> header shall define the sockaddr_un structure,
1568 * which shall include at least the following members:
1570 * sa_family_t sun_family Address family.
1571 * char sun_path[] Socket pathname.
1573 * so we assume that it's an array, with a specified size,
1574 * and that the size reflects the maximum path length.
1576 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1577 /* Path name too long */
1578 g_snprintf(errmsg, errmsgl,
1579 "The capture session coud not be initiated "
1580 "due to error on socket connect: Path name too long.");
1581 pcap_src->cap_pipe_err = PIPERR;
1585 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1587 g_snprintf(errmsg, errmsgl,
1588 "The capture session coud not be initiated "
1589 "due to error on socket connect: %s.", g_strerror(errno));
1590 pcap_src->cap_pipe_err = PIPERR;
1595 if (S_ISCHR(pipe_stat.st_mode)) {
1597 * Assume the user specified an interface on a system where
1598 * interfaces are in /dev. Pretend we haven't seen it.
1600 pcap_src->cap_pipe_err = PIPNEXIST;
1602 g_snprintf(errmsg, errmsgl,
1603 "The capture session could not be initiated because\n"
1604 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1605 pcap_src->cap_pipe_err = PIPERR;
1611 #define PIPE_STR "\\pipe\\"
1612 /* Under Windows, named pipes _must_ have the form
1613 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1615 pncopy = g_strdup(pipename);
1616 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1617 pos = strchr(pncopy + 3, '\\');
1618 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1625 g_snprintf(errmsg, errmsgl,
1626 "The capture session could not be initiated because\n"
1627 "\"%s\" is neither an interface nor a pipe.", pipename);
1628 pcap_src->cap_pipe_err = PIPNEXIST;
1632 extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
1633 extcap_pipe = strstr(interface_opts.name, extcap_pipe_name) ? TRUE : FALSE;
1634 g_free(extcap_pipe_name);
1637 /* Wait for the pipe to appear */
1642 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1645 pcap_src->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1646 OPEN_EXISTING, 0, NULL);
1648 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE)
1651 if (GetLastError() != ERROR_PIPE_BUSY) {
1652 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1653 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1654 g_snprintf(errmsg, errmsgl,
1655 "The capture session on \"%s\" could not be started "
1656 "due to error on pipe open: %s (error %d).",
1657 pipename, utf_16to8(err_str), GetLastError());
1659 pcap_src->cap_pipe_err = PIPERR;
1663 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1664 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1665 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1666 g_snprintf(errmsg, errmsgl,
1667 "The capture session on \"%s\" timed out during "
1668 "pipe open: %s (error %d).",
1669 pipename, utf_16to8(err_str), GetLastError());
1671 pcap_src->cap_pipe_err = PIPERR;
1678 pcap_src->from_cap_pipe = TRUE;
1681 if (pcap_src->from_cap_socket)
1684 /* read the pcap header */
1686 while (bytes_read < sizeof magic) {
1688 g_snprintf(errmsg, errmsgl, "Invalid file descriptor.");
1692 sel_ret = cap_pipe_select(fd);
1694 g_snprintf(errmsg, errmsgl,
1695 "Unexpected error from select: %s.", g_strerror(errno));
1697 } else if (sel_ret > 0) {
1698 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1699 sizeof magic-bytes_read,
1700 pcap_src->from_cap_socket);
1702 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1703 if (extcap_pipe && b <= 0)
1708 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1710 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1720 #if GLIB_CHECK_VERSION(2,31,0)
1721 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
1723 g_thread_create(&cap_thread_read, pcap_src, FALSE, NULL);
1726 pcap_src->cap_pipe_buf = (char *) &magic;
1727 pcap_src->cap_pipe_bytes_read = 0;
1728 pcap_src->cap_pipe_bytes_to_read = sizeof(magic);
1729 /* We don't have to worry about cap_pipe_read_mtx here */
1730 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1731 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1732 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1733 if (pcap_src->cap_pipe_bytes_read <= 0 && extcap_pipe)
1736 if (pcap_src->cap_pipe_bytes_read <= 0) {
1737 if (pcap_src->cap_pipe_bytes_read == 0)
1738 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1740 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1749 case PCAP_NSEC_MAGIC:
1750 /* Host that wrote it has our byte order, and was running
1751 a program using either standard or ss990417 libpcap. */
1752 pcap_src->cap_pipe_byte_swapped = FALSE;
1753 pcap_src->cap_pipe_modified = FALSE;
1754 pcap_src->ts_nsec = magic == PCAP_NSEC_MAGIC;
1756 case PCAP_MODIFIED_MAGIC:
1757 /* Host that wrote it has our byte order, but was running
1758 a program using either ss990915 or ss991029 libpcap. */
1759 pcap_src->cap_pipe_byte_swapped = FALSE;
1760 pcap_src->cap_pipe_modified = TRUE;
1762 case PCAP_SWAPPED_MAGIC:
1763 case PCAP_SWAPPED_NSEC_MAGIC:
1764 /* Host that wrote it has a byte order opposite to ours,
1765 and was running a program using either standard or
1766 ss990417 libpcap. */
1767 pcap_src->cap_pipe_byte_swapped = TRUE;
1768 pcap_src->cap_pipe_modified = FALSE;
1769 pcap_src->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
1771 case PCAP_SWAPPED_MODIFIED_MAGIC:
1772 /* Host that wrote it out has a byte order opposite to
1773 ours, and was running a program using either ss990915
1774 or ss991029 libpcap. */
1775 pcap_src->cap_pipe_byte_swapped = TRUE;
1776 pcap_src->cap_pipe_modified = TRUE;
1778 case BLOCK_TYPE_SHB:
1779 /* This isn't pcap, it's pcapng. We don't yet support
1781 g_snprintf(errmsg, errmsgl, "Capturing from a pipe doesn't support pcapng format.");
1784 /* Not a pcap type we know about, or not pcap at all. */
1785 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format or not libpcap data.");
1790 if (pcap_src->from_cap_socket)
1793 /* Read the rest of the header */
1795 while (bytes_read < sizeof(struct pcap_hdr)) {
1796 sel_ret = cap_pipe_select(fd);
1798 g_snprintf(errmsg, errmsgl,
1799 "Unexpected error from select: %s.", g_strerror(errno));
1801 } else if (sel_ret > 0) {
1802 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
1803 sizeof(struct pcap_hdr) - bytes_read,
1804 pcap_src->from_cap_socket);
1807 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1809 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s.",
1819 pcap_src->cap_pipe_buf = (char *) hdr;
1820 pcap_src->cap_pipe_bytes_read = 0;
1821 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1822 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1823 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1824 if (pcap_src->cap_pipe_bytes_read <= 0) {
1825 if (pcap_src->cap_pipe_bytes_read == 0)
1826 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1828 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s.",
1835 if (pcap_src->cap_pipe_byte_swapped) {
1836 /* Byte-swap the header fields about which we care. */
1837 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
1838 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
1839 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
1840 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
1842 pcap_src->linktype = hdr->network;
1844 if (hdr->version_major < 2) {
1845 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1849 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
1850 pcap_src->cap_pipe_err = PIPOK;
1851 pcap_src->cap_pipe_fd = fd;
1855 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1856 pcap_src->cap_pipe_err = PIPERR;
1857 cap_pipe_close(fd, pcap_src->from_cap_socket);
1858 pcap_src->cap_pipe_fd = -1;
1860 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1865 /* We read one record from the pipe, take care of byte order in the record
1866 * header, write the record to the capture file, and update capture statistics. */
1868 cap_pipe_dispatch(loop_data *ld, capture_src *pcap_src, guchar *data, char *errmsg, int errmsgl)
1870 struct pcap_pkthdr phdr;
1871 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1874 #if !GLIB_CHECK_VERSION(2,31,18)
1882 #ifdef LOG_CAPTURE_VERBOSE
1883 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1886 switch (pcap_src->cap_pipe_state) {
1888 case STATE_EXPECT_REC_HDR:
1890 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
1893 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
1894 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_modified ?
1895 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1896 pcap_src->cap_pipe_bytes_read = 0;
1899 pcap_src->cap_pipe_buf = (char *) &pcap_src->cap_pipe_rechdr;
1900 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1901 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1906 case STATE_READ_REC_HDR:
1908 if (pcap_src->from_cap_socket)
1911 b = cap_pipe_read(pcap_src->cap_pipe_fd, ((char *)&pcap_src->cap_pipe_rechdr)+pcap_src->cap_pipe_bytes_read,
1912 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read, pcap_src->from_cap_socket);
1915 result = PD_PIPE_EOF;
1917 result = PD_PIPE_ERR;
1920 pcap_src->cap_pipe_bytes_read += b;
1924 #if GLIB_CHECK_VERSION(2,31,18)
1925 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
1927 g_get_current_time(&wait_time);
1928 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
1929 q_status = g_async_queue_timed_pop(pcap_src->cap_pipe_done_q, &wait_time);
1931 if (pcap_src->cap_pipe_err == PIPEOF) {
1932 result = PD_PIPE_EOF;
1934 } else if (pcap_src->cap_pipe_err == PIPERR) {
1935 result = PD_PIPE_ERR;
1943 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
1945 result = PD_REC_HDR_READ;
1948 case STATE_EXPECT_DATA:
1950 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
1953 pcap_src->cap_pipe_state = STATE_READ_DATA;
1954 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_rechdr.hdr.incl_len;
1955 pcap_src->cap_pipe_bytes_read = 0;
1958 pcap_src->cap_pipe_buf = (char *) data;
1959 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1960 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1965 case STATE_READ_DATA:
1967 if (pcap_src->from_cap_socket)
1970 b = cap_pipe_read(pcap_src->cap_pipe_fd,
1971 data+pcap_src->cap_pipe_bytes_read,
1972 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read,
1973 pcap_src->from_cap_socket);
1976 result = PD_PIPE_EOF;
1978 result = PD_PIPE_ERR;
1981 pcap_src->cap_pipe_bytes_read += b;
1986 #if GLIB_CHECK_VERSION(2,31,18)
1987 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
1989 g_get_current_time(&wait_time);
1990 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
1991 q_status = g_async_queue_timed_pop(pcap_src->cap_pipe_done_q, &wait_time);
1992 #endif /* GLIB_CHECK_VERSION(2,31,18) */
1993 if (pcap_src->cap_pipe_err == PIPEOF) {
1994 result = PD_PIPE_EOF;
1996 } else if (pcap_src->cap_pipe_err == PIPERR) {
1997 result = PD_PIPE_ERR;
2005 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2007 result = PD_DATA_READ;
2011 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2014 } /* switch (pcap_src->cap_pipe_state) */
2017 * We've now read as much data as we were expecting, so process it.
2021 case PD_REC_HDR_READ:
2022 /* We've read the header. Take care of byte order. */
2023 cap_pipe_adjust_header(pcap_src->cap_pipe_byte_swapped, &pcap_src->cap_pipe_hdr,
2024 &pcap_src->cap_pipe_rechdr.hdr);
2025 if (pcap_src->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2026 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2027 ld->packet_count+1, pcap_src->cap_pipe_rechdr.hdr.incl_len);
2031 if (pcap_src->cap_pipe_rechdr.hdr.incl_len) {
2032 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2035 /* no data to read? */
2038 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2039 phdr.ts.tv_sec = pcap_src->cap_pipe_rechdr.hdr.ts_sec;
2040 phdr.ts.tv_usec = pcap_src->cap_pipe_rechdr.hdr.ts_usec;
2041 phdr.caplen = pcap_src->cap_pipe_rechdr.hdr.incl_len;
2042 phdr.len = pcap_src->cap_pipe_rechdr.hdr.orig_len;
2045 capture_loop_queue_packet_cb((u_char *)pcap_src, &phdr, data);
2047 capture_loop_write_packet_cb((u_char *)pcap_src, &phdr, data);
2049 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2053 pcap_src->cap_pipe_err = PIPEOF;
2058 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2059 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2060 g_snprintf(errmsg, errmsgl,
2061 "Error reading from pipe: %s (error %d)",
2062 utf_16to8(err_str), GetLastError());
2065 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2073 pcap_src->cap_pipe_err = PIPERR;
2074 /* Return here rather than inside the switch to prevent GCC warning */
2079 /** Open the capture input file (pcap or capture pipe).
2080 * Returns TRUE if it succeeds, FALSE otherwise. */
2082 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2083 char *errmsg, size_t errmsg_len,
2084 char *secondary_errmsg, size_t secondary_errmsg_len)
2086 gchar open_err_str[PCAP_ERRBUF_SIZE];
2087 gchar *sync_msg_str;
2088 interface_options interface_opts;
2089 capture_src *pcap_src;
2093 WORD wVersionRequested;
2097 /* XXX - opening Winsock on tshark? */
2099 /* Initialize Windows Socket if we are in a Win32 OS
2100 This needs to be done before querying the interface for network/netmask */
2102 /* XXX - do we really require 1.1 or earlier?
2103 Are there any versions that support only 2.0 or higher? */
2104 wVersionRequested = MAKEWORD(1, 1);
2105 err = WSAStartup(wVersionRequested, &wsaData);
2109 case WSASYSNOTREADY:
2110 g_snprintf(errmsg, (gulong) errmsg_len,
2111 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2114 case WSAVERNOTSUPPORTED:
2115 g_snprintf(errmsg, (gulong) errmsg_len,
2116 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2117 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2120 case WSAEINPROGRESS:
2121 g_snprintf(errmsg, (gulong) errmsg_len,
2122 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2126 g_snprintf(errmsg, (gulong) errmsg_len,
2127 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2131 g_snprintf(errmsg, (gulong) errmsg_len,
2132 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2136 g_snprintf(errmsg, (gulong) errmsg_len,
2137 "Couldn't initialize Windows Sockets: error %d", err);
2140 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2144 if ((use_threads == FALSE) &&
2145 (capture_opts->ifaces->len > 1)) {
2146 g_snprintf(errmsg, (gulong) errmsg_len,
2147 "Using threads is required for capturing on multiple interfaces.");
2151 for (i = 0; i < capture_opts->ifaces->len; i++) {
2152 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2153 pcap_src = (capture_src *)g_malloc(sizeof (capture_src));
2154 if (pcap_src == NULL) {
2155 g_snprintf(errmsg, (gulong) errmsg_len,
2156 "Could not allocate memory.");
2159 pcap_src->received = 0;
2160 pcap_src->dropped = 0;
2161 pcap_src->flushed = 0;
2162 pcap_src->pcap_h = NULL;
2163 #ifdef MUST_DO_SELECT
2164 pcap_src->pcap_fd = -1;
2166 pcap_src->pcap_err = FALSE;
2167 pcap_src->interface_id = i;
2168 pcap_src->tid = NULL;
2169 pcap_src->snaplen = 0;
2170 pcap_src->linktype = -1;
2171 pcap_src->ts_nsec = FALSE;
2172 pcap_src->from_cap_pipe = FALSE;
2173 pcap_src->from_cap_socket = FALSE;
2174 memset(&pcap_src->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2175 memset(&pcap_src->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2177 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2179 pcap_src->cap_pipe_fd = -1;
2180 pcap_src->cap_pipe_modified = FALSE;
2181 pcap_src->cap_pipe_byte_swapped = FALSE;
2183 pcap_src->cap_pipe_buf = NULL;
2185 pcap_src->cap_pipe_bytes_to_read = 0;
2186 pcap_src->cap_pipe_bytes_read = 0;
2187 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2188 pcap_src->cap_pipe_err = PIPOK;
2190 #if GLIB_CHECK_VERSION(2,31,0)
2191 pcap_src->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2192 g_mutex_init(pcap_src->cap_pipe_read_mtx);
2194 pcap_src->cap_pipe_read_mtx = g_mutex_new();
2196 pcap_src->cap_pipe_pending_q = g_async_queue_new();
2197 pcap_src->cap_pipe_done_q = g_async_queue_new();
2199 g_array_append_val(ld->pcaps, pcap_src);
2201 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2202 pcap_src->pcap_h = open_capture_device(capture_opts, &interface_opts,
2203 CAP_READ_TIMEOUT, &open_err_str);
2205 if (pcap_src->pcap_h != NULL) {
2206 /* we've opened "iface" as a network device */
2208 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2209 /* Find out if we're getting nanosecond-precision time stamps */
2210 pcap_src->ts_nsec = have_high_resolution_timestamp(pcap_src->pcap_h);
2213 #if defined(HAVE_PCAP_SETSAMPLING)
2214 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2215 struct pcap_samp *samp;
2217 if ((samp = pcap_setsampling(pcap_src->pcap_h)) != NULL) {
2218 switch (interface_opts.sampling_method) {
2219 case CAPTURE_SAMP_BY_COUNT:
2220 samp->method = PCAP_SAMP_1_EVERY_N;
2223 case CAPTURE_SAMP_BY_TIMER:
2224 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2228 sync_msg_str = g_strdup_printf(
2229 "Unknown sampling method %d specified,\n"
2230 "continue without packet sampling",
2231 interface_opts.sampling_method);
2232 report_capture_error("Couldn't set the capture "
2233 "sampling", sync_msg_str);
2234 g_free(sync_msg_str);
2236 samp->value = interface_opts.sampling_param;
2238 report_capture_error("Couldn't set the capture sampling",
2239 "Cannot get packet sampling data structure");
2244 /* setting the data link type only works on real interfaces */
2245 if (!set_pcap_datalink(pcap_src->pcap_h, interface_opts.linktype,
2246 interface_opts.name,
2248 secondary_errmsg, secondary_errmsg_len)) {
2251 pcap_src->linktype = get_pcap_datalink(pcap_src->pcap_h, interface_opts.name);
2253 /* We couldn't open "iface" as a network device. */
2254 /* Try to open it as a pipe */
2255 cap_pipe_open_live(interface_opts.name, pcap_src, &pcap_src->cap_pipe_hdr, errmsg, (int) errmsg_len);
2258 if (pcap_src->cap_pipe_fd == -1) {
2260 if (pcap_src->cap_pipe_h == INVALID_HANDLE_VALUE) {
2262 if (pcap_src->cap_pipe_err == PIPNEXIST) {
2264 * We tried opening as an interface, and that failed,
2265 * so we tried to open it as a pipe, but the pipe
2266 * doesn't exist. Report the error message for
2269 get_capture_device_open_failure_messages(open_err_str,
2270 interface_opts.name,
2274 secondary_errmsg_len);
2277 * Else pipe (or file) does exist and cap_pipe_open_live() has
2282 /* cap_pipe_open_live() succeeded; don't want
2283 error message from pcap_open_live() */
2284 open_err_str[0] = '\0';
2288 /* XXX - will this work for tshark? */
2289 #ifdef MUST_DO_SELECT
2290 if (!pcap_src->from_cap_pipe) {
2291 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2292 pcap_src->pcap_fd = pcap_get_selectable_fd(pcap_src->pcap_h);
2294 pcap_src->pcap_fd = pcap_fileno(pcap_src->pcap_h);
2299 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2300 returned a warning; print it, but keep capturing. */
2301 if (open_err_str[0] != '\0') {
2302 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2303 report_capture_error(sync_msg_str, "");
2304 g_free(sync_msg_str);
2306 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2307 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2310 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2311 /* to remove any suid privileges. */
2312 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2313 /* (euid/egid have already previously been set to ruid/rgid. */
2314 /* (See comment in main() for details) */
2316 relinquish_special_privs_perm();
2318 relinquish_all_capabilities();
2323 /* close the capture input file (pcap or capture pipe) */
2324 static void capture_loop_close_input(loop_data *ld)
2327 capture_src *pcap_src;
2329 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2331 for (i = 0; i < ld->pcaps->len; i++) {
2332 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2333 /* if open, close the capture pipe "input file" */
2334 if (pcap_src->cap_pipe_fd >= 0) {
2335 g_assert(pcap_src->from_cap_pipe);
2336 cap_pipe_close(pcap_src->cap_pipe_fd, pcap_src->from_cap_socket);
2337 pcap_src->cap_pipe_fd = -1;
2340 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE) {
2341 CloseHandle(pcap_src->cap_pipe_h);
2342 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2345 /* if open, close the pcap "input file" */
2346 if (pcap_src->pcap_h != NULL) {
2347 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_src->pcap_h);
2348 pcap_close(pcap_src->pcap_h);
2349 pcap_src->pcap_h = NULL;
2356 /* Shut down windows sockets */
2362 /* init the capture filter */
2363 static initfilter_status_t
2364 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2365 const gchar * name, const gchar * cfilter)
2367 struct bpf_program fcode;
2369 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2371 /* capture filters only work on real interfaces */
2372 if (cfilter && !from_cap_pipe) {
2373 /* A capture filter was specified; set it up. */
2374 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2375 /* Treat this specially - our caller might try to compile this
2376 as a display filter and, if that succeeds, warn the user that
2377 the display and capture filter syntaxes are different. */
2378 return INITFILTER_BAD_FILTER;
2380 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2381 #ifdef HAVE_PCAP_FREECODE
2382 pcap_freecode(&fcode);
2384 return INITFILTER_OTHER_ERROR;
2386 #ifdef HAVE_PCAP_FREECODE
2387 pcap_freecode(&fcode);
2391 return INITFILTER_NO_ERROR;
2395 /* set up to write to the already-opened capture output file/files */
2397 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2401 capture_src *pcap_src;
2402 interface_options interface_opts;
2403 gboolean successful;
2405 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2407 if ((capture_opts->use_pcapng == FALSE) &&
2408 (capture_opts->ifaces->len > 1)) {
2409 g_snprintf(errmsg, errmsg_len,
2410 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
2414 /* Set up to write to the capture file. */
2415 if (capture_opts->multi_files_on) {
2416 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2418 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2419 if (ld->pdh == NULL) {
2424 if (capture_opts->use_pcapng) {
2426 GString *cpu_info_str;
2427 GString *os_info_str;
2429 cpu_info_str = g_string_new("");
2430 os_info_str = g_string_new("");
2431 get_cpu_info(cpu_info_str);
2432 get_os_version_info(os_info_str);
2434 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2435 successful = pcapng_write_session_header_block(ld->pdh,
2436 (const char *)capture_opts->capture_comment, /* Comment */
2437 cpu_info_str->str, /* HW */
2438 os_info_str->str, /* OS */
2440 -1, /* section_length */
2445 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2446 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2447 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2448 if (pcap_src->from_cap_pipe) {
2449 pcap_src->snaplen = pcap_src->cap_pipe_hdr.snaplen;
2451 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
2453 successful = pcapng_write_interface_description_block(global_ld.pdh,
2454 NULL, /* OPT_COMMENT 1 */
2455 interface_opts.name, /* IDB_NAME 2 */
2456 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2457 interface_opts.cfilter, /* IDB_FILTER 11 */
2458 os_info_str->str, /* IDB_OS 12 */
2461 &(global_ld.bytes_written),
2462 0, /* IDB_IF_SPEED 8 */
2463 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2467 g_string_free(os_info_str, TRUE);
2470 pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
2471 if (pcap_src->from_cap_pipe) {
2472 pcap_src->snaplen = pcap_src->cap_pipe_hdr.snaplen;
2474 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
2476 successful = libpcap_write_file_header(ld->pdh, pcap_src->linktype, pcap_src->snaplen,
2477 pcap_src->ts_nsec, &ld->bytes_written, &err);
2485 if (ld->pdh == NULL) {
2486 /* We couldn't set up to write to the capture file. */
2487 /* XXX - use cf_open_error_message from tshark instead? */
2492 g_snprintf(errmsg, errmsg_len,
2493 "The file to which the capture would be"
2494 " saved (\"%s\") could not be opened: Error %d.",
2495 capture_opts->save_file, err);
2497 g_snprintf(errmsg, errmsg_len,
2498 "The file to which the capture would be"
2499 " saved (\"%s\") could not be opened: %s.",
2500 capture_opts->save_file, g_strerror(err));
2512 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2516 capture_src *pcap_src;
2517 guint64 end_time = create_timestamp();
2519 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2521 if (capture_opts->multi_files_on) {
2522 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2524 if (capture_opts->use_pcapng) {
2525 for (i = 0; i < global_ld.pcaps->len; i++) {
2526 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
2527 if (!pcap_src->from_cap_pipe) {
2528 guint64 isb_ifrecv, isb_ifdrop;
2529 struct pcap_stat stats;
2531 if (pcap_stats(pcap_src->pcap_h, &stats) >= 0) {
2532 isb_ifrecv = pcap_src->received;
2533 isb_ifdrop = stats.ps_drop + pcap_src->dropped + pcap_src->flushed;
2535 isb_ifrecv = G_MAXUINT64;
2536 isb_ifdrop = G_MAXUINT64;
2538 pcapng_write_interface_statistics_block(ld->pdh,
2541 "Counters provided by dumpcap",
2550 if (fclose(ld->pdh) == EOF) {
2551 if (err_close != NULL) {
2561 /* dispatch incoming packets (pcap or capture pipe)
2563 * Waits for incoming packets to be available, and calls pcap_dispatch()
2564 * to cause them to be processed.
2566 * Returns the number of packets which were processed.
2568 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2569 * packet-batching behaviour does not cause packets to get held back
2573 capture_loop_dispatch(loop_data *ld,
2574 char *errmsg, int errmsg_len, capture_src *pcap_src)
2577 gint packet_count_before;
2578 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2583 packet_count_before = ld->packet_count;
2584 if (pcap_src->from_cap_pipe) {
2585 /* dispatch from capture pipe */
2586 #ifdef LOG_CAPTURE_VERBOSE
2587 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2590 sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
2592 if (sel_ret < 0 && errno != EINTR) {
2593 g_snprintf(errmsg, errmsg_len,
2594 "Unexpected error from select: %s", g_strerror(errno));
2595 report_capture_error(errmsg, please_report);
2600 * "select()" says we can read from the pipe without blocking
2603 inpkts = cap_pipe_dispatch(ld, pcap_src, pcap_data, errmsg, errmsg_len);
2613 /* dispatch from pcap */
2614 #ifdef MUST_DO_SELECT
2616 * If we have "pcap_get_selectable_fd()", we use it to get the
2617 * descriptor on which to select; if that's -1, it means there
2618 * is no descriptor on which you can do a "select()" (perhaps
2619 * because you're capturing on a special device, and that device's
2620 * driver unfortunately doesn't support "select()", in which case
2621 * we don't do the select - which means it might not be possible
2622 * to stop a capture until a packet arrives. If that's unacceptable,
2623 * plead with whoever supplies the software for that device to add
2624 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2625 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2626 * later, so it can use pcap_breakloop().
2628 #ifdef LOG_CAPTURE_VERBOSE
2629 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2631 if (pcap_src->pcap_fd != -1) {
2632 sel_ret = cap_pipe_select(pcap_src->pcap_fd);
2635 * "select()" says we can read from it without blocking; go for
2638 * We don't have pcap_breakloop(), so we only process one packet
2639 * per pcap_dispatch() call, to allow a signal to stop the
2640 * processing immediately, rather than processing all packets
2641 * in a batch before quitting.
2644 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
2646 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
2650 /* Error, rather than pcap_breakloop(). */
2651 pcap_src->pcap_err = TRUE;
2653 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2656 if (sel_ret < 0 && errno != EINTR) {
2657 g_snprintf(errmsg, errmsg_len,
2658 "Unexpected error from select: %s", g_strerror(errno));
2659 report_capture_error(errmsg, please_report);
2665 #endif /* MUST_DO_SELECT */
2667 /* dispatch from pcap without select */
2669 #ifdef LOG_CAPTURE_VERBOSE
2670 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2674 * On Windows, we don't support asynchronously telling a process to
2675 * stop capturing; instead, we check for an indication on a pipe
2676 * after processing packets. We therefore process only one packet
2677 * at a time, so that we can check the pipe after every packet.
2680 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
2682 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
2686 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
2688 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_src);
2693 /* Error, rather than pcap_breakloop(). */
2694 pcap_src->pcap_err = TRUE;
2696 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2698 #else /* pcap_next_ex */
2699 #ifdef LOG_CAPTURE_VERBOSE
2700 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2702 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2705 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2706 * see https://wiki.wireshark.org/CaptureSetup/WinPcapRemote
2707 * This should be fixed in the WinPcap 4.0 alpha release.
2709 * For reference, an example remote interface:
2710 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2713 /* emulate dispatch from pcap */
2716 struct pcap_pkthdr *pkt_header;
2721 (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
2723 capture_loop_queue_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
2725 capture_loop_write_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
2730 pcap_src->pcap_err = TRUE;
2734 #endif /* pcap_next_ex */
2738 #ifdef LOG_CAPTURE_VERBOSE
2739 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2742 return ld->packet_count - packet_count_before;
2746 /* Isolate the Universally Unique Identifier from the interface. Basically, we
2747 * want to grab only the characters between the '{' and '}' delimiters.
2749 * Returns a GString that must be freed with g_string_free(). */
2751 isolate_uuid(const char *iface)
2756 ptr = strchr(iface, '{');
2758 return g_string_new(iface);
2759 gstr = g_string_new(ptr + 1);
2761 ptr = strchr(gstr->str, '}');
2765 gstr = g_string_truncate(gstr, ptr - gstr->str);
2770 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2771 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2773 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2774 char *errmsg, int errmsg_len)
2777 gchar *capfile_name;
2778 gchar *prefix, *suffix;
2779 gboolean is_tempfile;
2781 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2782 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
2784 if (capture_opts->save_file != NULL) {
2785 /* We return to the caller while the capture is in progress.
2786 * Therefore we need to take a copy of save_file in
2787 * case the caller destroys it after we return.
2789 capfile_name = g_strdup(capture_opts->save_file);
2791 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2792 if (capture_opts->multi_files_on) {
2793 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2794 g_snprintf(errmsg, errmsg_len,
2795 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2796 g_free(capfile_name);
2799 if (strcmp(capfile_name, "-") == 0) {
2800 /* write to stdout */
2803 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2804 _setmode(1, O_BINARY);
2807 } /* if (...output_to_pipe ... */
2810 if (capture_opts->multi_files_on) {
2811 /* ringbuffer is enabled */
2812 *save_file_fd = ringbuf_init(capfile_name,
2813 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
2814 capture_opts->group_read_access);
2816 /* we need the ringbuf name */
2817 if (*save_file_fd != -1) {
2818 g_free(capfile_name);
2819 capfile_name = g_strdup(ringbuf_current_filename());
2822 /* Try to open/create the specified file for use as a capture buffer. */
2823 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2824 (capture_opts->group_read_access) ? 0640 : 0600);
2827 is_tempfile = FALSE;
2829 /* Choose a random name for the temporary capture buffer */
2830 if (global_capture_opts.ifaces->len > 1) {
2831 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
2832 if (capture_opts->use_pcapng) {
2839 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
2841 /* use the generic portion of the interface guid to form the basis of the filename */
2842 if (strncmp("NPF_{", basename, 5)==0)
2844 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
2846 iface = isolate_uuid(basename);
2848 basename = g_strdup(iface->str);
2849 g_string_free(iface, TRUE);
2852 /* generate the temp file name prefix and suffix */
2853 if (capture_opts->use_pcapng) {
2854 prefix = g_strconcat("wireshark_", basename, NULL);
2857 prefix = g_strconcat("wireshark_", basename, NULL);
2862 *save_file_fd = create_tempfile(&tmpname, prefix, suffix);
2864 capfile_name = g_strdup(tmpname);
2868 /* did we fail to open the output file? */
2869 if (*save_file_fd == -1) {
2871 g_snprintf(errmsg, errmsg_len,
2872 "The temporary file to which the capture would be saved (\"%s\") "
2873 "could not be opened: %s.", capfile_name, g_strerror(errno));
2875 if (capture_opts->multi_files_on) {
2876 ringbuf_error_cleanup();
2879 g_snprintf(errmsg, errmsg_len,
2880 "The file to which the capture would be saved (\"%s\") "
2881 "could not be opened: %s.", capfile_name,
2884 g_free(capfile_name);
2888 if (capture_opts->save_file != NULL) {
2889 g_free(capture_opts->save_file);
2891 capture_opts->save_file = capfile_name;
2892 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2893 "g_free(capfile_name)". */
2899 /* Do the work of handling either the file size or file duration capture
2900 conditions being reached, and switching files or stopping. */
2902 do_file_switch_or_stop(capture_options *capture_opts,
2903 condition *cnd_autostop_files,
2904 condition *cnd_autostop_size,
2905 condition *cnd_file_duration)
2908 capture_src *pcap_src;
2909 interface_options interface_opts;
2910 gboolean successful;
2912 if (capture_opts->multi_files_on) {
2913 if (cnd_autostop_files != NULL &&
2914 cnd_eval(cnd_autostop_files, (guint64)++global_ld.autostop_files)) {
2915 /* no files left: stop here */
2916 global_ld.go = FALSE;
2920 /* Switch to the next ringbuffer file */
2921 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2922 &global_ld.save_file_fd, &global_ld.err)) {
2924 /* File switch succeeded: reset the conditions */
2925 global_ld.bytes_written = 0;
2926 if (capture_opts->use_pcapng) {
2928 GString *cpu_info_str;
2929 GString *os_info_str;
2931 cpu_info_str = g_string_new("");
2932 os_info_str = g_string_new("");
2933 get_cpu_info(cpu_info_str);
2934 get_os_version_info(os_info_str);
2936 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2937 successful = pcapng_write_session_header_block(global_ld.pdh,
2938 (const char *)capture_opts->capture_comment, /* Comment */
2939 cpu_info_str->str, /* HW */
2940 os_info_str->str, /* OS */
2942 -1, /* section_length */
2943 &(global_ld.bytes_written),
2947 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2948 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2949 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
2950 successful = pcapng_write_interface_description_block(global_ld.pdh,
2951 NULL, /* OPT_COMMENT 1 */
2952 interface_opts.name, /* IDB_NAME 2 */
2953 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2954 interface_opts.cfilter, /* IDB_FILTER 11 */
2955 os_info_str->str, /* IDB_OS 12 */
2958 &(global_ld.bytes_written),
2959 0, /* IDB_IF_SPEED 8 */
2960 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2964 g_string_free(os_info_str, TRUE);
2967 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
2968 successful = libpcap_write_file_header(global_ld.pdh, pcap_src->linktype, pcap_src->snaplen,
2969 pcap_src->ts_nsec, &global_ld.bytes_written, &global_ld.err);
2972 fclose(global_ld.pdh);
2973 global_ld.pdh = NULL;
2974 global_ld.go = FALSE;
2977 if (cnd_autostop_size)
2978 cnd_reset(cnd_autostop_size);
2979 if (cnd_file_duration)
2980 cnd_reset(cnd_file_duration);
2981 fflush(global_ld.pdh);
2983 report_packet_count(global_ld.inpkts_to_sync_pipe);
2984 global_ld.inpkts_to_sync_pipe = 0;
2985 report_new_capture_file(capture_opts->save_file);
2987 /* File switch failed: stop here */
2988 global_ld.go = FALSE;
2992 /* single file, stop now */
2993 global_ld.go = FALSE;
3000 pcap_read_handler(void* arg)
3002 capture_src *pcap_src;
3003 char errmsg[MSG_MAX_LENGTH+1];
3005 pcap_src = (capture_src *)arg;
3007 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3008 pcap_src->interface_id);
3010 while (global_ld.go) {
3011 /* dispatch incoming packets */
3012 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_src);
3014 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3015 pcap_src->interface_id);
3016 g_thread_exit(NULL);
3020 /* Do the low-level work of a capture.
3021 Returns TRUE if it succeeds, FALSE otherwise. */
3023 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3026 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3028 struct timeval upd_time, cur_time;
3032 condition *cnd_file_duration = NULL;
3033 condition *cnd_autostop_files = NULL;
3034 condition *cnd_autostop_size = NULL;
3035 condition *cnd_autostop_duration = NULL;
3038 gboolean cfilter_error = FALSE;
3039 char errmsg[MSG_MAX_LENGTH+1];
3040 char secondary_errmsg[MSG_MAX_LENGTH+1];
3041 capture_src *pcap_src;
3042 interface_options interface_opts;
3043 guint i, error_index = 0;
3046 *secondary_errmsg = '\0';
3048 /* init the loop data */
3049 global_ld.go = TRUE;
3050 global_ld.packet_count = 0;
3052 global_ld.report_packet_count = FALSE;
3054 if (capture_opts->has_autostop_packets)
3055 global_ld.packet_max = capture_opts->autostop_packets;
3057 global_ld.packet_max = 0; /* no limit */
3058 global_ld.inpkts_to_sync_pipe = 0;
3059 global_ld.err = 0; /* no error seen yet */
3060 global_ld.pdh = NULL;
3061 global_ld.autostop_files = 0;
3062 global_ld.save_file_fd = -1;
3064 /* We haven't yet gotten the capture statistics. */
3065 *stats_known = FALSE;
3067 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3068 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3070 /* open the "input file" from network interface or capture pipe */
3071 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3072 secondary_errmsg, sizeof(secondary_errmsg))) {
3075 for (i = 0; i < capture_opts->ifaces->len; i++) {
3076 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3077 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3078 /* init the input filter from the network interface (capture pipe will do nothing) */
3080 * When remote capturing WinPCap crashes when the capture filter
3081 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3084 switch (capture_loop_init_filter(pcap_src->pcap_h, pcap_src->from_cap_pipe,
3085 interface_opts.name,
3086 interface_opts.cfilter?interface_opts.cfilter:"")) {
3088 case INITFILTER_NO_ERROR:
3091 case INITFILTER_BAD_FILTER:
3092 cfilter_error = TRUE;
3094 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
3097 case INITFILTER_OTHER_ERROR:
3098 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3099 pcap_geterr(pcap_src->pcap_h));
3100 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3105 /* If we're supposed to write to a capture file, open it for output
3106 (temporary/specified name/ringbuffer) */
3107 if (capture_opts->saving_to_file) {
3108 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3109 errmsg, sizeof(errmsg))) {
3113 /* set up to write to the already-opened capture output file/files */
3114 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3119 /* XXX - capture SIGTERM and close the capture, in case we're on a
3120 Linux 2.0[.x] system and you have to explicitly close the capture
3121 stream in order to turn promiscuous mode off? We need to do that
3122 in other places as well - and I don't think that works all the
3123 time in any case, due to libpcap bugs. */
3125 /* Well, we should be able to start capturing.
3127 Sync out the capture file, so the header makes it to the file system,
3128 and send a "capture started successfully and capture file created"
3129 message to our parent so that they'll open the capture file and
3130 update its windows to indicate that we have a live capture in
3132 fflush(global_ld.pdh);
3133 report_new_capture_file(capture_opts->save_file);
3136 /* initialize capture stop (and alike) conditions */
3137 init_capture_stop_conditions();
3138 /* create stop conditions */
3139 if (capture_opts->has_autostop_filesize) {
3140 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3141 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3144 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3146 if (capture_opts->has_autostop_duration)
3147 cnd_autostop_duration =
3148 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3150 if (capture_opts->multi_files_on) {
3151 if (capture_opts->has_file_duration)
3153 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3155 if (capture_opts->has_autostop_files)
3156 cnd_autostop_files =
3157 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_files);
3160 /* init the time values */
3162 upd_time = GetTickCount();
3164 gettimeofday(&upd_time, NULL);
3166 start_time = create_timestamp();
3167 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3168 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3170 /* WOW, everything is prepared! */
3171 /* please fasten your seat belts, we will enter now the actual capture loop */
3173 pcap_queue = g_async_queue_new();
3174 pcap_queue_bytes = 0;
3175 pcap_queue_packets = 0;
3176 for (i = 0; i < global_ld.pcaps->len; i++) {
3177 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3178 #if GLIB_CHECK_VERSION(2,31,0)
3179 /* XXX - Add an interface name here? */
3180 pcap_src->tid = g_thread_new("Capture read", pcap_read_handler, pcap_src);
3182 pcap_src->tid = g_thread_create(pcap_read_handler, pcap_src, TRUE, NULL);
3186 while (global_ld.go) {
3187 /* dispatch incoming packets */
3189 pcap_queue_element *queue_element;
3190 #if GLIB_CHECK_VERSION(2,31,18)
3192 g_async_queue_lock(pcap_queue);
3193 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3195 GTimeVal write_thread_time;
3197 g_get_current_time(&write_thread_time);
3198 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3199 g_async_queue_lock(pcap_queue);
3200 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3202 if (queue_element) {
3203 pcap_queue_bytes -= queue_element->phdr.caplen;
3204 pcap_queue_packets -= 1;
3206 g_async_queue_unlock(pcap_queue);
3207 if (queue_element) {
3208 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3209 "Dequeued a packet of length %d captured on interface %d.",
3210 queue_element->phdr.caplen, queue_element->pcap_src->interface_id);
3212 capture_loop_write_packet_cb((u_char *) queue_element->pcap_src,
3213 &queue_element->phdr,
3215 g_free(queue_element->pd);
3216 g_free(queue_element);
3222 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3223 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3224 sizeof(errmsg), pcap_src);
3227 /* Were we asked to print packet counts by the SIGINFO handler? */
3228 if (global_ld.report_packet_count) {
3229 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3230 plurality(global_ld.packet_count, "", "s"));
3231 global_ld.report_packet_count = FALSE;
3236 /* any news from our parent (signal pipe)? -> just stop the capture */
3237 if (!signal_pipe_check_running()) {
3238 global_ld.go = FALSE;
3243 global_ld.inpkts_to_sync_pipe += inpkts;
3245 /* check capture size condition */
3246 if (cnd_autostop_size != NULL &&
3247 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3248 /* Capture size limit reached, do we have another file? */
3249 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3250 cnd_autostop_size, cnd_file_duration))
3252 } /* cnd_autostop_size */
3253 if (capture_opts->output_to_pipe) {
3254 fflush(global_ld.pdh);
3258 /* Only update once every 500ms so as not to overload slow displays.
3259 * This also prevents too much context-switching between the dumpcap
3260 * and wireshark processes.
3262 #define DUMPCAP_UPD_TIME 500
3265 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3266 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3268 gettimeofday(&cur_time, NULL);
3269 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3270 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3273 upd_time = cur_time;
3276 if (pcap_stats(pch, stats) >= 0) {
3277 *stats_known = TRUE;
3280 /* Let the parent process know. */
3281 if (global_ld.inpkts_to_sync_pipe) {
3283 fflush(global_ld.pdh);
3285 /* Send our parent a message saying we've written out
3286 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3288 report_packet_count(global_ld.inpkts_to_sync_pipe);
3290 global_ld.inpkts_to_sync_pipe = 0;
3293 /* check capture duration condition */
3294 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3295 /* The maximum capture time has elapsed; stop the capture. */
3296 global_ld.go = FALSE;
3300 /* check capture file duration condition */
3301 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3302 /* duration limit reached, do we have another file? */
3303 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3304 cnd_autostop_size, cnd_file_duration))
3306 } /* cnd_file_duration */
3310 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3312 pcap_queue_element *queue_element;
3314 for (i = 0; i < global_ld.pcaps->len; i++) {
3315 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3316 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3317 pcap_src->interface_id);
3318 g_thread_join(pcap_src->tid);
3319 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3320 pcap_src->interface_id);
3323 g_async_queue_lock(pcap_queue);
3324 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3325 if (queue_element) {
3326 pcap_queue_bytes -= queue_element->phdr.caplen;
3327 pcap_queue_packets -= 1;
3329 g_async_queue_unlock(pcap_queue);
3330 if (queue_element == NULL) {
3333 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3334 "Dequeued a packet of length %d captured on interface %d.",
3335 queue_element->phdr.caplen, queue_element->pcap_src->interface_id);
3336 capture_loop_write_packet_cb((u_char *)queue_element->pcap_src,
3337 &queue_element->phdr,
3339 g_free(queue_element->pd);
3340 g_free(queue_element);
3341 global_ld.inpkts_to_sync_pipe += 1;
3342 if (capture_opts->output_to_pipe) {
3343 fflush(global_ld.pdh);
3349 /* delete stop conditions */
3350 if (cnd_file_duration != NULL)
3351 cnd_delete(cnd_file_duration);
3352 if (cnd_autostop_files != NULL)
3353 cnd_delete(cnd_autostop_files);
3354 if (cnd_autostop_size != NULL)
3355 cnd_delete(cnd_autostop_size);
3356 if (cnd_autostop_duration != NULL)
3357 cnd_delete(cnd_autostop_duration);
3359 /* did we have a pcap (input) error? */
3360 for (i = 0; i < capture_opts->ifaces->len; i++) {
3361 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3362 if (pcap_src->pcap_err) {
3363 /* On Linux, if an interface goes down while you're capturing on it,
3364 you'll get a "recvfrom: Network is down" or
3365 "The interface went down" error (ENETDOWN).
3366 (At least you will if g_strerror() doesn't show a local translation
3369 On FreeBSD and OS X, if a network adapter disappears while
3370 you're capturing on it, you'll get a "read: Device not configured"
3371 error (ENXIO). (See previous parenthetical note.)
3373 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3375 These should *not* be reported to the Wireshark developers. */
3378 cap_err_str = pcap_geterr(pcap_src->pcap_h);
3379 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3380 strcmp(cap_err_str, "The interface went down") == 0 ||
3381 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3382 strcmp(cap_err_str, "read: I/O error") == 0 ||
3383 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3384 report_capture_error("The network adapter on which the capture was being done "
3385 "is no longer running; the capture has stopped.",
3388 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3390 report_capture_error(errmsg, please_report);
3393 } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
3394 report_capture_error(errmsg, "");
3398 /* did we have an output error while capturing? */
3399 if (global_ld.err == 0) {
3402 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3403 global_ld.err, FALSE);
3404 report_capture_error(errmsg, please_report);
3408 if (capture_opts->saving_to_file) {
3409 /* close the output file */
3410 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3414 /* there might be packets not yet notified to the parent */
3415 /* (do this after closing the file, so all packets are already flushed) */
3416 if (global_ld.inpkts_to_sync_pipe) {
3418 report_packet_count(global_ld.inpkts_to_sync_pipe);
3419 global_ld.inpkts_to_sync_pipe = 0;
3422 /* If we've displayed a message about a write error, there's no point
3423 in displaying another message about an error on close. */
3424 if (!close_ok && write_ok) {
3425 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3427 report_capture_error(errmsg, "");
3431 * XXX We exhibit different behaviour between normal mode and sync mode
3432 * when the pipe is stdin and not already at EOF. If we're a child, the
3433 * parent's stdin isn't closed, so if the user starts another capture,
3434 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3435 * will say "Unrecognized libpcap format". On the other hand, in normal
3436 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3439 report_capture_count(TRUE);
3441 /* get packet drop statistics from pcap */
3442 for (i = 0; i < capture_opts->ifaces->len; i++) {
3444 guint32 pcap_dropped = 0;
3446 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3447 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3448 received = pcap_src->received;
3449 if (pcap_src->pcap_h != NULL) {
3450 g_assert(!pcap_src->from_cap_pipe);
3451 /* Get the capture statistics, so we know how many packets were dropped. */
3453 * Older versions of libpcap didn't set ps_ifdrop on some
3454 * platforms; initialize it to 0 to handle that.
3456 stats->ps_ifdrop = 0;
3457 if (pcap_stats(pcap_src->pcap_h, stats) >= 0) {
3458 *stats_known = TRUE;
3459 /* Let the parent process know. */
3460 pcap_dropped += stats->ps_drop;
3462 g_snprintf(errmsg, sizeof(errmsg),
3463 "Can't get packet-drop statistics: %s",
3464 pcap_geterr(pcap_src->pcap_h));
3465 report_capture_error(errmsg, please_report);
3468 report_packet_drops(received, pcap_dropped, pcap_src->dropped, pcap_src->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
3471 /* close the input file (pcap or capture pipe) */
3472 capture_loop_close_input(&global_ld);
3474 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
3476 /* ok, if the write and the close were successful. */
3477 return write_ok && close_ok;
3480 if (capture_opts->multi_files_on) {
3481 /* cleanup ringbuffer */
3482 ringbuf_error_cleanup();
3484 /* We can't use the save file, and we have no FILE * for the stream
3485 to close in order to close it, so close the FD directly. */
3486 if (global_ld.save_file_fd != -1) {
3487 ws_close(global_ld.save_file_fd);
3490 /* We couldn't even start the capture, so get rid of the capture
3492 if (capture_opts->save_file != NULL) {
3493 ws_unlink(capture_opts->save_file);
3494 g_free(capture_opts->save_file);
3497 capture_opts->save_file = NULL;
3499 report_cfilter_error(capture_opts, error_index, errmsg);
3501 report_capture_error(errmsg, secondary_errmsg);
3503 /* close the input file (pcap or cap_pipe) */
3504 capture_loop_close_input(&global_ld);
3506 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3513 capture_loop_stop(void)
3515 #ifdef HAVE_PCAP_BREAKLOOP
3517 capture_src *pcap_src;
3519 for (i = 0; i < global_ld.pcaps->len; i++) {
3520 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3521 if (pcap_src->pcap_h != NULL)
3522 pcap_breakloop(pcap_src->pcap_h);
3525 global_ld.go = FALSE;
3530 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3531 int err, gboolean is_close)
3536 g_snprintf(errmsg, errmsglen,
3537 "Not all the packets could be written to the file"
3538 " to which the capture was being saved\n"
3539 "(\"%s\") because there is no space left on the file system\n"
3540 "on which that file resides.",
3546 g_snprintf(errmsg, errmsglen,
3547 "Not all the packets could be written to the file"
3548 " to which the capture was being saved\n"
3549 "(\"%s\") because you are too close to, or over,"
3550 " your disk quota\n"
3551 "on the file system on which that file resides.",
3558 g_snprintf(errmsg, errmsglen,
3559 "The file to which the capture was being saved\n"
3560 "(\"%s\") could not be closed: %s.",
3561 fname, g_strerror(err));
3563 g_snprintf(errmsg, errmsglen,
3564 "An error occurred while writing to the file"
3565 " to which the capture was being saved\n"
3567 fname, g_strerror(err));
3574 /* one packet was captured, process it */
3576 capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
3579 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
3581 guint ts_mul = pcap_src->ts_nsec ? 1000000000 : 1000000;
3583 /* We may be called multiple times from pcap_dispatch(); if we've set
3584 the "stop capturing" flag, ignore this packet, as we're not
3585 supposed to be saving any more packets. */
3586 if (!global_ld.go) {
3587 pcap_src->flushed++;
3591 if (global_ld.pdh) {
3592 gboolean successful;
3594 /* We're supposed to write the packet to a file; do so.
3595 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3596 "ld->err" to the error. */
3597 if (global_capture_opts.use_pcapng) {
3598 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
3600 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3601 phdr->caplen, phdr->len,
3602 pcap_src->interface_id,
3605 &global_ld.bytes_written, &err);
3607 successful = libpcap_write_packet(global_ld.pdh,
3608 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3609 phdr->caplen, phdr->len,
3611 &global_ld.bytes_written, &err);
3614 global_ld.go = FALSE;
3615 global_ld.err = err;
3616 pcap_src->dropped++;
3618 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3619 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3620 "Wrote a packet of length %d captured on interface %u.",
3621 phdr->caplen, pcap_src->interface_id);
3623 global_ld.packet_count++;
3624 pcap_src->received++;
3625 /* if the user told us to stop after x packets, do we already have enough? */
3626 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
3627 global_ld.go = FALSE;
3633 /* one packet was captured, queue it */
3635 capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
3638 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
3639 pcap_queue_element *queue_element;
3640 gboolean limit_reached;
3642 /* We may be called multiple times from pcap_dispatch(); if we've set
3643 the "stop capturing" flag, ignore this packet, as we're not
3644 supposed to be saving any more packets. */
3645 if (!global_ld.go) {
3646 pcap_src->flushed++;
3650 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
3651 if (queue_element == NULL) {
3652 pcap_src->dropped++;
3655 queue_element->pcap_src = pcap_src;
3656 queue_element->phdr = *phdr;
3657 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
3658 if (queue_element->pd == NULL) {
3659 pcap_src->dropped++;
3660 g_free(queue_element);
3663 memcpy(queue_element->pd, pd, phdr->caplen);
3664 g_async_queue_lock(pcap_queue);
3665 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
3666 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
3667 limit_reached = FALSE;
3668 g_async_queue_push_unlocked(pcap_queue, queue_element);
3669 pcap_queue_bytes += phdr->caplen;
3670 pcap_queue_packets += 1;
3672 limit_reached = TRUE;
3674 g_async_queue_unlock(pcap_queue);
3675 if (limit_reached) {
3676 pcap_src->dropped++;
3677 g_free(queue_element->pd);
3678 g_free(queue_element);
3679 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3680 "Dropped a packet of length %d captured on interface %u.",
3681 phdr->caplen, pcap_src->interface_id);
3683 pcap_src->received++;
3684 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3685 "Queued a packet of length %d captured on interface %u.",
3686 phdr->caplen, pcap_src->interface_id);
3688 /* I don't want to hold the mutex over the debug output. So the
3689 output may be wrong */
3690 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3691 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
3692 pcap_queue_bytes, pcap_queue_packets);
3696 set_80211_channel(const char *iface, const char *opt)
3700 guint32 center_freq1 = 0;
3701 guint32 center_freq2 = 0;
3704 gchar **options = NULL;
3706 options = g_strsplit_set(opt, ",", 4);
3707 for (args = 0; options[args]; args++);
3710 freq = get_nonzero_guint32(options[0], "802.11 channel frequency");
3712 if (args >= 1 && options[1]) {
3713 type = ws80211_str_to_chan_type(options[1]);
3715 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
3721 if (args >= 2 && options[2])
3722 center_freq1 = get_nonzero_guint32(options[2], "VHT center frequency");
3724 if (args >= 3 && options[3])
3725 center_freq2 = get_nonzero_guint32(options[3], "VHT center frequency 2");
3727 ret = ws80211_init();
3729 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
3733 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
3736 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
3742 pipe_write_block(2, SP_SUCCESS, NULL);
3745 g_strfreev(options);
3750 get_dumpcap_compiled_info(GString *str)
3752 /* Capture libraries */
3753 g_string_append(str, ", ");
3754 get_compiled_caplibs_version(str);
3758 get_dumpcap_runtime_info(GString *str)
3760 /* Capture libraries */
3761 g_string_append(str, ", ");
3762 get_runtime_caplibs_version(str);
3765 /* And now our feature presentation... [ fade to music ] */
3767 main(int argc, char *argv[])
3769 GString *comp_info_str;
3770 GString *runtime_info_str;
3772 static const struct option long_options[] = {
3773 {"help", no_argument, NULL, 'h'},
3774 {"version", no_argument, NULL, 'v'},
3775 LONGOPT_CAPTURE_COMMON
3779 gboolean arg_error = FALSE;
3784 struct sigaction action, oldaction;
3787 gboolean start_capture = TRUE;
3788 gboolean stats_known;
3789 struct pcap_stat stats;
3790 GLogLevelFlags log_flags;
3791 gboolean list_interfaces = FALSE;
3792 gboolean list_link_layer_types = FALSE;
3793 #ifdef HAVE_BPF_IMAGE
3794 gboolean print_bpf_code = FALSE;
3796 gboolean set_chan = FALSE;
3797 gchar *set_chan_arg = NULL;
3798 gboolean machine_readable = FALSE;
3799 gboolean print_statistics = FALSE;
3800 int status, run_once_args = 0;
3803 #if defined(__APPLE__) && defined(__LP64__)
3804 struct utsname osinfo;
3808 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
3810 /* Get the compile-time version information string */
3811 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
3813 /* Get the run-time version information string */
3814 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
3816 /* Add it to the information to be reported on a crash. */
3817 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
3822 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
3823 g_string_free(comp_info_str, TRUE);
3824 g_string_free(runtime_info_str, TRUE);
3827 arg_list_utf_16to8(argc, argv);
3828 create_app_running_mutex();
3831 * Initialize our DLL search path. MUST be called before LoadLibrary
3834 ws_init_dll_search_path();
3837 #ifdef HAVE_BPF_IMAGE
3838 #define OPTSTRING_d "d"
3840 #define OPTSTRING_d ""
3843 #ifdef HAVE_PCAP_REMOTE
3844 #define OPTSTRING_r "r"
3845 #define OPTSTRING_u "u"
3847 #define OPTSTRING_r ""
3848 #define OPTSTRING_u ""
3851 #ifdef HAVE_PCAP_SETSAMPLING
3852 #define OPTSTRING_m "m:"
3854 #define OPTSTRING_m ""
3857 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
3859 #ifdef DEBUG_CHILD_DUMPCAP
3860 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3861 fprintf (stderr, "Unable to open debug log file .\n");
3866 #if defined(__APPLE__) && defined(__LP64__)
3868 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
3869 * a bug workaround - timeouts less than 1 second don't work with libpcap
3870 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3871 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
3872 * The problem is extremely unlikely to be reintroduced in a future
3875 if (uname(&osinfo) == 0) {
3877 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
3878 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3879 * number of 10.0.0, not 10.1.0 - go figure).
3881 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
3882 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
3883 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
3884 need_timeout_workaround = TRUE;
3889 * Determine if dumpcap is being requested to run in a special
3890 * capture_child mode by going thru the command line args to see if
3891 * a -Z is present. (-Z is a hidden option).
3893 * The primary result of running in capture_child mode is that
3894 * all messages sent out on stderr are in a special type/len/string
3895 * format to allow message processing by type. These messages include
3896 * error messages if dumpcap fails to start the operation it was
3897 * requested to do, as well as various "status" messages which are sent
3898 * when an actual capture is in progress, and a "success" message sent
3899 * if dumpcap was requested to perform an operation other than a
3902 * Capture_child mode would normally be requested by a parent process
3903 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3904 * to which dumpcap stderr has been redirected. It might also have
3905 * another pipe to obtain dumpcap stdout output; for operations other
3906 * than a capture, that information is formatted specially for easier
3907 * parsing by the parent process.
3909 * Capture_child mode needs to be determined immediately upon
3910 * startup so that any messages generated by dumpcap in this mode
3911 * (eg: during initialization) will be formatted properly.
3914 for (i=1; i<argc; i++) {
3915 if (strcmp("-Z", argv[i]) == 0) {
3916 capture_child = TRUE;
3917 machine_readable = TRUE; /* request machine-readable output */
3919 /* set output pipe to binary mode, to avoid ugly text conversions */
3920 _setmode(2, O_BINARY);
3925 /* The default_log_handler will use stdout, which makes trouble in */
3926 /* capture child mode, as it uses stdout for its sync_pipe. */
3927 /* So: the filtering is done in the console_log_handler and not here.*/
3928 /* We set the log handlers right up front to make sure that any log */
3929 /* messages when running as child will be sent back to the parent */
3930 /* with the correct format. */
3935 G_LOG_LEVEL_CRITICAL|
3936 G_LOG_LEVEL_WARNING|
3937 G_LOG_LEVEL_MESSAGE|
3941 G_LOG_FLAG_RECURSION);
3943 g_log_set_handler(NULL,
3945 console_log_handler, NULL /* user_data */);
3946 g_log_set_handler(LOG_DOMAIN_MAIN,
3948 console_log_handler, NULL /* user_data */);
3949 g_log_set_handler(LOG_DOMAIN_CAPTURE,
3951 console_log_handler, NULL /* user_data */);
3952 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3954 console_log_handler, NULL /* user_data */);
3956 /* Initialize the pcaps list */
3957 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(capture_src *));
3959 #if !GLIB_CHECK_VERSION(2,31,0)
3960 /* Initialize the thread system */
3961 g_thread_init(NULL);
3965 /* Load wpcap if possible. Do this before collecting the run-time version information */
3968 /* ... and also load the packet.dll from wpcap */
3969 /* XXX - currently not required, may change later. */
3970 /*wpcap_packet_load();*/
3972 /* Start windows sockets */
3973 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3975 /* Set handler for Ctrl+C key */
3976 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3978 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3979 and exit. Do the same with SIGPIPE, in case, for example,
3980 we're writing to our standard output and it's a pipe.
3981 Do the same with SIGHUP if it's not being ignored (if we're
3982 being run under nohup, it might be ignored, in which case we
3983 should leave it ignored).
3985 XXX - apparently, Coverity complained that part of action
3986 wasn't initialized. Perhaps it's running on Linux, where
3987 struct sigaction has an ignored "sa_restorer" element and
3988 where "sa_handler" and "sa_sigaction" might not be two
3989 members of a union. */
3990 memset(&action, 0, sizeof(action));
3991 action.sa_handler = capture_cleanup_handler;
3993 * Arrange that system calls not get restarted, because when
3994 * our signal handler returns we don't want to restart
3995 * a call that was waiting for packets to arrive.
3997 action.sa_flags = 0;
3998 sigemptyset(&action.sa_mask);
3999 sigaction(SIGTERM, &action, NULL);
4000 sigaction(SIGINT, &action, NULL);
4001 sigaction(SIGPIPE, &action, NULL);
4002 sigaction(SIGHUP, NULL, &oldaction);
4003 if (oldaction.sa_handler == SIG_DFL)
4004 sigaction(SIGHUP, &action, NULL);
4007 /* Catch SIGINFO and, if we get it and we're capturing in
4008 quiet mode, report the number of packets we've captured. */
4009 action.sa_handler = report_counts_siginfo;
4010 action.sa_flags = SA_RESTART;
4011 sigemptyset(&action.sa_mask);
4012 sigaction(SIGINFO, &action, NULL);
4013 #endif /* SIGINFO */
4017 enable_kernel_bpf_jit_compiler();
4020 /* ----------------------------------------------------------------- */
4021 /* Privilege and capability handling */
4023 /* 1. Running not as root or suid root; no special capabilities. */
4026 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4029 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4031 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4032 /* capabilities; Drop all other capabilities; */
4033 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4034 /* else: after pcap_open_live() in capture_loop_open_input() */
4035 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4036 /* (Note: this means that the process, although logged in */
4037 /* as root, does not have various permissions such as the */
4038 /* ability to bypass file access permissions). */
4039 /* XXX: Should we just leave capabilities alone in this case */
4040 /* so that user gets expected effect that root can do */
4043 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4045 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4046 /* else: after pcap_open_live() in capture_loop_open_input() */
4047 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4048 /* pcap_open_live). */
4050 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4052 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4053 /* capabilities; Drop all other capabilities; */
4054 /* Drop suid privileges (euid=ruid); */
4055 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4056 /* else: after pcap_open_live() in capture_loop_open_input() */
4057 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4059 /* XXX: For some Linux versions/distros with capabilities */
4060 /* a 'normal' process with any capabilities cannot be */
4061 /* 'killed' (signaled) from another (same uid) non-privileged */
4063 /* For example: If (non-suid) Wireshark forks a */
4064 /* child suid dumpcap which acts as described here (case 5), */
4065 /* Wireshark will be unable to kill (signal) the child */
4066 /* dumpcap process until the capabilities have been dropped */
4067 /* (after pcap_open_live()). */
4068 /* This behaviour will apparently be changed in the kernel */
4069 /* to allow the kill (signal) in this case. */
4070 /* See the following for details: */
4071 /* https://www.mail-archive.com/ [wrapped] */
4072 /* linux-security-module@vger.kernel.org/msg02913.html */
4074 /* It is therefore conceivable that if dumpcap somehow hangs */
4075 /* in pcap_open_live or before that wireshark will not */
4076 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4077 /* In this case, exiting wireshark will kill the child */
4078 /* dumpcap process. */
4080 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4081 /* capabilities; Using libcap. Note: capset cmd (which see) */
4082 /* used to assign capabilities to file. */
4084 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4085 /* else: after pcap_open_live() in capture_loop_open_input() */
4086 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4088 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4089 /* longer required (similar to capture). */
4091 /* ----------------------------------------------------------------- */
4093 init_process_policies();
4096 /* If 'started with special privileges' (and using libcap) */
4097 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4098 /* Set euid/egid = ruid/rgid to remove suid privileges */
4099 relinquish_privs_except_capture();
4102 /* Set the initial values in the capture options. This might be overwritten
4103 by the command line parameters. */
4104 capture_opts_init(&global_capture_opts);
4105 /* We always save to a file - if no file was specified, we save to a
4107 global_capture_opts.saving_to_file = TRUE;
4108 global_capture_opts.has_ring_num_files = TRUE;
4110 /* Pass on capture_child mode for capture_opts */
4111 global_capture_opts.capture_child = capture_child;
4113 /* Now get our args */
4114 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4116 case 'h': /* Print help and exit */
4117 printf("Dumpcap (Wireshark) %s\n"
4118 "Capture network packets and dump them into a pcapng or pcap file.\n"
4119 "See https://www.wireshark.org for more information.\n",
4120 get_ws_vcs_version_info());
4121 print_usage(stdout);
4124 case 'v': /* Show version and exit */
4125 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4126 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4127 show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4128 g_string_free(comp_info_str, TRUE);
4129 g_string_free(runtime_info_str, TRUE);
4132 /*** capture option specific ***/
4133 case 'a': /* autostop criteria */
4134 case 'b': /* Ringbuffer option */
4135 case 'c': /* Capture x packets */
4136 case 'f': /* capture filter */
4137 case 'g': /* enable group read access on file(s) */
4138 case 'i': /* Use interface x */
4139 case 'n': /* Use pcapng format */
4140 case 'p': /* Don't capture in promiscuous mode */
4141 case 'P': /* Use pcap format */
4142 case 's': /* Set the snapshot (capture) length */
4143 case 'w': /* Write to capture file x */
4144 case 'y': /* Set the pcap data link type */
4145 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4146 #ifdef HAVE_PCAP_REMOTE
4147 case 'u': /* Use UDP for data transfer */
4148 case 'r': /* Capture own RPCAP traffic too */
4149 case 'A': /* Authentication */
4151 #ifdef HAVE_PCAP_SETSAMPLING
4152 case 'm': /* Sampling */
4154 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4155 case 'B': /* Buffer size */
4157 #ifdef HAVE_PCAP_CREATE
4158 case 'I': /* Monitor mode */
4160 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4165 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4167 capture_child = TRUE;
4169 /* set output pipe to binary mode, to avoid ugly text conversions */
4170 _setmode(2, O_BINARY);
4172 * optarg = the control ID, aka the PPID, currently used for the
4175 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4176 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4177 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4178 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4180 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4181 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4182 "Signal pipe: Unable to open %s. Dead parent?",
4190 case 'q': /* Quiet */
4196 /*** all non capture option specific ***/
4197 case 'D': /* Print a list of capture devices and exit */
4198 if (!list_interfaces) {
4199 list_interfaces = TRUE;
4203 case 'L': /* Print list of link-layer types and exit */
4204 if (!list_link_layer_types) {
4205 list_link_layer_types = TRUE;
4209 #ifdef HAVE_BPF_IMAGE
4210 case 'd': /* Print BPF code for capture filter and exit */
4211 if (!print_bpf_code) {
4212 print_bpf_code = TRUE;
4217 case 'S': /* Print interface statistics once a second */
4218 if (!print_statistics) {
4219 print_statistics = TRUE;
4223 case 'k': /* Set wireless channel */
4226 set_chan_arg = optarg;
4229 cmdarg_err("Only one -k flag may be specified");
4233 case 'M': /* For -D, -L, and -S, print machine-readable output */
4234 machine_readable = TRUE;
4237 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4240 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4243 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4245 case '?': /* Bad flag - print usage message */
4254 /* user specified file name as regular command-line argument */
4255 /* XXX - use it as the capture file name (or something else)? */
4261 * Extra command line arguments were specified; complain.
4262 * XXX - interpret as capture filter, as tcpdump and tshark do?
4264 cmdarg_err("Invalid argument: %s", argv[0]);
4269 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4272 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4273 /* Use some default if the user hasn't specified some */
4274 /* XXX: Are these defaults good enough? */
4275 pcap_queue_byte_limit = 1000 * 1000;
4276 pcap_queue_packet_limit = 1000;
4279 print_usage(stderr);
4283 if (run_once_args > 1) {
4284 #ifdef HAVE_BPF_IMAGE
4285 cmdarg_err("Only one of -D, -L, -d, -k, or -S may be supplied.");
4287 cmdarg_err("Only one of -D, -L, -k, or -S may be supplied.");
4290 } else if (run_once_args == 1) {
4291 /* We're supposed to print some information, rather than
4292 to capture traffic; did they specify a ring buffer option? */
4293 if (global_capture_opts.multi_files_on) {
4294 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4298 /* We're supposed to capture traffic; */
4300 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4301 if (global_capture_opts.ifaces->len > 1) {
4303 global_capture_opts.use_pcapng = TRUE;
4306 if (global_capture_opts.capture_comment &&
4307 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4308 /* XXX - for ringbuffer, should we apply the comment to each file? */
4309 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4313 /* Was the ring buffer option specified and, if so, does it make sense? */
4314 if (global_capture_opts.multi_files_on) {
4315 /* Ring buffer works only under certain conditions:
4316 a) ring buffer does not work with temporary files;
4317 b) it makes no sense to enable the ring buffer if the maximum
4318 file size is set to "infinite". */
4319 if (global_capture_opts.save_file == NULL) {
4320 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4321 global_capture_opts.multi_files_on = FALSE;
4323 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4324 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4326 /* XXX - this must be redesigned as the conditions changed */
4327 global_capture_opts.multi_files_on = FALSE;
4334 * "-D" requires no interface to be selected; it's supposed to list
4337 if (list_interfaces) {
4338 /* Get the list of interfaces */
4343 if_list = capture_interface_list(&err, &err_str,NULL);
4344 if (if_list == NULL) {
4347 * If we're being run by another program, just give them
4348 * an empty list of interfaces, don't report this as
4349 * an error; that lets them decide whether to report
4350 * this as an error or not.
4352 if (!machine_readable) {
4353 cmdarg_err("There are no interfaces on which a capture can be done");
4357 cmdarg_err("%s", err_str);
4363 if (machine_readable) /* tab-separated values to stdout */
4364 print_machine_readable_interfaces(if_list);
4366 capture_opts_print_interfaces(if_list);
4367 free_interface_list(if_list);
4372 * "-S" requires no interface to be selected; it gives statistics
4373 * for all interfaces.
4375 if (print_statistics) {
4376 status = print_statistics_loop(machine_readable);
4381 interface_options interface_opts;
4383 if (global_capture_opts.ifaces->len != 1) {
4384 cmdarg_err("Need one interface");
4388 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4389 status = set_80211_channel(interface_opts.name, set_chan_arg);
4394 * "-L", "-d", and capturing act on a particular interface, so we have to
4395 * have an interface; if none was specified, pick a default.
4397 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4399 /* cmdarg_err() already called .... */
4403 if (list_link_layer_types) {
4404 /* Get the list of link-layer types for the capture device. */
4405 if_capabilities_t *caps;
4409 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4410 interface_options interface_opts;
4412 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4414 caps = get_if_capabilities(&interface_opts, &err_str);
4416 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4417 "Please check to make sure you have sufficient permissions, and that\n"
4418 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4422 if (caps->data_link_types == NULL) {
4423 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4426 if (machine_readable) /* tab-separated values to stdout */
4427 /* XXX: We need to change the format and adopt consumers */
4428 print_machine_readable_if_capabilities(caps);
4430 /* XXX: We might want to print also the interface name */
4431 capture_opts_print_if_capabilities(caps, interface_opts.name,
4432 interface_opts.monitor_mode);
4433 free_if_capabilities(caps);
4438 /* We're supposed to do a capture, or print the BPF code for a filter. */
4440 /* Let the user know what interfaces were chosen. */
4441 if (capture_child) {
4442 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4443 interface_options interface_opts;
4445 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4446 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4447 interface_opts.name);
4450 str = g_string_new("");
4452 if (global_capture_opts.ifaces->len < 2)
4454 if (global_capture_opts.ifaces->len < 4)
4457 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4458 interface_options interface_opts;
4460 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4462 if (global_capture_opts.ifaces->len > 2) {
4463 g_string_append_printf(str, ",");
4465 g_string_append_printf(str, " ");
4466 if (j == global_capture_opts.ifaces->len - 1) {
4467 g_string_append_printf(str, "and ");
4470 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4473 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4475 fprintf(stderr, "Capturing on %s\n", str->str);
4476 g_string_free(str, TRUE);
4479 /* Process the snapshot length, as that affects the generated BPF code. */
4480 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4482 #ifdef HAVE_BPF_IMAGE
4483 if (print_bpf_code) {
4484 show_filter_code(&global_capture_opts);
4489 /* We're supposed to do a capture. Process the ring buffer arguments. */
4490 capture_opts_trim_ring_num_files(&global_capture_opts);
4492 /* flush stderr prior to starting the main capture loop */
4495 /* Now start the capture. */
4496 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4500 /* capture failed */
4503 return 0; /* never here, make compiler happy */
4508 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4509 const char *message, gpointer user_data _U_)
4516 /* ignore log message, if log_level isn't interesting */
4517 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4518 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4523 switch(log_level & G_LOG_LEVEL_MASK) {
4524 case G_LOG_LEVEL_ERROR:
4527 case G_LOG_LEVEL_CRITICAL:
4530 case G_LOG_LEVEL_WARNING:
4533 case G_LOG_LEVEL_MESSAGE:
4536 case G_LOG_LEVEL_INFO:
4539 case G_LOG_LEVEL_DEBUG:
4543 fprintf(stderr, "unknown log_level %d\n", log_level);
4545 g_assert_not_reached();
4548 /* Generate the output message */
4549 if (log_level & G_LOG_LEVEL_MESSAGE) {
4550 /* normal user messages without additional infos */
4551 msg = g_strdup_printf("%s\n", message);
4553 /* create a "timestamp" */
4555 today = localtime(&curr);
4557 /* info/debug messages with additional infos */
4559 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4560 today->tm_hour, today->tm_min, today->tm_sec,
4561 log_domain != NULL ? log_domain : "",
4564 msg = g_strdup_printf("Time not representable %8s %s %s\n",
4565 log_domain != NULL ? log_domain : "",
4569 /* DEBUG & INFO msgs (if we're debugging today) */
4570 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4571 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4572 #ifdef DEBUG_DUMPCAP
4573 fprintf(stderr, "%s", msg);
4576 #ifdef DEBUG_CHILD_DUMPCAP
4577 fprintf(debug_log, "%s", msg);
4585 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4586 /* to parent especially formatted if dumpcap running as child. */
4587 if (capture_child) {
4588 sync_pipe_errmsg_to_parent(2, msg, "");
4590 fprintf(stderr, "%s", msg);
4597 /****************************************************************************************************************/
4598 /* indication report routines */
4602 report_packet_count(unsigned int packet_count)
4604 char tmp[SP_DECISIZE+1+1];
4605 static unsigned int count = 0;
4607 if (capture_child) {
4608 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
4609 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4610 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4612 count += packet_count;
4613 fprintf(stderr, "\rPackets: %u ", count);
4614 /* stderr could be line buffered */
4620 report_new_capture_file(const char *filename)
4622 if (capture_child) {
4623 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4624 pipe_write_block(2, SP_FILE, filename);
4628 * Prevent a SIGINFO handler from writing to the standard error
4629 * while we're doing so; instead, have it just set a flag telling
4630 * us to print that information when we're done.
4633 #endif /* SIGINFO */
4634 fprintf(stderr, "File: %s\n", filename);
4635 /* stderr could be line buffered */
4640 * Allow SIGINFO handlers to write.
4645 * If a SIGINFO handler asked us to write out capture counts, do so.
4648 report_counts_for_siginfo();
4649 #endif /* SIGINFO */
4654 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4656 interface_options interface_opts;
4657 char tmp[MSG_MAX_LENGTH+1+6];
4659 if (i < capture_opts->ifaces->len) {
4660 if (capture_child) {
4661 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4662 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4663 pipe_write_block(2, SP_BAD_FILTER, tmp);
4666 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
4667 * the error message below.
4669 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
4671 "Invalid capture filter \"%s\" for interface '%s'.\n"
4673 "That string isn't a valid capture filter (%s).\n"
4674 "See the User's Guide for a description of the capture filter syntax.",
4675 interface_opts.cfilter, interface_opts.name, errmsg);
4681 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4683 if (capture_child) {
4684 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4685 "Primary Error: %s", error_msg);
4686 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4687 "Secondary Error: %s", secondary_error_msg);
4688 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4690 cmdarg_err("%s", error_msg);
4691 if (secondary_error_msg[0] != '\0')
4692 cmdarg_err_cont("%s", secondary_error_msg);
4697 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
4699 char tmp[SP_DECISIZE+1+1];
4700 guint32 total_drops = pcap_drops + drops + flushed;
4702 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
4704 if (capture_child) {
4705 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4706 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
4707 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
4708 /* XXX: Need to provide interface id, changes to consumers required. */
4709 pipe_write_block(2, SP_DROPS, tmp);
4712 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
4713 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
4714 received ? 100.0 * received / (received + total_drops) : 0.0);
4715 /* stderr could be line buffered */
4721 /************************************************************************************************/
4722 /* signal_pipe handling */
4727 signal_pipe_check_running(void)
4729 /* any news from our parent? -> just stop the capture */
4733 /* if we are running standalone, no check required */
4734 if (!capture_child) {
4738 if (!sig_pipe_name || !sig_pipe_handle) {
4739 /* This shouldn't happen */
4740 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4741 "Signal pipe: No name or handle");
4746 * XXX - We should have the process ID of the parent (from the "-Z" flag)
4747 * at this point. Should we check to see if the parent is still alive,
4748 * e.g. by using OpenProcess?
4751 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
4753 if (!result || avail > 0) {
4754 /* peek failed or some bytes really available */
4755 /* (if not piping from stdin this would fail) */
4756 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4757 "Signal pipe: Stop capture: %s", sig_pipe_name);
4758 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4759 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
4760 sig_pipe_handle, result, avail);
4763 /* pipe ok and no bytes available */
4770 * Editor modelines - https://www.wireshark.org/tools/modelines.html
4775 * indent-tabs-mode: nil
4778 * vi: set shiftwidth=4 tabstop=8 expandtab:
4779 * :indentSize=4:tabSize=8:noTabs=true: