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 <ws_version_info.h>
61 #ifndef HAVE_GETOPT_LONG
62 #include "wsutil/wsgetopt.h"
70 # include <sys/prctl.h>
71 # include <sys/capability.h>
74 #include "ringbuffer.h"
76 #include "caputils/capture_ifinfo.h"
77 #include "caputils/capture-pcap-util.h"
78 #include "caputils/capture-pcap-util-int.h"
80 #include "caputils/capture-wpcap.h"
83 #include "writecap/pcapio.h"
86 #include <wsutil/unicode-utils.h>
93 #include <wsutil/clopts_common.h>
94 #include <wsutil/privileges.h>
96 #include "sync_pipe.h"
98 #include "capture_opts.h"
99 #include <capchild/capture_session.h>
100 #include <capchild/capture_sync.h>
102 #include "conditions.h"
103 #include "capture_stop_conditions.h"
105 #include "wsutil/tempfile.h"
107 #include "wsutil/file_util.h"
108 #include "wsutil/os_version_info.h"
109 #include "wsutil/str_util.h"
110 #include "wsutil/inet_addr.h"
112 #include "caputils/ws80211_utils.h"
119 * Get information about libpcap format from "wiretap/libpcap.h".
120 * Get information about pcapng format from "wiretap/pcapng_module.h".
121 * XXX - can we just use pcap_open_offline() to read the pipe?
123 #include "wiretap/libpcap.h"
124 #include "wiretap/pcapng_module.h"
126 /**#define DEBUG_DUMPCAP**/
127 /**#define DEBUG_CHILD_DUMPCAP**/
131 #include <conio.h> /* _getch() */
135 #ifdef DEBUG_CHILD_DUMPCAP
136 FILE *debug_log; /* for logging debug messages to */
137 /* a file if DEBUG_CHILD_DUMPCAP */
141 static GAsyncQueue *pcap_queue;
142 static gint64 pcap_queue_bytes;
143 static gint64 pcap_queue_packets;
144 static gint64 pcap_queue_byte_limit = 0;
145 static gint64 pcap_queue_packet_limit = 0;
147 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
149 static gchar *sig_pipe_name = NULL;
150 static HANDLE sig_pipe_handle = NULL;
151 static gboolean signal_pipe_check_running(void);
155 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
156 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
159 /** Stop a low-level capture (stops the capture child). */
160 static void capture_loop_stop(void);
161 /** Close a pipe, or socket if \a from_socket is TRUE */
162 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
166 * Enable kernel BPF JIT compiler if available.
167 * If any calls fail, just drive on - the JIT compiler might not be
168 * enabled, but filtering will still work, and it's not clear what
169 * we could do if the calls fail; should we just report the error
170 * and not continue to capture, should we report it as a warning, or
174 enable_kernel_bpf_jit_compiler(void)
178 static const char file[] = "/proc/sys/net/core/bpf_jit_enable";
180 fd = ws_open(file, O_WRONLY);
184 written = ws_write(fd, "1", strlen("1"));
190 #if !defined (__linux__)
191 #ifndef HAVE_PCAP_BREAKLOOP
193 * We don't have pcap_breakloop(), which is the only way to ensure that
194 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
195 * won't, if the call to read the next packet or batch of packets is
196 * is interrupted by a signal on UN*X, just go back and try again to
199 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
200 * the signal handler, set a flag to stop capturing; however, without
201 * a guarantee of that sort, we can't guarantee that we'll stop capturing
202 * if the read will be retried and won't time out if no packets arrive.
204 * Therefore, on at least some platforms, we work around the lack of
205 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
206 * to wait for packets to arrive, so that we're probably going to be
207 * blocked in the select() when the signal arrives, and can just bail
208 * out of the loop at that point.
210 * However, we don't want to do that on BSD (because "select()" doesn't work
211 * correctly on BPF devices on at least some releases of some flavors of
212 * BSD), and we don't want to do it on Windows (because "select()" is
213 * something for sockets, not for arbitrary handles). (Note that "Windows"
214 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
215 * using WinPcap, not a UNIX libpcap.)
217 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
218 * on BSD times out even if no packets have arrived, so we'll eventually
219 * exit pcap_dispatch() with an indication that no packets have arrived,
220 * and will break out of the capture loop at that point.
222 * On Windows, we can't send a SIGINT to stop capturing, so none of this
223 * applies in any case.
225 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
226 * want to include it if it's not present on this platform, however.
228 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
229 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
231 # define MUST_DO_SELECT
232 # endif /* avoid select */
233 #endif /* HAVE_PCAP_BREAKLOOP */
235 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
236 * in pcap_dispatch(); on the other hand, select() works just fine there.
237 * Hence we use a select for that come what may.
239 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
240 * internally, and, with TPACKET_V3, once that's supported, it'll
241 * support timeouts, at least as I understand the way the code works.
243 #define MUST_DO_SELECT
246 /** init the capture filter */
249 INITFILTER_BAD_FILTER,
250 INITFILTER_OTHER_ERROR
251 } initfilter_status_t;
254 STATE_EXPECT_REC_HDR,
267 typedef struct _pcap_options {
272 #ifdef MUST_DO_SELECT
273 int pcap_fd; /**< pcap file descriptor */
280 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
281 /**< capture pipe (unix only "input file") */
282 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
283 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
284 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
285 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
287 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
289 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
290 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
291 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
293 char * cap_pipe_buf; /**< Pointer to the data buffer we read into */
294 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
295 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
297 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
298 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
300 cap_pipe_state_t cap_pipe_state;
301 cap_pipe_err_t cap_pipe_err;
304 GMutex *cap_pipe_read_mtx;
305 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
309 typedef struct _loop_data {
311 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
312 int err; /**< if non-zero, error seen while capturing */
313 gint packet_count; /**< Number of packets we have already captured */
314 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
315 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
317 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
323 guint64 bytes_written;
324 guint32 autostop_files;
327 typedef struct _pcap_queue_element {
328 pcap_options *pcap_opts;
329 struct pcap_pkthdr phdr;
331 } pcap_queue_element;
334 * Standard secondary message for unexpected errors.
336 static const char please_report[] =
337 "Please report this to the Wireshark developers.\n"
338 "https://bugs.wireshark.org/\n"
339 "(This is not a crash; please do not report it as such.)";
342 * This needs to be static, so that the SIGINT handler can clear the "go"
345 static loop_data global_ld;
348 * Timeout, in milliseconds, for reads from the stream of captured packets
349 * from a capture device.
351 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
352 * 64-bit applications, with sub-second timeouts not to work. The bug is
353 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
355 #if defined(__APPLE__) && defined(__LP64__)
356 static gboolean need_timeout_workaround;
358 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
360 #define CAP_READ_TIMEOUT 250
364 * Timeout, in microseconds, for reads from the stream of captured packets
365 * from a pipe. Pipes don't have the same problem that BPF devices do
366 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
367 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
368 * of the offending versions of Snow Leopard.
370 * On Windows this value is converted to milliseconds and passed to
371 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
372 * will return immediately.
375 #define PIPE_READ_TIMEOUT 100000
377 #define PIPE_READ_TIMEOUT 250000
380 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
383 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
384 const char *message, gpointer user_data _U_);
386 /* capture related options */
387 static capture_options global_capture_opts;
388 static gboolean quiet = FALSE;
389 static gboolean use_threads = FALSE;
390 static guint64 start_time;
392 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
394 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
396 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
397 int err, gboolean is_close);
399 static void WS_NORETURN exit_main(int err);
401 static void report_new_capture_file(const char *filename);
402 static void report_packet_count(unsigned int packet_count);
403 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
404 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
405 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
407 #define MSG_MAX_LENGTH 4096
409 /* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
411 create_timestamp(void) {
421 * Current time, represented as 100-nanosecond intervals since
422 * January 1, 1601, 00:00:00 UTC.
424 * I think DWORD might be signed, so cast both parts of "now"
425 * to guint32 so that the sign bit doesn't get treated specially.
427 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
428 * might want to use instead.
430 GetSystemTimeAsFileTime(&now);
431 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
432 (guint32)now.dwLowDateTime;
435 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
441 * Subtract difference, in microseconds, between January 1, 1601
442 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
444 timestamp -= G_GUINT64_CONSTANT(11644473600000000);
447 * Current time, represented as seconds and microseconds since
448 * January 1, 1970, 00:00:00 UTC.
450 gettimeofday(&now, NULL);
453 * Convert to delta in microseconds.
455 timestamp = (guint64)(now.tv_sec) * 1000000 +
456 (guint64)(now.tv_usec);
462 print_usage(FILE *output)
464 fprintf(output, "\nUsage: dumpcap [options] ...\n");
465 fprintf(output, "\n");
466 fprintf(output, "Capture interface:\n");
467 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
468 " or for remote capturing, use one of these formats:\n"
469 " rpcap://<host>/<interface>\n"
470 " TCP@<host>:<port>\n");
471 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
472 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
473 fprintf(output, " -p don't capture in promiscuous mode\n");
474 #ifdef HAVE_PCAP_CREATE
475 fprintf(output, " -I capture in monitor mode, if available\n");
477 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
478 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
480 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
481 fprintf(output, " -D print list of interfaces and exit\n");
482 fprintf(output, " -L print list of link-layer types of iface and exit\n");
483 #ifdef HAVE_BPF_IMAGE
484 fprintf(output, " -d print generated BPF code for capture filter\n");
486 fprintf(output, " -k set channel on wifi interface:\n"
487 " <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
488 fprintf(output, " -S print statistics for each interface once per second\n");
489 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
490 fprintf(output, "\n");
491 #ifdef HAVE_PCAP_REMOTE
492 fprintf(output, "RPCAP options:\n");
493 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
494 fprintf(output, " -u use UDP for RPCAP data transfer\n");
495 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
496 #ifdef HAVE_PCAP_SETSAMPLING
497 fprintf(output, " -m <sampling type> use packet sampling\n");
498 fprintf(output, " count:NUM - capture one packet of every NUM\n");
499 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
502 fprintf(output, "Stop conditions:\n");
503 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
504 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
505 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
506 fprintf(output, " files:NUM - stop after NUM files\n");
507 /*fprintf(output, "\n");*/
508 fprintf(output, "Output (files):\n");
509 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
510 fprintf(output, " -g enable group read access on the output file(s)\n");
511 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
512 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
513 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
514 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
515 fprintf(output, " -P use libpcap format instead of pcapng\n");
516 fprintf(output, " --capture-comment <comment>\n");
517 fprintf(output, " add a capture comment to the output file\n");
518 fprintf(output, " (only for pcapng)\n");
519 fprintf(output, "\n");
520 fprintf(output, "Miscellaneous:\n");
521 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
522 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
523 fprintf(output, " within dumpcap\n");
524 fprintf(output, " -t use a separate thread per interface\n");
525 fprintf(output, " -q don't report packet capture counts\n");
526 fprintf(output, " -v print version information and exit\n");
527 fprintf(output, " -h display this help and exit\n");
528 fprintf(output, "\n");
530 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
531 fprintf(output, "You might want to reset it\n");
532 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
533 fprintf(output, "\n");
535 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
536 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
537 fprintf(output, "\n");
538 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
542 * Report an error in command-line arguments.
543 * If we're a capture child, send a message back to the parent, otherwise
547 dumpcap_cmdarg_err(const char *fmt, va_list ap)
551 /* Generate a 'special format' message back to parent */
552 msg = g_strdup_vprintf(fmt, ap);
553 sync_pipe_errmsg_to_parent(2, msg, "");
556 fprintf(stderr, "dumpcap: ");
557 vfprintf(stderr, fmt, ap);
558 fprintf(stderr, "\n");
563 * Report additional information for an error in command-line arguments.
564 * If we're a capture child, send a message back to the parent, otherwise
568 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
572 msg = g_strdup_vprintf(fmt, ap);
573 sync_pipe_errmsg_to_parent(2, msg, "");
576 vfprintf(stderr, fmt, ap);
577 fprintf(stderr, "\n");
583 #if 0 /* Set to enable capability debugging */
584 /* see 'man cap_to_text()' for explanation of output */
585 /* '=' means 'all= ' ie: no capabilities */
586 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
588 print_caps(const char *pfx) {
589 cap_t caps = cap_get_proc();
590 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
591 "%s: EUID: %d Capabilities: %s", pfx,
592 geteuid(), cap_to_text(caps, NULL));
595 print_caps(const char *pfx _U_) {
600 relinquish_all_capabilities(void)
602 /* Drop any and all capabilities this process may have. */
603 /* Allowed whether or not process has any privileges. */
604 cap_t caps = cap_init(); /* all capabilities initialized to off */
605 print_caps("Pre-clear");
606 if (cap_set_proc(caps)) {
607 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
609 print_caps("Post-clear");
615 get_capture_device_open_failure_messages(const char *open_err_str,
617 char *errmsg, size_t errmsg_len,
618 char *secondary_errmsg,
619 size_t secondary_errmsg_len)
622 const char *libpcap_warn;
623 static const char ppamsg[] = "can't find PPA for ";
626 g_snprintf(errmsg, (gulong) errmsg_len,
627 "The capture session could not be initiated on interface '%s' (%s).",
628 iface, open_err_str);
631 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
633 "In order to capture packets, WinPcap must be installed; see\n"
635 " https://www.winpcap.org/\n"
637 "for a downloadable version of WinPcap and for instructions on how to install\n"
640 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
642 "Please check that \"%s\" is the proper interface.\n"
645 "Help can be found at:\n"
647 " https://wiki.wireshark.org/WinPcap\n"
648 " https://wiki.wireshark.org/CaptureSetup\n",
652 /* If we got a "can't find PPA for X" message, warn the user (who
653 is running dumpcap on HP-UX) that they don't have a version of
654 libpcap that properly handles HP-UX (libpcap 0.6.x and later
655 versions, which properly handle HP-UX, say "can't find /dev/dlpi
656 PPA for X" rather than "can't find PPA for X"). */
657 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
660 "You are running (T)Wireshark with a version of the libpcap library\n"
661 "that doesn't handle HP-UX network devices well; this means that\n"
662 "(T)Wireshark may not be able to capture packets.\n"
664 "To fix this, you should install libpcap 0.6.2, or a later version\n"
665 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
666 "packaged binary form from the Software Porting And Archive Centre\n"
667 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
668 "at the URL lists a number of mirror sites.";
672 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
673 "Please check to make sure you have sufficient permissions, and that you have "
674 "the proper interface or pipe specified.%s", libpcap_warn);
679 compile_capture_filter(const char *iface, pcap_t *pcap_h,
680 struct bpf_program *fcode, const char *cfilter)
682 bpf_u_int32 netnum, netmask;
683 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
685 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
687 * Well, we can't get the netmask for this interface; it's used
688 * only for filters that check for broadcast IP addresses, so
689 * we just punt and use 0. It might be nice to warn the user,
690 * but that's a pain in a GUI application, as it'd involve popping
691 * up a message box, and it's not clear how often this would make
692 * a difference (only filters that check for IP broadcast addresses
696 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
701 * Sigh. Older versions of libpcap don't properly declare the
702 * third argument to pcap_compile() as a const pointer. Cast
706 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
712 #ifdef HAVE_BPF_IMAGE
714 show_filter_code(capture_options *capture_opts)
716 interface_options interface_opts;
718 gchar open_err_str[PCAP_ERRBUF_SIZE];
719 char errmsg[MSG_MAX_LENGTH+1];
720 char secondary_errmsg[MSG_MAX_LENGTH+1];
721 struct bpf_program fcode;
722 struct bpf_insn *insn;
726 for (j = 0; j < capture_opts->ifaces->len; j++) {
727 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
728 pcap_h = open_capture_device(capture_opts, &interface_opts,
729 CAP_READ_TIMEOUT, &open_err_str);
730 if (pcap_h == NULL) {
731 /* Open failed; get messages */
732 get_capture_device_open_failure_messages(open_err_str,
734 errmsg, sizeof errmsg,
736 sizeof secondary_errmsg);
737 /* And report them */
738 report_capture_error(errmsg, secondary_errmsg);
742 /* Set the link-layer type. */
743 if (!set_pcap_datalink(pcap_h, interface_opts.linktype, interface_opts.name,
744 errmsg, sizeof errmsg,
745 secondary_errmsg, sizeof secondary_errmsg)) {
747 report_capture_error(errmsg, secondary_errmsg);
751 /* OK, try to compile the capture filter. */
752 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
753 interface_opts.cfilter)) {
755 report_cfilter_error(capture_opts, j, errmsg);
760 /* Now print the filter code. */
761 insn = fcode.bf_insns;
763 for (i = 0; i < fcode.bf_len; insn++, i++)
764 printf("%s\n", bpf_image(insn, i));
766 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
767 /* to remove any suid privileges. */
768 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
769 /* (euid/egid have already previously been set to ruid/rgid. */
770 /* (See comment in main() for details) */
772 relinquish_special_privs_perm();
774 relinquish_all_capabilities();
777 /* Let our parent know we succeeded. */
778 pipe_write_block(2, SP_SUCCESS, NULL);
785 * capture_interface_list() is expected to do the right thing to get
786 * a list of interfaces.
788 * In most of the programs in the Wireshark suite, "the right thing"
789 * is to run dumpcap and ask it for the list, because dumpcap may
790 * be the only program in the suite with enough privileges to get
793 * In dumpcap itself, however, we obviously can't run dumpcap to
794 * ask for the list. Therefore, our capture_interface_list() should
795 * just call get_interface_list().
798 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
800 return get_interface_list(err, err_str);
803 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
805 * Output a machine readable list of the interfaces
806 * This list is retrieved by the sync_interface_list_open() function
807 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
810 print_machine_readable_interfaces(GList *if_list)
817 char addr_str[ADDRSTRLEN];
820 /* Let our parent know we succeeded. */
821 pipe_write_block(2, SP_SUCCESS, NULL);
824 i = 1; /* Interface id number */
825 for (if_entry = g_list_first(if_list); if_entry != NULL;
826 if_entry = g_list_next(if_entry)) {
827 if_info = (if_info_t *)if_entry->data;
828 printf("%d. %s\t", i++, if_info->name);
831 * Print the contents of the if_entry struct in a parseable format.
832 * Each if_entry element is tab-separated. Addresses are comma-
835 /* XXX - Make sure our description doesn't contain a tab */
836 if (if_info->vendor_description != NULL)
837 printf("%s\t", if_info->vendor_description);
841 /* XXX - Make sure our friendly name doesn't contain a tab */
842 if (if_info->friendly_name != NULL)
843 printf("%s\t", if_info->friendly_name);
847 printf("%i\t", if_info->type);
849 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
850 addr = g_slist_next(addr)) {
851 if (addr != g_slist_nth(if_info->addrs, 0))
854 if_addr = (if_addr_t *)addr->data;
855 switch(if_addr->ifat_type) {
857 if (ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str,
859 printf("%s", addr_str);
861 printf("<unknown IPv4>");
865 if (ws_inet_ntop6(&if_addr->addr.ip6_addr,
866 addr_str, ADDRSTRLEN)) {
867 printf("%s", addr_str);
869 printf("<unknown IPv6>");
873 printf("<type unknown %i>", if_addr->ifat_type);
877 if (if_info->loopback)
878 printf("\tloopback");
882 printf("\t%s", if_info->extcap);
889 * If you change the machine-readable output format of this function,
890 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
893 print_machine_readable_if_capabilities(if_capabilities_t *caps)
896 data_link_info_t *data_link_info;
897 const gchar *desc_str;
900 /* Let our parent know we succeeded. */
901 pipe_write_block(2, SP_SUCCESS, NULL);
904 if (caps->can_set_rfmon)
908 for (lt_entry = caps->data_link_types; lt_entry != NULL;
909 lt_entry = g_list_next(lt_entry)) {
910 data_link_info = (data_link_info_t *)lt_entry->data;
911 if (data_link_info->description != NULL)
912 desc_str = data_link_info->description;
914 desc_str = "(not supported)";
915 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
925 /* Print the number of packets captured for each interface until we're killed. */
927 print_statistics_loop(gboolean machine_readable)
929 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
935 char errbuf[PCAP_ERRBUF_SIZE];
938 if_list = get_interface_list(&err, &err_str);
939 if (if_list == NULL) {
941 cmdarg_err("There are no interfaces on which a capture can be done");
943 cmdarg_err("%s", err_str);
949 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
950 if_info = (if_info_t *)if_entry->data;
953 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
954 * connections. We avoid collecting stats on them.
956 if (!strncmp(if_info->name, "nf", 2)) {
957 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
963 #ifdef HAVE_PCAP_OPEN
964 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
966 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
970 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
971 if_stat->name = g_strdup(if_info->name);
973 stat_list = g_list_append(stat_list, if_stat);
978 cmdarg_err("There are no interfaces on which a capture can be done");
983 /* Let our parent know we succeeded. */
984 pipe_write_block(2, SP_SUCCESS, NULL);
987 if (!machine_readable) {
988 printf("%-15s %10s %10s\n", "Interface", "Received",
993 while (global_ld.go) {
994 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
995 if_stat = (if_stat_t *)stat_entry->data;
996 pcap_stats(if_stat->pch, &ps);
998 if (!machine_readable) {
999 printf("%-15s %10u %10u\n", if_stat->name,
1000 ps.ps_recv, ps.ps_drop);
1002 printf("%s\t%u\t%u\n", if_stat->name,
1003 ps.ps_recv, ps.ps_drop);
1008 /* If we have a dummy signal pipe check it */
1009 if (!signal_pipe_check_running()) {
1010 global_ld.go = FALSE;
1018 /* XXX - Not reached. Should we look for 'q' in stdin? */
1019 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1020 if_stat = (if_stat_t *)stat_entry->data;
1021 pcap_close(if_stat->pch);
1022 g_free(if_stat->name);
1025 g_list_free(stat_list);
1026 free_interface_list(if_list);
1034 capture_cleanup_handler(DWORD dwCtrlType)
1036 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1037 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1038 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1039 like SIGTERM at least when the machine's shutting down.
1041 For now, if we're running as a command rather than a capture child,
1042 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1043 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1044 in that way on UN*X.
1046 If we're not running as a capture child, we might be running as
1047 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1048 user logs out. (XXX - can we explicitly check whether we're
1049 running as a service?) */
1051 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1052 "Console: Control signal");
1053 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1054 "Console: Control signal, CtrlType: %u", dwCtrlType);
1056 /* Keep capture running if we're a service and a user logs off */
1057 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1058 capture_loop_stop();
1066 capture_cleanup_handler(int signum _U_)
1068 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1069 SIGTERM. We assume that if the user wanted it to keep running
1070 after they logged out, they'd have nohupped it. */
1072 /* Note: don't call g_log() in the signal handler: if we happened to be in
1073 * g_log() in process context when the signal came in, g_log will detect
1074 * the "recursion" and abort.
1077 capture_loop_stop();
1083 report_capture_count(gboolean reportit)
1085 /* Don't print this if we're a capture child. */
1086 if (!capture_child && reportit) {
1087 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packet_count);
1088 /* stderr could be line buffered */
1096 report_counts_for_siginfo(void)
1098 report_capture_count(quiet);
1099 infoprint = FALSE; /* we just reported it */
1103 report_counts_siginfo(int signum _U_)
1105 int sav_errno = errno;
1107 /* If we've been told to delay printing, just set a flag asking
1108 that we print counts (if we're supposed to), otherwise print
1109 the count of packets captured (if we're supposed to). */
1113 report_counts_for_siginfo();
1116 #endif /* SIGINFO */
1119 exit_main(int status)
1122 /* Shutdown windows sockets */
1125 /* can be helpful for debugging */
1126 #ifdef DEBUG_DUMPCAP
1127 printf("Press any key\n");
1138 * If we were linked with libcap (not related to libpcap), make sure we have
1139 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1140 * (See comment in main() for details)
1143 relinquish_privs_except_capture(void)
1145 /* If 'started_with_special_privs' (ie: suid) then enable for
1146 * ourself the NET_ADMIN and NET_RAW capabilities and then
1147 * drop our suid privileges.
1149 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1150 * stuff we don't need (and shouldn't have).
1151 * CAP_NET_RAW: Packet capture (raw sockets).
1154 if (started_with_special_privs()) {
1155 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1156 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1158 cap_t caps = cap_init(); /* all capabilities initialized to off */
1160 print_caps("Pre drop, pre set");
1162 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1163 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1166 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1167 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1169 if (cap_set_proc(caps)) {
1170 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1172 print_caps("Pre drop, post set");
1174 relinquish_special_privs_perm();
1176 print_caps("Post drop, pre set");
1177 cap_set_flag(caps, CAP_EFFECTIVE, 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("Post drop, post set");
1187 #endif /* HAVE_LIBCAP */
1189 /* Take care of byte order in the libpcap headers read from pipes.
1190 * (function taken from wiretap/libpcap.c) */
1192 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1195 /* Byte-swap the record header fields. */
1196 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1197 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1198 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1199 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1202 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1203 swapped, in order to match the BPF header layout.
1205 Unfortunately, some files were, according to a comment in the "libpcap"
1206 source, written with version 2.3 in their headers but without the
1207 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1208 would make no sense - we assume that we need to swap them. */
1209 if (hdr->version_major == 2 &&
1210 (hdr->version_minor < 3 ||
1211 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1214 temp = rechdr->orig_len;
1215 rechdr->orig_len = rechdr->incl_len;
1216 rechdr->incl_len = temp;
1220 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1224 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1228 return recv(pipe_fd, buf, (int)sz, 0);
1233 return ws_read(pipe_fd, buf, sz);
1239 * Thread function that reads from a pipe and pushes the data
1240 * to the main application thread.
1243 * XXX Right now we use async queues for basic signaling. The main thread
1244 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1245 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1246 * Iff the read is successful cap_pipe_read pushes an item onto
1247 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1248 * the queues themselves (yet).
1250 * We might want to move some of the cap_pipe_dispatch logic here so that
1251 * we can let cap_thread_read run independently, queuing up multiple reads
1252 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1254 static void *cap_thread_read(void *arg)
1256 pcap_options *pcap_opts;
1259 DWORD b, last_err, bytes_read;
1265 pcap_opts = (pcap_options *)arg;
1266 while (pcap_opts->cap_pipe_err == PIPOK) {
1267 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1268 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1270 while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1271 if ((pcap_opts->from_cap_socket)
1277 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1278 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1281 pcap_opts->cap_pipe_err = PIPEOF;
1285 pcap_opts->cap_pipe_err = PIPERR;
1296 /* If we try to use read() on a named pipe on Windows with partial
1297 * data it appears to return EOF.
1299 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1300 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1305 last_err = GetLastError();
1306 if (last_err == ERROR_MORE_DATA) {
1308 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1309 pcap_opts->cap_pipe_err = PIPEOF;
1313 pcap_opts->cap_pipe_err = PIPERR;
1316 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1317 pcap_opts->cap_pipe_err = PIPEOF;
1324 pcap_opts->cap_pipe_bytes_read = bytes_read;
1325 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1326 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1328 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1334 /* Provide select() functionality for a single file descriptor
1335 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1337 * Returns the same values as select.
1340 cap_pipe_select(int pipe_fd)
1343 struct timeval timeout;
1346 FD_SET(pipe_fd, &rfds);
1348 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1349 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1351 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1354 #define DEF_TCP_PORT 19000
1357 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1359 char *sockname = pipename + 4;
1360 struct sockaddr_in sa;
1367 memset(&sa, 0, sizeof(sa));
1369 p = strchr(sockname, ':');
1371 len = strlen(sockname);
1372 port = DEF_TCP_PORT;
1376 port = strtoul(p + 1, &p, 10);
1377 if (*p || port > 65535) {
1386 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1388 if (!ws_inet_pton4(buf, (guint32 *)&sa.sin_addr)) {
1392 sa.sin_family = AF_INET;
1393 sa.sin_port = g_htons((u_short)port);
1395 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1396 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1398 LPTSTR errorText = NULL;
1401 lastError = WSAGetLastError();
1402 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1403 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1404 FORMAT_MESSAGE_IGNORE_INSERTS,
1405 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1406 (LPTSTR)&errorText, 0, NULL);
1408 g_snprintf(errmsg, errmsgl,
1409 "The capture session could not be initiated due to the socket error: \n"
1411 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1413 LocalFree(errorText);
1415 " %d: %s", errno, g_strerror(errno));
1417 pcap_opts->cap_pipe_err = PIPERR;
1420 cap_pipe_close(fd, TRUE);
1424 pcap_opts->from_cap_socket = TRUE;
1428 g_snprintf(errmsg, errmsgl,
1429 "The capture session could not be initiated because\n"
1430 "\"%s\" is not a valid socket specification", pipename);
1431 pcap_opts->cap_pipe_err = PIPERR;
1435 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1439 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1443 closesocket(pipe_fd);
1450 /* Mimic pcap_open_live() for pipe captures
1452 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1453 * open it, and read the header.
1455 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1456 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1458 cap_pipe_open_live(char *pipename,
1459 pcap_options *pcap_opts,
1460 struct pcap_hdr *hdr,
1461 char *errmsg, int errmsgl)
1464 ws_statb64 pipe_stat;
1465 struct sockaddr_un sa;
1469 interface_options interface_opts;
1471 char* extcap_pipe_name;
1472 gboolean extcap_pipe;
1476 int fd = -1, sel_ret;
1479 pcap_opts->cap_pipe_fd = -1;
1481 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1484 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1487 * XXX - this blocks until a pcap per-file header has been written to
1488 * the pipe, so it could block indefinitely.
1490 if (strcmp(pipename, "-") == 0) {
1492 fd = 0; /* read from stdin */
1494 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1496 } else if (!strncmp(pipename, "TCP@", 4)) {
1497 if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
1502 if (ws_stat64(pipename, &pipe_stat) < 0) {
1503 if (errno == ENOENT || errno == ENOTDIR)
1504 pcap_opts->cap_pipe_err = PIPNEXIST;
1506 g_snprintf(errmsg, errmsgl,
1507 "The capture session could not be initiated "
1508 "due to error getting information on pipe/socket: %s.", g_strerror(errno));
1509 pcap_opts->cap_pipe_err = PIPERR;
1513 if (S_ISFIFO(pipe_stat.st_mode)) {
1514 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1516 g_snprintf(errmsg, errmsgl,
1517 "The capture session could not be initiated "
1518 "due to error on pipe open: %s.", g_strerror(errno));
1519 pcap_opts->cap_pipe_err = PIPERR;
1522 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1523 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1525 g_snprintf(errmsg, errmsgl,
1526 "The capture session could not be initiated "
1527 "due to error on socket create: %s.", g_strerror(errno));
1528 pcap_opts->cap_pipe_err = PIPERR;
1531 sa.sun_family = AF_UNIX;
1533 * The Single UNIX Specification says:
1535 * The size of sun_path has intentionally been left undefined.
1536 * This is because different implementations use different sizes.
1537 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1538 * of 104. Since most implementations originate from BSD versions,
1539 * the size is typically in the range 92 to 108.
1541 * Applications should not assume a particular length for sun_path
1542 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1546 * The <sys/un.h> header shall define the sockaddr_un structure,
1547 * which shall include at least the following members:
1549 * sa_family_t sun_family Address family.
1550 * char sun_path[] Socket pathname.
1552 * so we assume that it's an array, with a specified size,
1553 * and that the size reflects the maximum path length.
1555 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1556 /* Path name too long */
1557 g_snprintf(errmsg, errmsgl,
1558 "The capture session coud not be initiated "
1559 "due to error on socket connect: Path name too long.");
1560 pcap_opts->cap_pipe_err = PIPERR;
1564 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1566 g_snprintf(errmsg, errmsgl,
1567 "The capture session coud not be initiated "
1568 "due to error on socket connect: %s.", g_strerror(errno));
1569 pcap_opts->cap_pipe_err = PIPERR;
1574 if (S_ISCHR(pipe_stat.st_mode)) {
1576 * Assume the user specified an interface on a system where
1577 * interfaces are in /dev. Pretend we haven't seen it.
1579 pcap_opts->cap_pipe_err = PIPNEXIST;
1581 g_snprintf(errmsg, errmsgl,
1582 "The capture session could not be initiated because\n"
1583 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1584 pcap_opts->cap_pipe_err = PIPERR;
1589 #define PIPE_STR "\\pipe\\"
1590 /* Under Windows, named pipes _must_ have the form
1591 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1593 pncopy = g_strdup(pipename);
1594 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1595 pos = strchr(pncopy + 3, '\\');
1596 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1603 g_snprintf(errmsg, errmsgl,
1604 "The capture session could not be initiated because\n"
1605 "\"%s\" is neither an interface nor a pipe.", pipename);
1606 pcap_opts->cap_pipe_err = PIPNEXIST;
1610 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
1612 extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
1613 extcap_pipe = strstr(interface_opts.name, extcap_pipe_name) ? TRUE : FALSE;
1614 g_free(extcap_pipe_name);
1617 /* Wait for the pipe to appear */
1622 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1625 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1626 OPEN_EXISTING, 0, NULL);
1628 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
1631 if (GetLastError() != ERROR_PIPE_BUSY) {
1632 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1633 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1634 g_snprintf(errmsg, errmsgl,
1635 "The capture session on \"%s\" could not be started "
1636 "due to error on pipe open: %s (error %d).",
1637 pipename, utf_16to8(err_str), GetLastError());
1639 pcap_opts->cap_pipe_err = PIPERR;
1643 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1644 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1645 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1646 g_snprintf(errmsg, errmsgl,
1647 "The capture session on \"%s\" timed out during "
1648 "pipe open: %s (error %d).",
1649 pipename, utf_16to8(err_str), GetLastError());
1651 pcap_opts->cap_pipe_err = PIPERR;
1658 pcap_opts->from_cap_pipe = TRUE;
1661 if (pcap_opts->from_cap_socket)
1664 /* read the pcap header */
1666 while (bytes_read < sizeof magic) {
1668 g_snprintf(errmsg, errmsgl, "Invalid file descriptor.");
1672 sel_ret = cap_pipe_select(fd);
1674 g_snprintf(errmsg, errmsgl,
1675 "Unexpected error from select: %s.", g_strerror(errno));
1677 } else if (sel_ret > 0) {
1678 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1679 sizeof magic-bytes_read,
1680 pcap_opts->from_cap_socket);
1683 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1685 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1695 #if GLIB_CHECK_VERSION(2,31,0)
1696 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
1698 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
1701 pcap_opts->cap_pipe_buf = (char *) &magic;
1702 pcap_opts->cap_pipe_bytes_read = 0;
1703 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
1704 /* We don't have to worry about cap_pipe_read_mtx here */
1705 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1706 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
1707 if (pcap_opts->cap_pipe_bytes_read <= 0) {
1708 if (pcap_opts->cap_pipe_bytes_read == 0)
1709 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1711 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1720 case PCAP_NSEC_MAGIC:
1721 /* Host that wrote it has our byte order, and was running
1722 a program using either standard or ss990417 libpcap. */
1723 pcap_opts->cap_pipe_byte_swapped = FALSE;
1724 pcap_opts->cap_pipe_modified = FALSE;
1725 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
1727 case PCAP_MODIFIED_MAGIC:
1728 /* Host that wrote it has our byte order, but was running
1729 a program using either ss990915 or ss991029 libpcap. */
1730 pcap_opts->cap_pipe_byte_swapped = FALSE;
1731 pcap_opts->cap_pipe_modified = TRUE;
1733 case PCAP_SWAPPED_MAGIC:
1734 case PCAP_SWAPPED_NSEC_MAGIC:
1735 /* Host that wrote it has a byte order opposite to ours,
1736 and was running a program using either standard or
1737 ss990417 libpcap. */
1738 pcap_opts->cap_pipe_byte_swapped = TRUE;
1739 pcap_opts->cap_pipe_modified = FALSE;
1740 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
1742 case PCAP_SWAPPED_MODIFIED_MAGIC:
1743 /* Host that wrote it out has a byte order opposite to
1744 ours, and was running a program using either ss990915
1745 or ss991029 libpcap. */
1746 pcap_opts->cap_pipe_byte_swapped = TRUE;
1747 pcap_opts->cap_pipe_modified = TRUE;
1749 case BLOCK_TYPE_SHB:
1750 /* This isn't pcap, it's pcapng. We don't yet support
1752 g_snprintf(errmsg, errmsgl, "Capturing from a pipe doesn't support pcapng format.");
1755 /* Not a pcap type we know about, or not pcap at all. */
1756 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format or not libpcap data.");
1761 if (pcap_opts->from_cap_socket)
1764 /* Read the rest of the header */
1766 while (bytes_read < sizeof(struct pcap_hdr)) {
1767 sel_ret = cap_pipe_select(fd);
1769 g_snprintf(errmsg, errmsgl,
1770 "Unexpected error from select: %s.", g_strerror(errno));
1772 } else if (sel_ret > 0) {
1773 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
1774 sizeof(struct pcap_hdr) - bytes_read,
1775 pcap_opts->from_cap_socket);
1778 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1780 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s.",
1790 pcap_opts->cap_pipe_buf = (char *) hdr;
1791 pcap_opts->cap_pipe_bytes_read = 0;
1792 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1793 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1794 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
1795 if (pcap_opts->cap_pipe_bytes_read <= 0) {
1796 if (pcap_opts->cap_pipe_bytes_read == 0)
1797 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1799 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s.",
1806 if (pcap_opts->cap_pipe_byte_swapped) {
1807 /* Byte-swap the header fields about which we care. */
1808 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
1809 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
1810 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
1811 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
1813 pcap_opts->linktype = hdr->network;
1815 if (hdr->version_major < 2) {
1816 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1820 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
1821 pcap_opts->cap_pipe_err = PIPOK;
1822 pcap_opts->cap_pipe_fd = fd;
1826 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1827 pcap_opts->cap_pipe_err = PIPERR;
1828 cap_pipe_close(fd, pcap_opts->from_cap_socket);
1829 pcap_opts->cap_pipe_fd = -1;
1833 /* We read one record from the pipe, take care of byte order in the record
1834 * header, write the record to the capture file, and update capture statistics. */
1836 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
1838 struct pcap_pkthdr phdr;
1839 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1842 #if !GLIB_CHECK_VERSION(2,31,18)
1850 #ifdef LOG_CAPTURE_VERBOSE
1851 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1854 switch (pcap_opts->cap_pipe_state) {
1856 case STATE_EXPECT_REC_HDR:
1858 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
1861 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
1862 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
1863 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1864 pcap_opts->cap_pipe_bytes_read = 0;
1867 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
1868 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1869 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1874 case STATE_READ_REC_HDR:
1876 if (pcap_opts->from_cap_socket)
1879 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
1880 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
1883 result = PD_PIPE_EOF;
1885 result = PD_PIPE_ERR;
1888 pcap_opts->cap_pipe_bytes_read += b;
1892 #if GLIB_CHECK_VERSION(2,31,18)
1893 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
1895 g_get_current_time(&wait_time);
1896 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
1897 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
1899 if (pcap_opts->cap_pipe_err == PIPEOF) {
1900 result = PD_PIPE_EOF;
1902 } else if (pcap_opts->cap_pipe_err == PIPERR) {
1903 result = PD_PIPE_ERR;
1911 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
1913 result = PD_REC_HDR_READ;
1916 case STATE_EXPECT_DATA:
1918 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
1921 pcap_opts->cap_pipe_state = STATE_READ_DATA;
1922 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
1923 pcap_opts->cap_pipe_bytes_read = 0;
1926 pcap_opts->cap_pipe_buf = (char *) data;
1927 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1928 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1933 case STATE_READ_DATA:
1935 if (pcap_opts->from_cap_socket)
1938 b = cap_pipe_read(pcap_opts->cap_pipe_fd,
1939 data+pcap_opts->cap_pipe_bytes_read,
1940 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
1941 pcap_opts->from_cap_socket);
1944 result = PD_PIPE_EOF;
1946 result = PD_PIPE_ERR;
1949 pcap_opts->cap_pipe_bytes_read += b;
1954 #if GLIB_CHECK_VERSION(2,31,18)
1955 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
1957 g_get_current_time(&wait_time);
1958 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
1959 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
1960 #endif /* GLIB_CHECK_VERSION(2,31,18) */
1961 if (pcap_opts->cap_pipe_err == PIPEOF) {
1962 result = PD_PIPE_EOF;
1964 } else if (pcap_opts->cap_pipe_err == PIPERR) {
1965 result = PD_PIPE_ERR;
1973 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
1975 result = PD_DATA_READ;
1979 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
1982 } /* switch (pcap_opts->cap_pipe_state) */
1985 * We've now read as much data as we were expecting, so process it.
1989 case PD_REC_HDR_READ:
1990 /* We've read the header. Take care of byte order. */
1991 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
1992 &pcap_opts->cap_pipe_rechdr.hdr);
1993 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1994 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1995 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
1999 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2000 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2003 /* no data to read? fall through */
2006 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2007 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2008 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2009 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2010 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2013 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2015 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2017 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2021 pcap_opts->cap_pipe_err = PIPEOF;
2026 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2027 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2028 g_snprintf(errmsg, errmsgl,
2029 "Error reading from pipe: %s (error %d)",
2030 utf_16to8(err_str), GetLastError());
2033 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2041 pcap_opts->cap_pipe_err = PIPERR;
2042 /* Return here rather than inside the switch to prevent GCC warning */
2047 /** Open the capture input file (pcap or capture pipe).
2048 * Returns TRUE if it succeeds, FALSE otherwise. */
2050 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2051 char *errmsg, size_t errmsg_len,
2052 char *secondary_errmsg, size_t secondary_errmsg_len)
2054 gchar open_err_str[PCAP_ERRBUF_SIZE];
2055 gchar *sync_msg_str;
2056 interface_options interface_opts;
2057 pcap_options *pcap_opts;
2061 WORD wVersionRequested;
2065 /* XXX - opening Winsock on tshark? */
2067 /* Initialize Windows Socket if we are in a Win32 OS
2068 This needs to be done before querying the interface for network/netmask */
2070 /* XXX - do we really require 1.1 or earlier?
2071 Are there any versions that support only 2.0 or higher? */
2072 wVersionRequested = MAKEWORD(1, 1);
2073 err = WSAStartup(wVersionRequested, &wsaData);
2077 case WSASYSNOTREADY:
2078 g_snprintf(errmsg, (gulong) errmsg_len,
2079 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2082 case WSAVERNOTSUPPORTED:
2083 g_snprintf(errmsg, (gulong) errmsg_len,
2084 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2085 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2088 case WSAEINPROGRESS:
2089 g_snprintf(errmsg, (gulong) errmsg_len,
2090 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2094 g_snprintf(errmsg, (gulong) errmsg_len,
2095 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2099 g_snprintf(errmsg, (gulong) errmsg_len,
2100 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2104 g_snprintf(errmsg, (gulong) errmsg_len,
2105 "Couldn't initialize Windows Sockets: error %d", err);
2108 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2112 if ((use_threads == FALSE) &&
2113 (capture_opts->ifaces->len > 1)) {
2114 g_snprintf(errmsg, (gulong) errmsg_len,
2115 "Using threads is required for capturing on multiple interfaces.");
2119 for (i = 0; i < capture_opts->ifaces->len; i++) {
2120 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2121 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2122 if (pcap_opts == NULL) {
2123 g_snprintf(errmsg, (gulong) errmsg_len,
2124 "Could not allocate memory.");
2127 pcap_opts->received = 0;
2128 pcap_opts->dropped = 0;
2129 pcap_opts->flushed = 0;
2130 pcap_opts->pcap_h = NULL;
2131 #ifdef MUST_DO_SELECT
2132 pcap_opts->pcap_fd = -1;
2134 pcap_opts->pcap_err = FALSE;
2135 pcap_opts->interface_id = i;
2136 pcap_opts->tid = NULL;
2137 pcap_opts->snaplen = 0;
2138 pcap_opts->linktype = -1;
2139 pcap_opts->ts_nsec = FALSE;
2140 pcap_opts->from_cap_pipe = FALSE;
2141 pcap_opts->from_cap_socket = FALSE;
2142 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2143 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2145 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2147 pcap_opts->cap_pipe_fd = -1;
2148 pcap_opts->cap_pipe_modified = FALSE;
2149 pcap_opts->cap_pipe_byte_swapped = FALSE;
2151 pcap_opts->cap_pipe_buf = NULL;
2153 pcap_opts->cap_pipe_bytes_to_read = 0;
2154 pcap_opts->cap_pipe_bytes_read = 0;
2155 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2156 pcap_opts->cap_pipe_err = PIPOK;
2158 #if GLIB_CHECK_VERSION(2,31,0)
2159 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2160 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2162 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2164 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2165 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2167 g_array_append_val(ld->pcaps, pcap_opts);
2169 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2170 pcap_opts->pcap_h = open_capture_device(capture_opts, &interface_opts,
2171 CAP_READ_TIMEOUT, &open_err_str);
2173 if (pcap_opts->pcap_h != NULL) {
2174 /* we've opened "iface" as a network device */
2176 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2177 /* Find out if we're getting nanosecond-precision time stamps */
2178 pcap_opts->ts_nsec = have_high_resolution_timestamp(pcap_opts->pcap_h);
2181 #if defined(HAVE_PCAP_SETSAMPLING)
2182 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2183 struct pcap_samp *samp;
2185 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2186 switch (interface_opts.sampling_method) {
2187 case CAPTURE_SAMP_BY_COUNT:
2188 samp->method = PCAP_SAMP_1_EVERY_N;
2191 case CAPTURE_SAMP_BY_TIMER:
2192 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2196 sync_msg_str = g_strdup_printf(
2197 "Unknown sampling method %d specified,\n"
2198 "continue without packet sampling",
2199 interface_opts.sampling_method);
2200 report_capture_error("Couldn't set the capture "
2201 "sampling", sync_msg_str);
2202 g_free(sync_msg_str);
2204 samp->value = interface_opts.sampling_param;
2206 report_capture_error("Couldn't set the capture sampling",
2207 "Cannot get packet sampling data structure");
2212 /* setting the data link type only works on real interfaces */
2213 if (!set_pcap_datalink(pcap_opts->pcap_h, interface_opts.linktype,
2214 interface_opts.name,
2216 secondary_errmsg, secondary_errmsg_len)) {
2219 pcap_opts->linktype = get_pcap_datalink(pcap_opts->pcap_h, interface_opts.name);
2221 /* We couldn't open "iface" as a network device. */
2222 /* Try to open it as a pipe */
2223 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2226 if (pcap_opts->cap_pipe_fd == -1) {
2228 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2230 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2232 * We tried opening as an interface, and that failed,
2233 * so we tried to open it as a pipe, but the pipe
2234 * doesn't exist. Report the error message for
2237 get_capture_device_open_failure_messages(open_err_str,
2238 interface_opts.name,
2242 secondary_errmsg_len);
2245 * Else pipe (or file) does exist and cap_pipe_open_live() has
2250 /* cap_pipe_open_live() succeeded; don't want
2251 error message from pcap_open_live() */
2252 open_err_str[0] = '\0';
2256 /* XXX - will this work for tshark? */
2257 #ifdef MUST_DO_SELECT
2258 if (!pcap_opts->from_cap_pipe) {
2259 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2260 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2262 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2267 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2268 returned a warning; print it, but keep capturing. */
2269 if (open_err_str[0] != '\0') {
2270 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2271 report_capture_error(sync_msg_str, "");
2272 g_free(sync_msg_str);
2274 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2275 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2278 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2279 /* to remove any suid privileges. */
2280 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2281 /* (euid/egid have already previously been set to ruid/rgid. */
2282 /* (See comment in main() for details) */
2284 relinquish_special_privs_perm();
2286 relinquish_all_capabilities();
2291 /* close the capture input file (pcap or capture pipe) */
2292 static void capture_loop_close_input(loop_data *ld)
2295 pcap_options *pcap_opts;
2297 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2299 for (i = 0; i < ld->pcaps->len; i++) {
2300 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2301 /* if open, close the capture pipe "input file" */
2302 if (pcap_opts->cap_pipe_fd >= 0) {
2303 g_assert(pcap_opts->from_cap_pipe);
2304 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2305 pcap_opts->cap_pipe_fd = -1;
2308 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2309 CloseHandle(pcap_opts->cap_pipe_h);
2310 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2313 /* if open, close the pcap "input file" */
2314 if (pcap_opts->pcap_h != NULL) {
2315 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2316 pcap_close(pcap_opts->pcap_h);
2317 pcap_opts->pcap_h = NULL;
2324 /* Shut down windows sockets */
2330 /* init the capture filter */
2331 static initfilter_status_t
2332 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2333 const gchar * name, const gchar * cfilter)
2335 struct bpf_program fcode;
2337 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2339 /* capture filters only work on real interfaces */
2340 if (cfilter && !from_cap_pipe) {
2341 /* A capture filter was specified; set it up. */
2342 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2343 /* Treat this specially - our caller might try to compile this
2344 as a display filter and, if that succeeds, warn the user that
2345 the display and capture filter syntaxes are different. */
2346 return INITFILTER_BAD_FILTER;
2348 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2349 #ifdef HAVE_PCAP_FREECODE
2350 pcap_freecode(&fcode);
2352 return INITFILTER_OTHER_ERROR;
2354 #ifdef HAVE_PCAP_FREECODE
2355 pcap_freecode(&fcode);
2359 return INITFILTER_NO_ERROR;
2363 /* set up to write to the already-opened capture output file/files */
2365 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2369 pcap_options *pcap_opts;
2370 interface_options interface_opts;
2371 gboolean successful;
2373 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2375 if ((capture_opts->use_pcapng == FALSE) &&
2376 (capture_opts->ifaces->len > 1)) {
2377 g_snprintf(errmsg, errmsg_len,
2378 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
2382 /* Set up to write to the capture file. */
2383 if (capture_opts->multi_files_on) {
2384 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2386 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2387 if (ld->pdh == NULL) {
2392 if (capture_opts->use_pcapng) {
2394 GString *os_info_str;
2396 os_info_str = g_string_new("");
2397 get_os_version_info(os_info_str);
2399 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2400 successful = pcapng_write_session_header_block(ld->pdh,
2401 (const char *)capture_opts->capture_comment, /* Comment*/
2403 os_info_str->str, /* OS*/
2405 -1, /* section_length */
2410 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2411 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2412 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2413 if (pcap_opts->from_cap_pipe) {
2414 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2416 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2418 successful = pcapng_write_interface_description_block(global_ld.pdh,
2419 NULL, /* OPT_COMMENT 1 */
2420 interface_opts.name, /* IDB_NAME 2 */
2421 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2422 interface_opts.cfilter, /* IDB_FILTER 11 */
2423 os_info_str->str, /* IDB_OS 12 */
2424 pcap_opts->linktype,
2426 &(global_ld.bytes_written),
2427 0, /* IDB_IF_SPEED 8 */
2428 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2432 g_string_free(os_info_str, TRUE);
2435 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2436 if (pcap_opts->from_cap_pipe) {
2437 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2439 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2441 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2442 pcap_opts->ts_nsec, &ld->bytes_written, &err);
2450 if (ld->pdh == NULL) {
2451 /* We couldn't set up to write to the capture file. */
2452 /* XXX - use cf_open_error_message from tshark instead? */
2457 g_snprintf(errmsg, errmsg_len,
2458 "The file to which the capture would be"
2459 " saved (\"%s\") could not be opened: Error %d.",
2460 capture_opts->save_file, err);
2462 g_snprintf(errmsg, errmsg_len,
2463 "The file to which the capture would be"
2464 " saved (\"%s\") could not be opened: %s.",
2465 capture_opts->save_file, g_strerror(err));
2477 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2481 pcap_options *pcap_opts;
2482 guint64 end_time = create_timestamp();
2484 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2486 if (capture_opts->multi_files_on) {
2487 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2489 if (capture_opts->use_pcapng) {
2490 for (i = 0; i < global_ld.pcaps->len; i++) {
2491 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2492 if (!pcap_opts->from_cap_pipe) {
2493 guint64 isb_ifrecv, isb_ifdrop;
2494 struct pcap_stat stats;
2496 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
2497 isb_ifrecv = pcap_opts->received;
2498 isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
2500 isb_ifrecv = G_MAXUINT64;
2501 isb_ifdrop = G_MAXUINT64;
2503 pcapng_write_interface_statistics_block(ld->pdh,
2506 "Counters provided by dumpcap",
2515 if (fclose(ld->pdh) == EOF) {
2516 if (err_close != NULL) {
2526 /* dispatch incoming packets (pcap or capture pipe)
2528 * Waits for incoming packets to be available, and calls pcap_dispatch()
2529 * to cause them to be processed.
2531 * Returns the number of packets which were processed.
2533 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2534 * packet-batching behaviour does not cause packets to get held back
2538 capture_loop_dispatch(loop_data *ld,
2539 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
2542 gint packet_count_before;
2543 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2548 packet_count_before = ld->packet_count;
2549 if (pcap_opts->from_cap_pipe) {
2550 /* dispatch from capture pipe */
2551 #ifdef LOG_CAPTURE_VERBOSE
2552 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2555 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
2557 if (sel_ret < 0 && errno != EINTR) {
2558 g_snprintf(errmsg, errmsg_len,
2559 "Unexpected error from select: %s", g_strerror(errno));
2560 report_capture_error(errmsg, please_report);
2565 * "select()" says we can read from the pipe without blocking
2568 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
2578 /* dispatch from pcap */
2579 #ifdef MUST_DO_SELECT
2581 * If we have "pcap_get_selectable_fd()", we use it to get the
2582 * descriptor on which to select; if that's -1, it means there
2583 * is no descriptor on which you can do a "select()" (perhaps
2584 * because you're capturing on a special device, and that device's
2585 * driver unfortunately doesn't support "select()", in which case
2586 * we don't do the select - which means it might not be possible
2587 * to stop a capture until a packet arrives. If that's unacceptable,
2588 * plead with whoever supplies the software for that device to add
2589 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2590 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2591 * later, so it can use pcap_breakloop().
2593 #ifdef LOG_CAPTURE_VERBOSE
2594 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2596 if (pcap_opts->pcap_fd != -1) {
2597 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
2600 * "select()" says we can read from it without blocking; go for
2603 * We don't have pcap_breakloop(), so we only process one packet
2604 * per pcap_dispatch() call, to allow a signal to stop the
2605 * processing immediately, rather than processing all packets
2606 * in a batch before quitting.
2609 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2611 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2615 /* Error, rather than pcap_breakloop(). */
2616 pcap_opts->pcap_err = TRUE;
2618 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2621 if (sel_ret < 0 && errno != EINTR) {
2622 g_snprintf(errmsg, errmsg_len,
2623 "Unexpected error from select: %s", g_strerror(errno));
2624 report_capture_error(errmsg, please_report);
2630 #endif /* MUST_DO_SELECT */
2632 /* dispatch from pcap without select */
2634 #ifdef LOG_CAPTURE_VERBOSE
2635 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2639 * On Windows, we don't support asynchronously telling a process to
2640 * stop capturing; instead, we check for an indication on a pipe
2641 * after processing packets. We therefore process only one packet
2642 * at a time, so that we can check the pipe after every packet.
2645 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2647 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2651 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2653 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2658 /* Error, rather than pcap_breakloop(). */
2659 pcap_opts->pcap_err = TRUE;
2661 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2663 #else /* pcap_next_ex */
2664 #ifdef LOG_CAPTURE_VERBOSE
2665 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2667 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2670 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2671 * see https://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
2672 * This should be fixed in the WinPcap 4.0 alpha release.
2674 * For reference, an example remote interface:
2675 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2678 /* emulate dispatch from pcap */
2681 struct pcap_pkthdr *pkt_header;
2686 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
2688 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2690 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2695 pcap_opts->pcap_err = TRUE;
2699 #endif /* pcap_next_ex */
2703 #ifdef LOG_CAPTURE_VERBOSE
2704 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2707 return ld->packet_count - packet_count_before;
2711 /* Isolate the Universally Unique Identifier from the interface. Basically, we
2712 * want to grab only the characters between the '{' and '}' delimiters.
2714 * Returns a GString that must be freed with g_string_free(). */
2716 isolate_uuid(const char *iface)
2721 ptr = strchr(iface, '{');
2723 return g_string_new(iface);
2724 gstr = g_string_new(ptr + 1);
2726 ptr = strchr(gstr->str, '}');
2730 gstr = g_string_truncate(gstr, ptr - gstr->str);
2735 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2736 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2738 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2739 char *errmsg, int errmsg_len)
2742 gchar *capfile_name;
2743 gchar *prefix, *suffix;
2744 gboolean is_tempfile;
2746 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2747 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
2749 if (capture_opts->save_file != NULL) {
2750 /* We return to the caller while the capture is in progress.
2751 * Therefore we need to take a copy of save_file in
2752 * case the caller destroys it after we return.
2754 capfile_name = g_strdup(capture_opts->save_file);
2756 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2757 if (capture_opts->multi_files_on) {
2758 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2759 g_snprintf(errmsg, errmsg_len,
2760 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2761 g_free(capfile_name);
2764 if (strcmp(capfile_name, "-") == 0) {
2765 /* write to stdout */
2768 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2769 _setmode(1, O_BINARY);
2772 } /* if (...output_to_pipe ... */
2775 if (capture_opts->multi_files_on) {
2776 /* ringbuffer is enabled */
2777 *save_file_fd = ringbuf_init(capfile_name,
2778 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
2779 capture_opts->group_read_access);
2781 /* we need the ringbuf name */
2782 if (*save_file_fd != -1) {
2783 g_free(capfile_name);
2784 capfile_name = g_strdup(ringbuf_current_filename());
2787 /* Try to open/create the specified file for use as a capture buffer. */
2788 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2789 (capture_opts->group_read_access) ? 0640 : 0600);
2792 is_tempfile = FALSE;
2794 /* Choose a random name for the temporary capture buffer */
2795 if (global_capture_opts.ifaces->len > 1) {
2796 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
2797 if (capture_opts->use_pcapng) {
2804 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
2806 /* use the generic portion of the interface guid to form the basis of the filename */
2807 if (strncmp("NPF_{", basename, 5)==0)
2809 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
2811 iface = isolate_uuid(basename);
2813 basename = g_strdup(iface->str);
2814 g_string_free(iface, TRUE);
2817 /* generate the temp file name prefix and suffix */
2818 if (capture_opts->use_pcapng) {
2819 prefix = g_strconcat("wireshark_", basename, NULL);
2822 prefix = g_strconcat("wireshark_", basename, NULL);
2827 *save_file_fd = create_tempfile(&tmpname, prefix, suffix);
2829 capfile_name = g_strdup(tmpname);
2833 /* did we fail to open the output file? */
2834 if (*save_file_fd == -1) {
2836 g_snprintf(errmsg, errmsg_len,
2837 "The temporary file to which the capture would be saved (\"%s\") "
2838 "could not be opened: %s.", capfile_name, g_strerror(errno));
2840 if (capture_opts->multi_files_on) {
2841 ringbuf_error_cleanup();
2844 g_snprintf(errmsg, errmsg_len,
2845 "The file to which the capture would be saved (\"%s\") "
2846 "could not be opened: %s.", capfile_name,
2849 g_free(capfile_name);
2853 if (capture_opts->save_file != NULL) {
2854 g_free(capture_opts->save_file);
2856 capture_opts->save_file = capfile_name;
2857 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2858 "g_free(capfile_name)". */
2864 /* Do the work of handling either the file size or file duration capture
2865 conditions being reached, and switching files or stopping. */
2867 do_file_switch_or_stop(capture_options *capture_opts,
2868 condition *cnd_autostop_files,
2869 condition *cnd_autostop_size,
2870 condition *cnd_file_duration)
2873 pcap_options *pcap_opts;
2874 interface_options interface_opts;
2875 gboolean successful;
2877 if (capture_opts->multi_files_on) {
2878 if (cnd_autostop_files != NULL &&
2879 cnd_eval(cnd_autostop_files, (guint64)++global_ld.autostop_files)) {
2880 /* no files left: stop here */
2881 global_ld.go = FALSE;
2885 /* Switch to the next ringbuffer file */
2886 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2887 &global_ld.save_file_fd, &global_ld.err)) {
2889 /* File switch succeeded: reset the conditions */
2890 global_ld.bytes_written = 0;
2891 if (capture_opts->use_pcapng) {
2893 GString *os_info_str;
2895 os_info_str = g_string_new("");
2896 get_os_version_info(os_info_str);
2898 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2899 successful = pcapng_write_session_header_block(global_ld.pdh,
2902 os_info_str->str, /* OS */
2904 -1, /* section_length */
2905 &(global_ld.bytes_written),
2909 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2910 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2911 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2912 successful = pcapng_write_interface_description_block(global_ld.pdh,
2913 NULL, /* OPT_COMMENT 1 */
2914 interface_opts.name, /* IDB_NAME 2 */
2915 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2916 interface_opts.cfilter, /* IDB_FILTER 11 */
2917 os_info_str->str, /* IDB_OS 12 */
2918 pcap_opts->linktype,
2920 &(global_ld.bytes_written),
2921 0, /* IDB_IF_SPEED 8 */
2922 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2926 g_string_free(os_info_str, TRUE);
2929 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
2930 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
2931 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
2934 fclose(global_ld.pdh);
2935 global_ld.pdh = NULL;
2936 global_ld.go = FALSE;
2939 if (cnd_autostop_size)
2940 cnd_reset(cnd_autostop_size);
2941 if (cnd_file_duration)
2942 cnd_reset(cnd_file_duration);
2943 fflush(global_ld.pdh);
2945 report_packet_count(global_ld.inpkts_to_sync_pipe);
2946 global_ld.inpkts_to_sync_pipe = 0;
2947 report_new_capture_file(capture_opts->save_file);
2949 /* File switch failed: stop here */
2950 global_ld.go = FALSE;
2954 /* single file, stop now */
2955 global_ld.go = FALSE;
2962 pcap_read_handler(void* arg)
2964 pcap_options *pcap_opts;
2965 char errmsg[MSG_MAX_LENGTH+1];
2967 pcap_opts = (pcap_options *)arg;
2969 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
2970 pcap_opts->interface_id);
2972 while (global_ld.go) {
2973 /* dispatch incoming packets */
2974 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
2976 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
2977 pcap_opts->interface_id);
2978 g_thread_exit(NULL);
2982 /* Do the low-level work of a capture.
2983 Returns TRUE if it succeeds, FALSE otherwise. */
2985 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
2988 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
2990 struct timeval upd_time, cur_time;
2994 condition *cnd_file_duration = NULL;
2995 condition *cnd_autostop_files = NULL;
2996 condition *cnd_autostop_size = NULL;
2997 condition *cnd_autostop_duration = NULL;
3000 gboolean cfilter_error = FALSE;
3001 char errmsg[MSG_MAX_LENGTH+1];
3002 char secondary_errmsg[MSG_MAX_LENGTH+1];
3003 pcap_options *pcap_opts;
3004 interface_options interface_opts;
3005 guint i, error_index = 0;
3008 *secondary_errmsg = '\0';
3010 /* init the loop data */
3011 global_ld.go = TRUE;
3012 global_ld.packet_count = 0;
3014 global_ld.report_packet_count = FALSE;
3016 if (capture_opts->has_autostop_packets)
3017 global_ld.packet_max = capture_opts->autostop_packets;
3019 global_ld.packet_max = 0; /* no limit */
3020 global_ld.inpkts_to_sync_pipe = 0;
3021 global_ld.err = 0; /* no error seen yet */
3022 global_ld.pdh = NULL;
3023 global_ld.autostop_files = 0;
3024 global_ld.save_file_fd = -1;
3026 /* We haven't yet gotten the capture statistics. */
3027 *stats_known = FALSE;
3029 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3030 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3032 /* open the "input file" from network interface or capture pipe */
3033 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3034 secondary_errmsg, sizeof(secondary_errmsg))) {
3037 for (i = 0; i < capture_opts->ifaces->len; i++) {
3038 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3039 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3040 /* init the input filter from the network interface (capture pipe will do nothing) */
3042 * When remote capturing WinPCap crashes when the capture filter
3043 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3046 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3047 interface_opts.name,
3048 interface_opts.cfilter?interface_opts.cfilter:"")) {
3050 case INITFILTER_NO_ERROR:
3053 case INITFILTER_BAD_FILTER:
3054 cfilter_error = TRUE;
3056 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3059 case INITFILTER_OTHER_ERROR:
3060 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3061 pcap_geterr(pcap_opts->pcap_h));
3062 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3067 /* If we're supposed to write to a capture file, open it for output
3068 (temporary/specified name/ringbuffer) */
3069 if (capture_opts->saving_to_file) {
3070 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3071 errmsg, sizeof(errmsg))) {
3075 /* set up to write to the already-opened capture output file/files */
3076 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3081 /* XXX - capture SIGTERM and close the capture, in case we're on a
3082 Linux 2.0[.x] system and you have to explicitly close the capture
3083 stream in order to turn promiscuous mode off? We need to do that
3084 in other places as well - and I don't think that works all the
3085 time in any case, due to libpcap bugs. */
3087 /* Well, we should be able to start capturing.
3089 Sync out the capture file, so the header makes it to the file system,
3090 and send a "capture started successfully and capture file created"
3091 message to our parent so that they'll open the capture file and
3092 update its windows to indicate that we have a live capture in
3094 fflush(global_ld.pdh);
3095 report_new_capture_file(capture_opts->save_file);
3098 /* initialize capture stop (and alike) conditions */
3099 init_capture_stop_conditions();
3100 /* create stop conditions */
3101 if (capture_opts->has_autostop_filesize) {
3102 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3103 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3106 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3108 if (capture_opts->has_autostop_duration)
3109 cnd_autostop_duration =
3110 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3112 if (capture_opts->multi_files_on) {
3113 if (capture_opts->has_file_duration)
3115 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3117 if (capture_opts->has_autostop_files)
3118 cnd_autostop_files =
3119 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_files);
3122 /* init the time values */
3124 upd_time = GetTickCount();
3126 gettimeofday(&upd_time, NULL);
3128 start_time = create_timestamp();
3129 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3131 /* WOW, everything is prepared! */
3132 /* please fasten your seat belts, we will enter now the actual capture loop */
3134 pcap_queue = g_async_queue_new();
3135 pcap_queue_bytes = 0;
3136 pcap_queue_packets = 0;
3137 for (i = 0; i < global_ld.pcaps->len; i++) {
3138 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3139 #if GLIB_CHECK_VERSION(2,31,0)
3140 /* XXX - Add an interface name here? */
3141 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3143 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3147 while (global_ld.go) {
3148 /* dispatch incoming packets */
3150 pcap_queue_element *queue_element;
3151 #if GLIB_CHECK_VERSION(2,31,18)
3153 g_async_queue_lock(pcap_queue);
3154 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3156 GTimeVal write_thread_time;
3158 g_get_current_time(&write_thread_time);
3159 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3160 g_async_queue_lock(pcap_queue);
3161 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3163 if (queue_element) {
3164 pcap_queue_bytes -= queue_element->phdr.caplen;
3165 pcap_queue_packets -= 1;
3167 g_async_queue_unlock(pcap_queue);
3168 if (queue_element) {
3169 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3170 "Dequeued a packet of length %d captured on interface %d.",
3171 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3173 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3174 &queue_element->phdr,
3176 g_free(queue_element->pd);
3177 g_free(queue_element);
3183 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3184 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3185 sizeof(errmsg), pcap_opts);
3188 /* Were we asked to print packet counts by the SIGINFO handler? */
3189 if (global_ld.report_packet_count) {
3190 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3191 plurality(global_ld.packet_count, "", "s"));
3192 global_ld.report_packet_count = FALSE;
3197 /* any news from our parent (signal pipe)? -> just stop the capture */
3198 if (!signal_pipe_check_running()) {
3199 global_ld.go = FALSE;
3204 global_ld.inpkts_to_sync_pipe += inpkts;
3206 /* check capture size condition */
3207 if (cnd_autostop_size != NULL &&
3208 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3209 /* Capture size limit reached, do we have another file? */
3210 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3211 cnd_autostop_size, cnd_file_duration))
3213 } /* cnd_autostop_size */
3214 if (capture_opts->output_to_pipe) {
3215 fflush(global_ld.pdh);
3219 /* Only update once every 500ms so as not to overload slow displays.
3220 * This also prevents too much context-switching between the dumpcap
3221 * and wireshark processes.
3223 #define DUMPCAP_UPD_TIME 500
3226 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3227 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3229 gettimeofday(&cur_time, NULL);
3230 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3231 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3234 upd_time = cur_time;
3237 if (pcap_stats(pch, stats) >= 0) {
3238 *stats_known = TRUE;
3241 /* Let the parent process know. */
3242 if (global_ld.inpkts_to_sync_pipe) {
3244 fflush(global_ld.pdh);
3246 /* Send our parent a message saying we've written out
3247 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3249 report_packet_count(global_ld.inpkts_to_sync_pipe);
3251 global_ld.inpkts_to_sync_pipe = 0;
3254 /* check capture duration condition */
3255 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3256 /* The maximum capture time has elapsed; stop the capture. */
3257 global_ld.go = FALSE;
3261 /* check capture file duration condition */
3262 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3263 /* duration limit reached, do we have another file? */
3264 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3265 cnd_autostop_size, cnd_file_duration))
3267 } /* cnd_file_duration */
3271 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3273 pcap_queue_element *queue_element;
3275 for (i = 0; i < global_ld.pcaps->len; i++) {
3276 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3277 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3278 pcap_opts->interface_id);
3279 g_thread_join(pcap_opts->tid);
3280 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3281 pcap_opts->interface_id);
3284 g_async_queue_lock(pcap_queue);
3285 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3286 if (queue_element) {
3287 pcap_queue_bytes -= queue_element->phdr.caplen;
3288 pcap_queue_packets -= 1;
3290 g_async_queue_unlock(pcap_queue);
3291 if (queue_element == NULL) {
3294 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3295 "Dequeued a packet of length %d captured on interface %d.",
3296 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3297 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3298 &queue_element->phdr,
3300 g_free(queue_element->pd);
3301 g_free(queue_element);
3302 global_ld.inpkts_to_sync_pipe += 1;
3303 if (capture_opts->output_to_pipe) {
3304 fflush(global_ld.pdh);
3310 /* delete stop conditions */
3311 if (cnd_file_duration != NULL)
3312 cnd_delete(cnd_file_duration);
3313 if (cnd_autostop_files != NULL)
3314 cnd_delete(cnd_autostop_files);
3315 if (cnd_autostop_size != NULL)
3316 cnd_delete(cnd_autostop_size);
3317 if (cnd_autostop_duration != NULL)
3318 cnd_delete(cnd_autostop_duration);
3320 /* did we have a pcap (input) error? */
3321 for (i = 0; i < capture_opts->ifaces->len; i++) {
3322 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3323 if (pcap_opts->pcap_err) {
3324 /* On Linux, if an interface goes down while you're capturing on it,
3325 you'll get a "recvfrom: Network is down" or
3326 "The interface went down" error (ENETDOWN).
3327 (At least you will if g_strerror() doesn't show a local translation
3330 On FreeBSD and OS X, if a network adapter disappears while
3331 you're capturing on it, you'll get a "read: Device not configured"
3332 error (ENXIO). (See previous parenthetical note.)
3334 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3336 These should *not* be reported to the Wireshark developers. */
3339 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3340 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3341 strcmp(cap_err_str, "The interface went down") == 0 ||
3342 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3343 strcmp(cap_err_str, "read: I/O error") == 0 ||
3344 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3345 report_capture_error("The network adapter on which the capture was being done "
3346 "is no longer running; the capture has stopped.",
3349 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3351 report_capture_error(errmsg, please_report);
3354 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3355 report_capture_error(errmsg, "");
3359 /* did we have an output error while capturing? */
3360 if (global_ld.err == 0) {
3363 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3364 global_ld.err, FALSE);
3365 report_capture_error(errmsg, please_report);
3369 if (capture_opts->saving_to_file) {
3370 /* close the output file */
3371 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3375 /* there might be packets not yet notified to the parent */
3376 /* (do this after closing the file, so all packets are already flushed) */
3377 if (global_ld.inpkts_to_sync_pipe) {
3379 report_packet_count(global_ld.inpkts_to_sync_pipe);
3380 global_ld.inpkts_to_sync_pipe = 0;
3383 /* If we've displayed a message about a write error, there's no point
3384 in displaying another message about an error on close. */
3385 if (!close_ok && write_ok) {
3386 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3388 report_capture_error(errmsg, "");
3392 * XXX We exhibit different behaviour between normal mode and sync mode
3393 * when the pipe is stdin and not already at EOF. If we're a child, the
3394 * parent's stdin isn't closed, so if the user starts another capture,
3395 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3396 * will say "Unrecognized libpcap format". On the other hand, in normal
3397 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3400 report_capture_count(TRUE);
3402 /* get packet drop statistics from pcap */
3403 for (i = 0; i < capture_opts->ifaces->len; i++) {
3405 guint32 pcap_dropped = 0;
3407 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3408 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3409 received = pcap_opts->received;
3410 if (pcap_opts->pcap_h != NULL) {
3411 g_assert(!pcap_opts->from_cap_pipe);
3412 /* Get the capture statistics, so we know how many packets were dropped. */
3414 * Older versions of libpcap didn't set ps_ifdrop on some
3415 * platforms; initialize it to 0 to handle that.
3417 stats->ps_ifdrop = 0;
3418 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3419 *stats_known = TRUE;
3420 /* Let the parent process know. */
3421 pcap_dropped += stats->ps_drop;
3423 g_snprintf(errmsg, sizeof(errmsg),
3424 "Can't get packet-drop statistics: %s",
3425 pcap_geterr(pcap_opts->pcap_h));
3426 report_capture_error(errmsg, please_report);
3429 report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
3432 /* close the input file (pcap or capture pipe) */
3433 capture_loop_close_input(&global_ld);
3435 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
3437 /* ok, if the write and the close were successful. */
3438 return write_ok && close_ok;
3441 if (capture_opts->multi_files_on) {
3442 /* cleanup ringbuffer */
3443 ringbuf_error_cleanup();
3445 /* We can't use the save file, and we have no FILE * for the stream
3446 to close in order to close it, so close the FD directly. */
3447 if (global_ld.save_file_fd != -1) {
3448 ws_close(global_ld.save_file_fd);
3451 /* We couldn't even start the capture, so get rid of the capture
3453 if (capture_opts->save_file != NULL) {
3454 ws_unlink(capture_opts->save_file);
3455 g_free(capture_opts->save_file);
3458 capture_opts->save_file = NULL;
3460 report_cfilter_error(capture_opts, error_index, errmsg);
3462 report_capture_error(errmsg, secondary_errmsg);
3464 /* close the input file (pcap or cap_pipe) */
3465 capture_loop_close_input(&global_ld);
3467 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3474 capture_loop_stop(void)
3476 #ifdef HAVE_PCAP_BREAKLOOP
3478 pcap_options *pcap_opts;
3480 for (i = 0; i < global_ld.pcaps->len; i++) {
3481 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3482 if (pcap_opts->pcap_h != NULL)
3483 pcap_breakloop(pcap_opts->pcap_h);
3486 global_ld.go = FALSE;
3491 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3492 int err, gboolean is_close)
3497 g_snprintf(errmsg, errmsglen,
3498 "Not all the packets could be written to the file"
3499 " to which the capture was being saved\n"
3500 "(\"%s\") because there is no space left on the file system\n"
3501 "on which that file resides.",
3507 g_snprintf(errmsg, errmsglen,
3508 "Not all the packets could be written to the file"
3509 " to which the capture was being saved\n"
3510 "(\"%s\") because you are too close to, or over,"
3511 " your disk quota\n"
3512 "on the file system on which that file resides.",
3519 g_snprintf(errmsg, errmsglen,
3520 "The file to which the capture was being saved\n"
3521 "(\"%s\") could not be closed: %s.",
3522 fname, g_strerror(err));
3524 g_snprintf(errmsg, errmsglen,
3525 "An error occurred while writing to the file"
3526 " to which the capture was being saved\n"
3528 fname, g_strerror(err));
3535 /* one packet was captured, process it */
3537 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3540 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3542 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
3544 /* We may be called multiple times from pcap_dispatch(); if we've set
3545 the "stop capturing" flag, ignore this packet, as we're not
3546 supposed to be saving any more packets. */
3547 if (!global_ld.go) {
3548 pcap_opts->flushed++;
3552 if (global_ld.pdh) {
3553 gboolean successful;
3555 /* We're supposed to write the packet to a file; do so.
3556 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3557 "ld->err" to the error. */
3558 if (global_capture_opts.use_pcapng) {
3559 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
3561 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3562 phdr->caplen, phdr->len,
3563 pcap_opts->interface_id,
3566 &global_ld.bytes_written, &err);
3568 successful = libpcap_write_packet(global_ld.pdh,
3569 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3570 phdr->caplen, phdr->len,
3572 &global_ld.bytes_written, &err);
3575 global_ld.go = FALSE;
3576 global_ld.err = err;
3577 pcap_opts->dropped++;
3579 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3580 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3581 "Wrote a packet of length %d captured on interface %u.",
3582 phdr->caplen, pcap_opts->interface_id);
3584 global_ld.packet_count++;
3585 pcap_opts->received++;
3586 /* if the user told us to stop after x packets, do we already have enough? */
3587 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
3588 global_ld.go = FALSE;
3594 /* one packet was captured, queue it */
3596 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3599 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3600 pcap_queue_element *queue_element;
3601 gboolean limit_reached;
3603 /* We may be called multiple times from pcap_dispatch(); if we've set
3604 the "stop capturing" flag, ignore this packet, as we're not
3605 supposed to be saving any more packets. */
3606 if (!global_ld.go) {
3607 pcap_opts->flushed++;
3611 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
3612 if (queue_element == NULL) {
3613 pcap_opts->dropped++;
3616 queue_element->pcap_opts = pcap_opts;
3617 queue_element->phdr = *phdr;
3618 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
3619 if (queue_element->pd == NULL) {
3620 pcap_opts->dropped++;
3621 g_free(queue_element);
3624 memcpy(queue_element->pd, pd, phdr->caplen);
3625 g_async_queue_lock(pcap_queue);
3626 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
3627 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
3628 limit_reached = FALSE;
3629 g_async_queue_push_unlocked(pcap_queue, queue_element);
3630 pcap_queue_bytes += phdr->caplen;
3631 pcap_queue_packets += 1;
3633 limit_reached = TRUE;
3635 g_async_queue_unlock(pcap_queue);
3636 if (limit_reached) {
3637 pcap_opts->dropped++;
3638 g_free(queue_element->pd);
3639 g_free(queue_element);
3640 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3641 "Dropped a packet of length %d captured on interface %u.",
3642 phdr->caplen, pcap_opts->interface_id);
3644 pcap_opts->received++;
3645 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3646 "Queued a packet of length %d captured on interface %u.",
3647 phdr->caplen, pcap_opts->interface_id);
3649 /* I don't want to hold the mutex over the debug output. So the
3650 output may be wrong */
3651 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3652 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
3653 pcap_queue_bytes, pcap_queue_packets);
3657 set_80211_channel(const char *iface, const char *opt)
3661 int center_freq1 = -1;
3662 int center_freq2 = -1;
3665 gchar **options = NULL;
3667 options = g_strsplit_set(opt, ",", 4);
3668 for (args = 0; options[args]; args++);
3671 freq = atoi(options[0]);
3673 if (args >= 1 && options[1]) {
3674 type = ws80211_str_to_chan_type(options[1]);
3681 if (args >= 2 && options[2])
3682 center_freq1 = atoi(options[2]);
3684 if (args >= 3 && options[3])
3685 center_freq2 = atoi(options[3]);
3687 ret = ws80211_init();
3689 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
3693 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
3696 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
3702 pipe_write_block(2, SP_SUCCESS, NULL);
3706 g_strfreev(options);
3711 get_dumpcap_compiled_info(GString *str)
3713 /* Capture libraries */
3714 g_string_append(str, ", ");
3715 get_compiled_caplibs_version(str);
3719 get_dumpcap_runtime_info(GString *str)
3721 /* Capture libraries */
3722 g_string_append(str, ", ");
3723 get_runtime_caplibs_version(str);
3726 /* And now our feature presentation... [ fade to music ] */
3728 main(int argc, char *argv[])
3730 GString *comp_info_str;
3731 GString *runtime_info_str;
3733 static const struct option long_options[] = {
3734 {"help", no_argument, NULL, 'h'},
3735 {"version", no_argument, NULL, 'v'},
3736 LONGOPT_CAPTURE_COMMON
3740 gboolean arg_error = FALSE;
3745 struct sigaction action, oldaction;
3748 gboolean start_capture = TRUE;
3749 gboolean stats_known;
3750 struct pcap_stat stats;
3751 GLogLevelFlags log_flags;
3752 gboolean list_interfaces = FALSE;
3753 gboolean list_link_layer_types = FALSE;
3754 #ifdef HAVE_BPF_IMAGE
3755 gboolean print_bpf_code = FALSE;
3757 gboolean set_chan = FALSE;
3758 gchar *set_chan_arg = NULL;
3759 gboolean machine_readable = FALSE;
3760 gboolean print_statistics = FALSE;
3761 int status, run_once_args = 0;
3764 #if defined(__APPLE__) && defined(__LP64__)
3765 struct utsname osinfo;
3769 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
3771 /* Get the compile-time version information string */
3772 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
3774 /* Get the run-time version information string */
3775 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
3777 /* Add it to the information to be reported on a crash. */
3778 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
3783 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
3786 arg_list_utf_16to8(argc, argv);
3787 create_app_running_mutex();
3790 * Initialize our DLL search path. MUST be called before LoadLibrary
3793 ws_init_dll_search_path();
3796 #ifdef HAVE_BPF_IMAGE
3797 #define OPTSTRING_d "d"
3799 #define OPTSTRING_d ""
3802 #ifdef HAVE_PCAP_REMOTE
3803 #define OPTSTRING_r "r"
3804 #define OPTSTRING_u "u"
3806 #define OPTSTRING_r ""
3807 #define OPTSTRING_u ""
3810 #ifdef HAVE_PCAP_SETSAMPLING
3811 #define OPTSTRING_m "m:"
3813 #define OPTSTRING_m ""
3816 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
3818 #ifdef DEBUG_CHILD_DUMPCAP
3819 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3820 fprintf (stderr, "Unable to open debug log file .\n");
3825 #if defined(__APPLE__) && defined(__LP64__)
3827 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
3828 * a bug workaround - timeouts less than 1 second don't work with libpcap
3829 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3830 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
3831 * The problem is extremely unlikely to be reintroduced in a future
3834 if (uname(&osinfo) == 0) {
3836 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
3837 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3838 * number of 10.0.0, not 10.1.0 - go figure).
3840 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
3841 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
3842 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
3843 need_timeout_workaround = TRUE;
3848 * Determine if dumpcap is being requested to run in a special
3849 * capture_child mode by going thru the command line args to see if
3850 * a -Z is present. (-Z is a hidden option).
3852 * The primary result of running in capture_child mode is that
3853 * all messages sent out on stderr are in a special type/len/string
3854 * format to allow message processing by type. These messages include
3855 * error messages if dumpcap fails to start the operation it was
3856 * requested to do, as well as various "status" messages which are sent
3857 * when an actual capture is in progress, and a "success" message sent
3858 * if dumpcap was requested to perform an operation other than a
3861 * Capture_child mode would normally be requested by a parent process
3862 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3863 * to which dumpcap stderr has been redirected. It might also have
3864 * another pipe to obtain dumpcap stdout output; for operations other
3865 * than a capture, that information is formatted specially for easier
3866 * parsing by the parent process.
3868 * Capture_child mode needs to be determined immediately upon
3869 * startup so that any messages generated by dumpcap in this mode
3870 * (eg: during initialization) will be formatted properly.
3873 for (i=1; i<argc; i++) {
3874 if (strcmp("-Z", argv[i]) == 0) {
3875 capture_child = TRUE;
3876 machine_readable = TRUE; /* request machine-readable output */
3878 /* set output pipe to binary mode, to avoid ugly text conversions */
3879 _setmode(2, O_BINARY);
3884 /* The default_log_handler will use stdout, which makes trouble in */
3885 /* capture child mode, as it uses stdout for its sync_pipe. */
3886 /* So: the filtering is done in the console_log_handler and not here.*/
3887 /* We set the log handlers right up front to make sure that any log */
3888 /* messages when running as child will be sent back to the parent */
3889 /* with the correct format. */
3894 G_LOG_LEVEL_CRITICAL|
3895 G_LOG_LEVEL_WARNING|
3896 G_LOG_LEVEL_MESSAGE|
3900 G_LOG_FLAG_RECURSION);
3902 g_log_set_handler(NULL,
3904 console_log_handler, NULL /* user_data */);
3905 g_log_set_handler(LOG_DOMAIN_MAIN,
3907 console_log_handler, NULL /* user_data */);
3908 g_log_set_handler(LOG_DOMAIN_CAPTURE,
3910 console_log_handler, NULL /* user_data */);
3911 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3913 console_log_handler, NULL /* user_data */);
3915 /* Initialize the pcaps list */
3916 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
3918 #if !GLIB_CHECK_VERSION(2,31,0)
3919 /* Initialize the thread system */
3920 g_thread_init(NULL);
3924 /* Load wpcap if possible. Do this before collecting the run-time version information */
3927 /* ... and also load the packet.dll from wpcap */
3928 /* XXX - currently not required, may change later. */
3929 /*wpcap_packet_load();*/
3931 /* Start windows sockets */
3932 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3934 /* Set handler for Ctrl+C key */
3935 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3937 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3938 and exit. Do the same with SIGPIPE, in case, for example,
3939 we're writing to our standard output and it's a pipe.
3940 Do the same with SIGHUP if it's not being ignored (if we're
3941 being run under nohup, it might be ignored, in which case we
3942 should leave it ignored).
3944 XXX - apparently, Coverity complained that part of action
3945 wasn't initialized. Perhaps it's running on Linux, where
3946 struct sigaction has an ignored "sa_restorer" element and
3947 where "sa_handler" and "sa_sigaction" might not be two
3948 members of a union. */
3949 memset(&action, 0, sizeof(action));
3950 action.sa_handler = capture_cleanup_handler;
3952 * Arrange that system calls not get restarted, because when
3953 * our signal handler returns we don't want to restart
3954 * a call that was waiting for packets to arrive.
3956 action.sa_flags = 0;
3957 sigemptyset(&action.sa_mask);
3958 sigaction(SIGTERM, &action, NULL);
3959 sigaction(SIGINT, &action, NULL);
3960 sigaction(SIGPIPE, &action, NULL);
3961 sigaction(SIGHUP, NULL, &oldaction);
3962 if (oldaction.sa_handler == SIG_DFL)
3963 sigaction(SIGHUP, &action, NULL);
3966 /* Catch SIGINFO and, if we get it and we're capturing in
3967 quiet mode, report the number of packets we've captured. */
3968 action.sa_handler = report_counts_siginfo;
3969 action.sa_flags = SA_RESTART;
3970 sigemptyset(&action.sa_mask);
3971 sigaction(SIGINFO, &action, NULL);
3972 #endif /* SIGINFO */
3976 enable_kernel_bpf_jit_compiler();
3979 /* ----------------------------------------------------------------- */
3980 /* Privilege and capability handling */
3982 /* 1. Running not as root or suid root; no special capabilities. */
3985 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
3988 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
3990 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3991 /* capabilities; Drop all other capabilities; */
3992 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3993 /* else: after pcap_open_live() in capture_loop_open_input() */
3994 /* drop all capabilities (NET_RAW and NET_ADMIN); */
3995 /* (Note: this means that the process, although logged in */
3996 /* as root, does not have various permissions such as the */
3997 /* ability to bypass file access permissions). */
3998 /* XXX: Should we just leave capabilities alone in this case */
3999 /* so that user gets expected effect that root can do */
4002 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4004 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4005 /* else: after pcap_open_live() in capture_loop_open_input() */
4006 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4007 /* pcap_open_live). */
4009 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4011 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4012 /* capabilities; Drop all other capabilities; */
4013 /* Drop suid privileges (euid=ruid); */
4014 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4015 /* else: after pcap_open_live() in capture_loop_open_input() */
4016 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4018 /* XXX: For some Linux versions/distros with capabilities */
4019 /* a 'normal' process with any capabilities cannot be */
4020 /* 'killed' (signaled) from another (same uid) non-privileged */
4022 /* For example: If (non-suid) Wireshark forks a */
4023 /* child suid dumpcap which acts as described here (case 5), */
4024 /* Wireshark will be unable to kill (signal) the child */
4025 /* dumpcap process until the capabilities have been dropped */
4026 /* (after pcap_open_live()). */
4027 /* This behaviour will apparently be changed in the kernel */
4028 /* to allow the kill (signal) in this case. */
4029 /* See the following for details: */
4030 /* https://www.mail-archive.com/ [wrapped] */
4031 /* linux-security-module@vger.kernel.org/msg02913.html */
4033 /* It is therefore conceivable that if dumpcap somehow hangs */
4034 /* in pcap_open_live or before that wireshark will not */
4035 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4036 /* In this case, exiting wireshark will kill the child */
4037 /* dumpcap process. */
4039 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4040 /* capabilities; Using libcap. Note: capset cmd (which see) */
4041 /* used to assign capabilities to file. */
4043 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4044 /* else: after pcap_open_live() in capture_loop_open_input() */
4045 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4047 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4048 /* longer required (similar to capture). */
4050 /* ----------------------------------------------------------------- */
4052 init_process_policies();
4055 /* If 'started with special privileges' (and using libcap) */
4056 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4057 /* Set euid/egid = ruid/rgid to remove suid privileges */
4058 relinquish_privs_except_capture();
4061 /* Set the initial values in the capture options. This might be overwritten
4062 by the command line parameters. */
4063 capture_opts_init(&global_capture_opts);
4064 /* We always save to a file - if no file was specified, we save to a
4066 global_capture_opts.saving_to_file = TRUE;
4067 global_capture_opts.has_ring_num_files = TRUE;
4069 /* Pass on capture_child mode for capture_opts */
4070 global_capture_opts.capture_child = capture_child;
4072 /* Now get our args */
4073 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4075 case 'h': /* Print help and exit */
4076 printf("Dumpcap (Wireshark) %s\n"
4077 "Capture network packets and dump them into a pcapng or pcap file.\n"
4078 "See https://www.wireshark.org for more information.\n",
4079 get_ws_vcs_version_info());
4080 print_usage(stdout);
4083 case 'v': /* Show version and exit */
4085 show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4086 g_string_free(comp_info_str, TRUE);
4087 g_string_free(runtime_info_str, TRUE);
4091 /*** capture option specific ***/
4092 case 'a': /* autostop criteria */
4093 case 'b': /* Ringbuffer option */
4094 case 'c': /* Capture x packets */
4095 case 'f': /* capture filter */
4096 case 'g': /* enable group read access on file(s) */
4097 case 'i': /* Use interface x */
4098 case 'n': /* Use pcapng format */
4099 case 'p': /* Don't capture in promiscuous mode */
4100 case 'P': /* Use pcap format */
4101 case 's': /* Set the snapshot (capture) length */
4102 case 'w': /* Write to capture file x */
4103 case 'y': /* Set the pcap data link type */
4104 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4105 #ifdef HAVE_PCAP_REMOTE
4106 case 'u': /* Use UDP for data transfer */
4107 case 'r': /* Capture own RPCAP traffic too */
4108 case 'A': /* Authentication */
4110 #ifdef HAVE_PCAP_SETSAMPLING
4111 case 'm': /* Sampling */
4113 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4114 case 'B': /* Buffer size */
4116 #ifdef HAVE_PCAP_CREATE
4117 case 'I': /* Monitor mode */
4119 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4124 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4126 capture_child = TRUE;
4128 /* set output pipe to binary mode, to avoid ugly text conversions */
4129 _setmode(2, O_BINARY);
4131 * optarg = the control ID, aka the PPID, currently used for the
4134 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4135 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4136 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4137 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4139 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4140 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4141 "Signal pipe: Unable to open %s. Dead parent?",
4149 case 'q': /* Quiet */
4155 /*** all non capture option specific ***/
4156 case 'D': /* Print a list of capture devices and exit */
4157 if (!list_interfaces) {
4158 list_interfaces = TRUE;
4162 case 'L': /* Print list of link-layer types and exit */
4163 if (!list_link_layer_types) {
4164 list_link_layer_types = TRUE;
4168 #ifdef HAVE_BPF_IMAGE
4169 case 'd': /* Print BPF code for capture filter and exit */
4170 if (!print_bpf_code) {
4171 print_bpf_code = TRUE;
4176 case 'S': /* Print interface statistics once a second */
4177 if (!print_statistics) {
4178 print_statistics = TRUE;
4182 case 'k': /* Set wireless channel */
4185 set_chan_arg = optarg;
4188 cmdarg_err("Only one -k flag may be specified");
4192 case 'M': /* For -D, -L, and -S, print machine-readable output */
4193 machine_readable = TRUE;
4196 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4199 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4202 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4204 case '?': /* Bad flag - print usage message */
4213 /* user specified file name as regular command-line argument */
4214 /* XXX - use it as the capture file name (or something else)? */
4220 * Extra command line arguments were specified; complain.
4221 * XXX - interpret as capture filter, as tcpdump and tshark do?
4223 cmdarg_err("Invalid argument: %s", argv[0]);
4228 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4231 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4232 /* Use some default if the user hasn't specified some */
4233 /* XXX: Are these defaults good enough? */
4234 pcap_queue_byte_limit = 1000 * 1000;
4235 pcap_queue_packet_limit = 1000;
4238 print_usage(stderr);
4242 if (run_once_args > 1) {
4243 #ifdef HAVE_BPF_IMAGE
4244 cmdarg_err("Only one of -D, -L, -d, -k, or -S may be supplied.");
4246 cmdarg_err("Only one of -D, -L, -k, or -S may be supplied.");
4249 } else if (run_once_args == 1) {
4250 /* We're supposed to print some information, rather than
4251 to capture traffic; did they specify a ring buffer option? */
4252 if (global_capture_opts.multi_files_on) {
4253 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4257 /* We're supposed to capture traffic; */
4259 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4260 if (global_capture_opts.ifaces->len > 1) {
4262 global_capture_opts.use_pcapng = TRUE;
4265 if (global_capture_opts.capture_comment &&
4266 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4267 /* XXX - for ringbuffer, should we apply the comment to each file? */
4268 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4272 /* Was the ring buffer option specified and, if so, does it make sense? */
4273 if (global_capture_opts.multi_files_on) {
4274 /* Ring buffer works only under certain conditions:
4275 a) ring buffer does not work with temporary files;
4276 b) it makes no sense to enable the ring buffer if the maximum
4277 file size is set to "infinite". */
4278 if (global_capture_opts.save_file == NULL) {
4279 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4280 global_capture_opts.multi_files_on = FALSE;
4282 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4283 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4285 /* XXX - this must be redesigned as the conditions changed */
4286 global_capture_opts.multi_files_on = FALSE;
4293 * "-D" requires no interface to be selected; it's supposed to list
4296 if (list_interfaces) {
4297 /* Get the list of interfaces */
4302 if_list = capture_interface_list(&err, &err_str,NULL);
4303 if (if_list == NULL) {
4306 * If we're being run by another program, just give them
4307 * an empty list of interfaces, don't report this as
4308 * an error; that lets them decide whether to report
4309 * this as an error or not.
4311 if (!machine_readable) {
4312 cmdarg_err("There are no interfaces on which a capture can be done");
4316 cmdarg_err("%s", err_str);
4322 if (machine_readable) /* tab-separated values to stdout */
4323 print_machine_readable_interfaces(if_list);
4325 capture_opts_print_interfaces(if_list);
4326 free_interface_list(if_list);
4331 * "-S" requires no interface to be selected; it gives statistics
4332 * for all interfaces.
4334 if (print_statistics) {
4335 status = print_statistics_loop(machine_readable);
4340 interface_options interface_opts;
4342 if (global_capture_opts.ifaces->len != 1) {
4343 cmdarg_err("Need one interface");
4347 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4348 status = set_80211_channel(interface_opts.name, set_chan_arg);
4353 * "-L", "-d", and capturing act on a particular interface, so we have to
4354 * have an interface; if none was specified, pick a default.
4356 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4358 /* cmdarg_err() already called .... */
4362 if (list_link_layer_types) {
4363 /* Get the list of link-layer types for the capture device. */
4364 if_capabilities_t *caps;
4368 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4369 interface_options interface_opts;
4371 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4373 caps = get_if_capabilities(&interface_opts, &err_str);
4375 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4376 "Please check to make sure you have sufficient permissions, and that\n"
4377 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4381 if (caps->data_link_types == NULL) {
4382 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4385 if (machine_readable) /* tab-separated values to stdout */
4386 /* XXX: We need to change the format and adopt consumers */
4387 print_machine_readable_if_capabilities(caps);
4389 /* XXX: We might want to print also the interface name */
4390 capture_opts_print_if_capabilities(caps, interface_opts.name,
4391 interface_opts.monitor_mode);
4392 free_if_capabilities(caps);
4397 /* We're supposed to do a capture, or print the BPF code for a filter. */
4399 /* Let the user know what interfaces were chosen. */
4400 if (capture_child) {
4401 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4402 interface_options interface_opts;
4404 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4405 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4406 interface_opts.name);
4409 str = g_string_new("");
4411 if (global_capture_opts.ifaces->len < 2)
4413 if (global_capture_opts.ifaces->len < 4)
4416 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4417 interface_options interface_opts;
4419 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4421 if (global_capture_opts.ifaces->len > 2) {
4422 g_string_append_printf(str, ",");
4424 g_string_append_printf(str, " ");
4425 if (j == global_capture_opts.ifaces->len - 1) {
4426 g_string_append_printf(str, "and ");
4429 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4432 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4434 fprintf(stderr, "Capturing on %s\n", str->str);
4435 g_string_free(str, TRUE);
4438 /* Process the snapshot length, as that affects the generated BPF code. */
4439 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4441 #ifdef HAVE_BPF_IMAGE
4442 if (print_bpf_code) {
4443 show_filter_code(&global_capture_opts);
4448 /* We're supposed to do a capture. Process the ring buffer arguments. */
4449 capture_opts_trim_ring_num_files(&global_capture_opts);
4451 /* flush stderr prior to starting the main capture loop */
4454 /* Now start the capture. */
4455 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4459 /* capture failed */
4462 return 0; /* never here, make compiler happy */
4467 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4468 const char *message, gpointer user_data _U_)
4475 /* ignore log message, if log_level isn't interesting */
4476 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4477 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4482 /* create a "timestamp" */
4484 today = localtime(&curr);
4486 switch(log_level & G_LOG_LEVEL_MASK) {
4487 case G_LOG_LEVEL_ERROR:
4490 case G_LOG_LEVEL_CRITICAL:
4493 case G_LOG_LEVEL_WARNING:
4496 case G_LOG_LEVEL_MESSAGE:
4499 case G_LOG_LEVEL_INFO:
4502 case G_LOG_LEVEL_DEBUG:
4506 fprintf(stderr, "unknown log_level %d\n", log_level);
4508 g_assert_not_reached();
4511 /* Generate the output message */
4512 if (log_level & G_LOG_LEVEL_MESSAGE) {
4513 /* normal user messages without additional infos */
4514 msg = g_strdup_printf("%s\n", message);
4516 /* info/debug messages with additional infos */
4517 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4518 today->tm_hour, today->tm_min, today->tm_sec,
4519 log_domain != NULL ? log_domain : "",
4523 /* DEBUG & INFO msgs (if we're debugging today) */
4524 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4525 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4526 #ifdef DEBUG_DUMPCAP
4527 fprintf(stderr, "%s", msg);
4530 #ifdef DEBUG_CHILD_DUMPCAP
4531 fprintf(debug_log, "%s", msg);
4539 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4540 /* to parent especially formatted if dumpcap running as child. */
4541 if (capture_child) {
4542 sync_pipe_errmsg_to_parent(2, msg, "");
4544 fprintf(stderr, "%s", msg);
4551 /****************************************************************************************************************/
4552 /* indication report routines */
4556 report_packet_count(unsigned int packet_count)
4558 char tmp[SP_DECISIZE+1+1];
4559 static unsigned int count = 0;
4561 if (capture_child) {
4562 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
4563 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4564 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4566 count += packet_count;
4567 fprintf(stderr, "\rPackets: %u ", count);
4568 /* stderr could be line buffered */
4574 report_new_capture_file(const char *filename)
4576 if (capture_child) {
4577 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4578 pipe_write_block(2, SP_FILE, filename);
4582 * Prevent a SIGINFO handler from writing to the standard error
4583 * while we're doing so; instead, have it just set a flag telling
4584 * us to print that information when we're done.
4587 #endif /* SIGINFO */
4588 fprintf(stderr, "File: %s\n", filename);
4589 /* stderr could be line buffered */
4594 * Allow SIGINFO handlers to write.
4599 * If a SIGINFO handler asked us to write out capture counts, do so.
4602 report_counts_for_siginfo();
4603 #endif /* SIGINFO */
4608 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4610 interface_options interface_opts;
4611 char tmp[MSG_MAX_LENGTH+1+6];
4613 if (i < capture_opts->ifaces->len) {
4614 if (capture_child) {
4615 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4616 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4617 pipe_write_block(2, SP_BAD_FILTER, tmp);
4620 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
4621 * the error message below.
4623 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
4625 "Invalid capture filter \"%s\" for interface '%s'.\n"
4627 "That string isn't a valid capture filter (%s).\n"
4628 "See the User's Guide for a description of the capture filter syntax.",
4629 interface_opts.cfilter, interface_opts.name, errmsg);
4635 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4637 if (capture_child) {
4638 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4639 "Primary Error: %s", error_msg);
4640 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4641 "Secondary Error: %s", secondary_error_msg);
4642 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4644 cmdarg_err("%s", error_msg);
4645 if (secondary_error_msg[0] != '\0')
4646 cmdarg_err_cont("%s", secondary_error_msg);
4651 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
4653 char tmp[SP_DECISIZE+1+1];
4654 guint32 total_drops = pcap_drops + drops + flushed;
4656 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
4658 if (capture_child) {
4659 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4660 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
4661 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
4662 /* XXX: Need to provide interface id, changes to consumers required. */
4663 pipe_write_block(2, SP_DROPS, tmp);
4666 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
4667 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
4668 received ? 100.0 * received / (received + total_drops) : 0.0);
4669 /* stderr could be line buffered */
4675 /************************************************************************************************/
4676 /* signal_pipe handling */
4681 signal_pipe_check_running(void)
4683 /* any news from our parent? -> just stop the capture */
4687 /* if we are running standalone, no check required */
4688 if (!capture_child) {
4692 if (!sig_pipe_name || !sig_pipe_handle) {
4693 /* This shouldn't happen */
4694 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4695 "Signal pipe: No name or handle");
4700 * XXX - We should have the process ID of the parent (from the "-Z" flag)
4701 * at this point. Should we check to see if the parent is still alive,
4702 * e.g. by using OpenProcess?
4705 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
4707 if (!result || avail > 0) {
4708 /* peek failed or some bytes really available */
4709 /* (if not piping from stdin this would fail) */
4710 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4711 "Signal pipe: Stop capture: %s", sig_pipe_name);
4712 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4713 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
4714 sig_pipe_handle, result, avail);
4717 /* pipe ok and no bytes available */
4724 * Editor modelines - https://www.wireshark.org/tools/modelines.html
4729 * indent-tabs-mode: nil
4732 * vi: set shiftwidth=4 tabstop=8 expandtab:
4733 * :indentSize=4:tabSize=8:noTabs=true: