3 * Wireshark - Network traffic analyzer
4 * By Gerald Combs <gerald@wireshark.org>
5 * Copyright 1998 Gerald Combs
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 #include <stdlib.h> /* for exit() */
30 #ifdef HAVE_SYS_TYPES_H
31 # include <sys/types.h>
34 #ifdef HAVE_SYS_SOCKET_H
35 #include <sys/socket.h>
38 #ifdef HAVE_NETINET_IN_H
39 #include <netinet/in.h>
46 #ifdef HAVE_ARPA_INET_H
47 #include <arpa/inet.h>
50 #if defined(__APPLE__) && defined(__LP64__)
51 #include <sys/utsname.h>
57 #include <wsutil/cmdarg_err.h>
58 #include <wsutil/crash_info.h>
59 #include <wsutil/strtoi.h>
60 #include <ws_version_info.h>
62 #ifndef HAVE_GETOPT_LONG
63 #include "wsutil/wsgetopt.h"
71 # include <sys/prctl.h>
72 # include <sys/capability.h>
75 #include "ringbuffer.h"
77 #include "caputils/capture_ifinfo.h"
78 #include "caputils/capture-pcap-util.h"
79 #include "caputils/capture-pcap-util-int.h"
81 #include "caputils/capture-wpcap.h"
84 #include "writecap/pcapio.h"
87 #include <wsutil/unicode-utils.h>
94 #include <wsutil/clopts_common.h>
95 #include <wsutil/privileges.h>
97 #include "sync_pipe.h"
99 #include "capture_opts.h"
100 #include <capchild/capture_session.h>
101 #include <capchild/capture_sync.h>
103 #include "conditions.h"
104 #include "capture_stop_conditions.h"
106 #include "wsutil/tempfile.h"
108 #include "wsutil/file_util.h"
109 #include "wsutil/cpu_info.h"
110 #include "wsutil/os_version_info.h"
111 #include "wsutil/str_util.h"
112 #include "wsutil/inet_addr.h"
114 #include "caputils/ws80211_utils.h"
121 * Get information about libpcap format from "wiretap/libpcap.h".
122 * Get information about pcapng format from "wiretap/pcapng_module.h".
123 * XXX - can we just use pcap_open_offline() to read the pipe?
125 #include "wiretap/libpcap.h"
126 #include "wiretap/pcapng_module.h"
128 /**#define DEBUG_DUMPCAP**/
129 /**#define DEBUG_CHILD_DUMPCAP**/
133 #include <conio.h> /* _getch() */
137 #ifdef DEBUG_CHILD_DUMPCAP
138 FILE *debug_log; /* for logging debug messages to */
139 /* a file if DEBUG_CHILD_DUMPCAP */
143 static GAsyncQueue *pcap_queue;
144 static gint64 pcap_queue_bytes;
145 static gint64 pcap_queue_packets;
146 static gint64 pcap_queue_byte_limit = 0;
147 static gint64 pcap_queue_packet_limit = 0;
149 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
151 static gchar *sig_pipe_name = NULL;
152 static HANDLE sig_pipe_handle = NULL;
153 static gboolean signal_pipe_check_running(void);
157 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
158 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
161 /** Stop a low-level capture (stops the capture child). */
162 static void capture_loop_stop(void);
163 /** Close a pipe, or socket if \a from_socket is TRUE */
164 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
168 * Enable kernel BPF JIT compiler if available.
169 * If any calls fail, just drive on - the JIT compiler might not be
170 * enabled, but filtering will still work, and it's not clear what
171 * we could do if the calls fail; should we just report the error
172 * and not continue to capture, should we report it as a warning, or
176 enable_kernel_bpf_jit_compiler(void)
180 static const char file[] = "/proc/sys/net/core/bpf_jit_enable";
182 fd = ws_open(file, O_WRONLY);
186 written = ws_write(fd, "1", strlen("1"));
192 #if !defined (__linux__)
193 #ifndef HAVE_PCAP_BREAKLOOP
195 * We don't have pcap_breakloop(), which is the only way to ensure that
196 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
197 * won't, if the call to read the next packet or batch of packets is
198 * is interrupted by a signal on UN*X, just go back and try again to
201 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
202 * the signal handler, set a flag to stop capturing; however, without
203 * a guarantee of that sort, we can't guarantee that we'll stop capturing
204 * if the read will be retried and won't time out if no packets arrive.
206 * Therefore, on at least some platforms, we work around the lack of
207 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
208 * to wait for packets to arrive, so that we're probably going to be
209 * blocked in the select() when the signal arrives, and can just bail
210 * out of the loop at that point.
212 * However, we don't want to do that on BSD (because "select()" doesn't work
213 * correctly on BPF devices on at least some releases of some flavors of
214 * BSD), and we don't want to do it on Windows (because "select()" is
215 * something for sockets, not for arbitrary handles). (Note that "Windows"
216 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
217 * using WinPcap, not a UNIX libpcap.)
219 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
220 * on BSD times out even if no packets have arrived, so we'll eventually
221 * exit pcap_dispatch() with an indication that no packets have arrived,
222 * and will break out of the capture loop at that point.
224 * On Windows, we can't send a SIGINT to stop capturing, so none of this
225 * applies in any case.
227 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
228 * want to include it if it's not present on this platform, however.
230 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
231 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
233 # define MUST_DO_SELECT
234 # endif /* avoid select */
235 #endif /* HAVE_PCAP_BREAKLOOP */
237 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
238 * in pcap_dispatch(); on the other hand, select() works just fine there.
239 * Hence we use a select for that come what may.
241 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
242 * internally, and, with TPACKET_V3, once that's supported, it'll
243 * support timeouts, at least as I understand the way the code works.
245 #define MUST_DO_SELECT
248 /** init the capture filter */
251 INITFILTER_BAD_FILTER,
252 INITFILTER_OTHER_ERROR
253 } initfilter_status_t;
256 STATE_EXPECT_REC_HDR,
270 * A source of packets from which we're capturing.
272 typedef struct _capture_src {
277 #ifdef MUST_DO_SELECT
278 int pcap_fd; /**< pcap file descriptor */
285 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
286 /**< capture pipe (unix only "input file") */
287 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
288 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
289 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
290 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
292 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
294 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
295 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
296 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
297 char * cap_pipe_databuf; /**< Pointer to the data buffer we've allocated */
298 size_t cap_pipe_databuf_size; /**< Current size of the data buffer */
299 guint cap_pipe_max_pkt_size; /**< Maximum packet size allowed */
301 char * cap_pipe_buf; /**< Pointer to the buffer we read into */
302 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
303 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
305 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
306 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
308 cap_pipe_state_t cap_pipe_state;
309 cap_pipe_err_t cap_pipe_err;
312 GMutex *cap_pipe_read_mtx;
313 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
318 * Global capture loop state.
320 typedef struct _loop_data {
322 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
323 int err; /**< if non-zero, error seen while capturing */
324 gint packet_count; /**< Number of packets we have already captured */
325 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
326 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
328 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
330 GArray *pcaps; /**< Array of capture_src's on which we're capturing */
334 guint64 bytes_written;
335 guint32 autostop_files;
338 typedef struct _pcap_queue_element {
339 capture_src *pcap_src;
340 struct pcap_pkthdr phdr;
342 } pcap_queue_element;
345 * Standard secondary message for unexpected errors.
347 static const char please_report[] =
348 "Please report this to the Wireshark developers.\n"
349 "https://bugs.wireshark.org/\n"
350 "(This is not a crash; please do not report it as such.)";
353 * This needs to be static, so that the SIGINT handler can clear the "go"
356 static loop_data global_ld;
359 * Timeout, in milliseconds, for reads from the stream of captured packets
360 * from a capture device.
362 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
363 * 64-bit applications, with sub-second timeouts not to work. The bug is
364 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
366 #if defined(__APPLE__) && defined(__LP64__)
367 static gboolean need_timeout_workaround;
369 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
371 #define CAP_READ_TIMEOUT 250
375 * Timeout, in microseconds, for reads from the stream of captured packets
376 * from a pipe. Pipes don't have the same problem that BPF devices do
377 * in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
378 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
379 * of the offending versions of Snow Leopard.
381 * On Windows this value is converted to milliseconds and passed to
382 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
383 * will return immediately.
386 #define PIPE_READ_TIMEOUT 100000
388 #define PIPE_READ_TIMEOUT 250000
391 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
394 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
395 const char *message, gpointer user_data _U_);
397 /* capture related options */
398 static capture_options global_capture_opts;
399 static gboolean quiet = FALSE;
400 static gboolean use_threads = FALSE;
401 static guint64 start_time;
403 static void capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
405 static void capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
407 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
408 int err, gboolean is_close);
410 static void WS_NORETURN exit_main(int err);
412 static void report_new_capture_file(const char *filename);
413 static void report_packet_count(unsigned int packet_count);
414 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
415 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
416 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
418 #define MSG_MAX_LENGTH 4096
420 /* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
422 create_timestamp(void) {
432 * Current time, represented as 100-nanosecond intervals since
433 * January 1, 1601, 00:00:00 UTC.
435 * I think DWORD might be signed, so cast both parts of "now"
436 * to guint32 so that the sign bit doesn't get treated specially.
438 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
439 * might want to use instead.
441 GetSystemTimeAsFileTime(&now);
442 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
443 (guint32)now.dwLowDateTime;
446 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
452 * Subtract difference, in microseconds, between January 1, 1601
453 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
455 timestamp -= G_GUINT64_CONSTANT(11644473600000000);
458 * Current time, represented as seconds and microseconds since
459 * January 1, 1970, 00:00:00 UTC.
461 gettimeofday(&now, NULL);
464 * Convert to delta in microseconds.
466 timestamp = (guint64)(now.tv_sec) * 1000000 +
467 (guint64)(now.tv_usec);
473 print_usage(FILE *output)
475 fprintf(output, "\nUsage: dumpcap [options] ...\n");
476 fprintf(output, "\n");
477 fprintf(output, "Capture interface:\n");
478 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
479 " or for remote capturing, use one of these formats:\n"
480 " rpcap://<host>/<interface>\n"
481 " TCP@<host>:<port>\n");
482 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
483 #ifdef HAVE_PCAP_CREATE
484 fprintf(output, " -s <snaplen> packet snapshot length (def: appropriate maximum)\n");
486 fprintf(output, " -s <snaplen> packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
488 fprintf(output, " -p don't capture in promiscuous mode\n");
489 #ifdef HAVE_PCAP_CREATE
490 fprintf(output, " -I capture in monitor mode, if available\n");
492 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
493 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
495 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
496 fprintf(output, " -D print list of interfaces and exit\n");
497 fprintf(output, " -L print list of link-layer types of iface and exit\n");
498 #ifdef HAVE_BPF_IMAGE
499 fprintf(output, " -d print generated BPF code for capture filter\n");
501 fprintf(output, " -k set channel on wifi interface:\n"
502 " <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
503 fprintf(output, " -S print statistics for each interface once per second\n");
504 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
505 fprintf(output, "\n");
506 #ifdef HAVE_PCAP_REMOTE
507 fprintf(output, "RPCAP options:\n");
508 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
509 fprintf(output, " -u use UDP for RPCAP data transfer\n");
510 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
511 #ifdef HAVE_PCAP_SETSAMPLING
512 fprintf(output, " -m <sampling type> use packet sampling\n");
513 fprintf(output, " count:NUM - capture one packet of every NUM\n");
514 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
517 fprintf(output, "Stop conditions:\n");
518 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
519 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
520 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
521 fprintf(output, " files:NUM - stop after NUM files\n");
522 /*fprintf(output, "\n");*/
523 fprintf(output, "Output (files):\n");
524 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
525 fprintf(output, " -g enable group read access on the output file(s)\n");
526 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
527 fprintf(output, " interval:NUM - create time intervals of NUM secs\n");
528 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
529 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
530 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
531 fprintf(output, " -P use libpcap format instead of pcapng\n");
532 fprintf(output, " --capture-comment <comment>\n");
533 fprintf(output, " add a capture comment to the output file\n");
534 fprintf(output, " (only for pcapng)\n");
535 fprintf(output, "\n");
536 fprintf(output, "Miscellaneous:\n");
537 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
538 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
539 fprintf(output, " within dumpcap\n");
540 fprintf(output, " -t use a separate thread per interface\n");
541 fprintf(output, " -q don't report packet capture counts\n");
542 fprintf(output, " -v print version information and exit\n");
543 fprintf(output, " -h display this help and exit\n");
544 fprintf(output, "\n");
546 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
547 fprintf(output, "You might want to reset it\n");
548 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
549 fprintf(output, "\n");
551 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
552 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
553 fprintf(output, "\n");
554 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
558 * Report an error in command-line arguments.
559 * If we're a capture child, send a message back to the parent, otherwise
563 dumpcap_cmdarg_err(const char *fmt, va_list ap)
567 /* Generate a 'special format' message back to parent */
568 msg = g_strdup_vprintf(fmt, ap);
569 sync_pipe_errmsg_to_parent(2, msg, "");
572 fprintf(stderr, "dumpcap: ");
573 vfprintf(stderr, fmt, ap);
574 fprintf(stderr, "\n");
579 * Report additional information for an error in command-line arguments.
580 * If we're a capture child, send a message back to the parent, otherwise
584 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
588 msg = g_strdup_vprintf(fmt, ap);
589 sync_pipe_errmsg_to_parent(2, msg, "");
592 vfprintf(stderr, fmt, ap);
593 fprintf(stderr, "\n");
599 #if 0 /* Set to enable capability debugging */
600 /* see 'man cap_to_text()' for explanation of output */
601 /* '=' means 'all= ' ie: no capabilities */
602 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
604 print_caps(const char *pfx) {
605 cap_t caps = cap_get_proc();
606 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
607 "%s: EUID: %d Capabilities: %s", pfx,
608 geteuid(), cap_to_text(caps, NULL));
611 print_caps(const char *pfx _U_) {
616 relinquish_all_capabilities(void)
618 /* Drop any and all capabilities this process may have. */
619 /* Allowed whether or not process has any privileges. */
620 cap_t caps = cap_init(); /* all capabilities initialized to off */
621 print_caps("Pre-clear");
622 if (cap_set_proc(caps)) {
623 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
625 print_caps("Post-clear");
631 get_capture_device_open_failure_messages(const char *open_err_str,
633 char *errmsg, size_t errmsg_len,
634 char *secondary_errmsg,
635 size_t secondary_errmsg_len)
638 const char *libpcap_warn;
639 static const char ppamsg[] = "can't find PPA for ";
642 g_snprintf(errmsg, (gulong) errmsg_len,
643 "The capture session could not be initiated on interface '%s' (%s).",
644 iface, open_err_str);
647 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
649 "In order to capture packets, WinPcap must be installed; see\n"
651 " https://www.winpcap.org/\n"
653 "for a downloadable version of WinPcap and for instructions on how to install\n"
656 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
658 "Please check that \"%s\" is the proper interface.\n"
661 "Help can be found on the following pages:\n"
663 " https://wiki.wireshark.org/WinPcap\n"
664 " https://wiki.wireshark.org/CaptureSetup\n",
668 /* If we got a "can't find PPA for X" message, warn the user (who
669 is running dumpcap on HP-UX) that they don't have a version of
670 libpcap that properly handles HP-UX (libpcap 0.6.x and later
671 versions, which properly handle HP-UX, say "can't find /dev/dlpi
672 PPA for X" rather than "can't find PPA for X"). */
673 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
676 "You are running (T)Wireshark with a version of the libpcap library\n"
677 "that doesn't handle HP-UX network devices well; this means that\n"
678 "(T)Wireshark may not be able to capture packets.\n"
680 "To fix this, you should install libpcap 0.6.2, or a later version\n"
681 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
682 "packaged binary form from the Software Porting And Archive Centre\n"
683 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
684 "at the URL lists a number of mirror sites.";
688 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
689 "Please check to make sure you have sufficient permissions, and that you have "
690 "the proper interface or pipe specified.%s", libpcap_warn);
695 compile_capture_filter(const char *iface, pcap_t *pcap_h,
696 struct bpf_program *fcode, const char *cfilter)
698 bpf_u_int32 netnum, netmask;
699 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
701 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
703 * Well, we can't get the netmask for this interface; it's used
704 * only for filters that check for broadcast IP addresses, so
705 * we just punt and use 0. It might be nice to warn the user,
706 * but that's a pain in a GUI application, as it'd involve popping
707 * up a message box, and it's not clear how often this would make
708 * a difference (only filters that check for IP broadcast addresses
712 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
717 * Sigh. Older versions of libpcap don't properly declare the
718 * third argument to pcap_compile() as a const pointer. Cast
722 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
728 #ifdef HAVE_BPF_IMAGE
730 show_filter_code(capture_options *capture_opts)
732 interface_options interface_opts;
734 gchar open_err_str[PCAP_ERRBUF_SIZE];
735 char errmsg[MSG_MAX_LENGTH+1];
736 char secondary_errmsg[MSG_MAX_LENGTH+1];
737 struct bpf_program fcode;
738 struct bpf_insn *insn;
742 for (j = 0; j < capture_opts->ifaces->len; j++) {
743 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
744 pcap_h = open_capture_device(capture_opts, &interface_opts,
745 CAP_READ_TIMEOUT, &open_err_str);
746 if (pcap_h == NULL) {
747 /* Open failed; get messages */
748 get_capture_device_open_failure_messages(open_err_str,
750 errmsg, sizeof errmsg,
752 sizeof secondary_errmsg);
753 /* And report them */
754 report_capture_error(errmsg, secondary_errmsg);
758 /* Set the link-layer type. */
759 if (!set_pcap_datalink(pcap_h, interface_opts.linktype, interface_opts.name,
760 errmsg, sizeof errmsg,
761 secondary_errmsg, sizeof secondary_errmsg)) {
763 report_capture_error(errmsg, secondary_errmsg);
767 /* OK, try to compile the capture filter. */
768 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
769 interface_opts.cfilter)) {
771 report_cfilter_error(capture_opts, j, errmsg);
776 /* Now print the filter code. */
777 insn = fcode.bf_insns;
779 for (i = 0; i < fcode.bf_len; insn++, i++)
780 printf("%s\n", bpf_image(insn, i));
782 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
783 /* to remove any suid privileges. */
784 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
785 /* (euid/egid have already previously been set to ruid/rgid. */
786 /* (See comment in main() for details) */
788 relinquish_special_privs_perm();
790 relinquish_all_capabilities();
793 /* Let our parent know we succeeded. */
794 pipe_write_block(2, SP_SUCCESS, NULL);
801 * capture_interface_list() is expected to do the right thing to get
802 * a list of interfaces.
804 * In most of the programs in the Wireshark suite, "the right thing"
805 * is to run dumpcap and ask it for the list, because dumpcap may
806 * be the only program in the suite with enough privileges to get
809 * In dumpcap itself, however, we obviously can't run dumpcap to
810 * ask for the list. Therefore, our capture_interface_list() should
811 * just call get_interface_list().
814 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
816 return get_interface_list(err, err_str);
819 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
821 * Output a machine readable list of the interfaces
822 * This list is retrieved by the sync_interface_list_open() function
823 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
826 print_machine_readable_interfaces(GList *if_list)
833 char addr_str[ADDRSTRLEN];
836 /* Let our parent know we succeeded. */
837 pipe_write_block(2, SP_SUCCESS, NULL);
840 i = 1; /* Interface id number */
841 for (if_entry = g_list_first(if_list); if_entry != NULL;
842 if_entry = g_list_next(if_entry)) {
843 if_info = (if_info_t *)if_entry->data;
844 printf("%d. %s\t", i++, if_info->name);
847 * Print the contents of the if_entry struct in a parseable format.
848 * Each if_entry element is tab-separated. Addresses are comma-
851 /* XXX - Make sure our description doesn't contain a tab */
852 if (if_info->vendor_description != NULL)
853 printf("%s\t", if_info->vendor_description);
857 /* XXX - Make sure our friendly name doesn't contain a tab */
858 if (if_info->friendly_name != NULL)
859 printf("%s\t", if_info->friendly_name);
863 printf("%i\t", if_info->type);
865 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
866 addr = g_slist_next(addr)) {
867 if (addr != g_slist_nth(if_info->addrs, 0))
870 if_addr = (if_addr_t *)addr->data;
871 switch(if_addr->ifat_type) {
873 if (ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str,
875 printf("%s", addr_str);
877 printf("<unknown IPv4>");
881 if (ws_inet_ntop6(&if_addr->addr.ip6_addr,
882 addr_str, ADDRSTRLEN)) {
883 printf("%s", addr_str);
885 printf("<unknown IPv6>");
889 printf("<type unknown %i>", if_addr->ifat_type);
893 if (if_info->loopback)
894 printf("\tloopback");
898 printf("\t%s", if_info->extcap);
905 * If you change the machine-readable output format of this function,
906 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
909 print_machine_readable_if_capabilities(if_capabilities_t *caps)
912 data_link_info_t *data_link_info;
913 const gchar *desc_str;
916 /* Let our parent know we succeeded. */
917 pipe_write_block(2, SP_SUCCESS, NULL);
920 if (caps->can_set_rfmon)
924 for (lt_entry = caps->data_link_types; lt_entry != NULL;
925 lt_entry = g_list_next(lt_entry)) {
926 data_link_info = (data_link_info_t *)lt_entry->data;
927 if (data_link_info->description != NULL)
928 desc_str = data_link_info->description;
930 desc_str = "(not supported)";
931 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
941 /* Print the number of packets captured for each interface until we're killed. */
943 print_statistics_loop(gboolean machine_readable)
945 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
951 char errbuf[PCAP_ERRBUF_SIZE];
954 if_list = get_interface_list(&err, &err_str);
955 if (if_list == NULL) {
957 cmdarg_err("There are no interfaces on which a capture can be done");
959 cmdarg_err("%s", err_str);
965 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
966 if_info = (if_info_t *)if_entry->data;
969 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
970 * connections. We avoid collecting stats on them.
972 if (!strncmp(if_info->name, "nf", 2)) {
973 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
979 #ifdef HAVE_PCAP_OPEN
980 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
982 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
986 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
987 if_stat->name = g_strdup(if_info->name);
989 stat_list = g_list_append(stat_list, if_stat);
994 cmdarg_err("There are no interfaces on which a capture can be done");
999 /* Let our parent know we succeeded. */
1000 pipe_write_block(2, SP_SUCCESS, NULL);
1003 if (!machine_readable) {
1004 printf("%-15s %10s %10s\n", "Interface", "Received",
1008 global_ld.go = TRUE;
1009 while (global_ld.go) {
1010 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1011 if_stat = (if_stat_t *)stat_entry->data;
1012 pcap_stats(if_stat->pch, &ps);
1014 if (!machine_readable) {
1015 printf("%-15s %10u %10u\n", if_stat->name,
1016 ps.ps_recv, ps.ps_drop);
1018 printf("%s\t%u\t%u\n", if_stat->name,
1019 ps.ps_recv, ps.ps_drop);
1024 /* If we have a dummy signal pipe check it */
1025 if (!signal_pipe_check_running()) {
1026 global_ld.go = FALSE;
1034 /* XXX - Not reached. Should we look for 'q' in stdin? */
1035 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1036 if_stat = (if_stat_t *)stat_entry->data;
1037 pcap_close(if_stat->pch);
1038 g_free(if_stat->name);
1041 g_list_free(stat_list);
1042 free_interface_list(if_list);
1050 capture_cleanup_handler(DWORD dwCtrlType)
1052 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1053 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1054 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1055 like SIGTERM at least when the machine's shutting down.
1057 For now, if we're running as a command rather than a capture child,
1058 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1059 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1060 in that way on UN*X.
1062 If we're not running as a capture child, we might be running as
1063 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1064 user logs out. (XXX - can we explicitly check whether we're
1065 running as a service?) */
1067 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1068 "Console: Control signal");
1069 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1070 "Console: Control signal, CtrlType: %u", dwCtrlType);
1072 /* Keep capture running if we're a service and a user logs off */
1073 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1074 capture_loop_stop();
1082 capture_cleanup_handler(int signum _U_)
1084 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1085 SIGTERM. We assume that if the user wanted it to keep running
1086 after they logged out, they'd have nohupped it. */
1088 /* Note: don't call g_log() in the signal handler: if we happened to be in
1089 * g_log() in process context when the signal came in, g_log will detect
1090 * the "recursion" and abort.
1093 capture_loop_stop();
1099 report_capture_count(gboolean reportit)
1101 /* Don't print this if we're a capture child. */
1102 if (!capture_child && reportit) {
1103 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packet_count);
1104 /* stderr could be line buffered */
1112 report_counts_for_siginfo(void)
1114 report_capture_count(quiet);
1115 infoprint = FALSE; /* we just reported it */
1119 report_counts_siginfo(int signum _U_)
1121 int sav_errno = errno;
1123 /* If we've been told to delay printing, just set a flag asking
1124 that we print counts (if we're supposed to), otherwise print
1125 the count of packets captured (if we're supposed to). */
1129 report_counts_for_siginfo();
1132 #endif /* SIGINFO */
1135 exit_main(int status)
1138 /* Shutdown windows sockets */
1141 /* can be helpful for debugging */
1142 #ifdef DEBUG_DUMPCAP
1143 printf("Press any key\n");
1149 capture_opts_cleanup(&global_capture_opts);
1155 * If we were linked with libcap (not related to libpcap), make sure we have
1156 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1157 * (See comment in main() for details)
1160 relinquish_privs_except_capture(void)
1162 /* If 'started_with_special_privs' (ie: suid) then enable for
1163 * ourself the NET_ADMIN and NET_RAW capabilities and then
1164 * drop our suid privileges.
1166 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1167 * stuff we don't need (and shouldn't have).
1168 * CAP_NET_RAW: Packet capture (raw sockets).
1171 if (started_with_special_privs()) {
1172 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1173 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1175 cap_t caps = cap_init(); /* all capabilities initialized to off */
1177 print_caps("Pre drop, pre set");
1179 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1180 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1183 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1184 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1186 if (cap_set_proc(caps)) {
1187 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1189 print_caps("Pre drop, post set");
1191 relinquish_special_privs_perm();
1193 print_caps("Post drop, pre set");
1194 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1195 if (cap_set_proc(caps)) {
1196 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1198 print_caps("Post drop, post set");
1204 #endif /* HAVE_LIBCAP */
1206 /* Take care of byte order in the libpcap headers read from pipes.
1207 * (function taken from wiretap/libpcap.c) */
1209 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1212 /* Byte-swap the record header fields. */
1213 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1214 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1215 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1216 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1219 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1220 swapped, in order to match the BPF header layout.
1222 Unfortunately, some files were, according to a comment in the "libpcap"
1223 source, written with version 2.3 in their headers but without the
1224 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1225 would make no sense - we assume that we need to swap them. */
1226 if (hdr->version_major == 2 &&
1227 (hdr->version_minor < 3 ||
1228 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1231 temp = rechdr->orig_len;
1232 rechdr->orig_len = rechdr->incl_len;
1233 rechdr->incl_len = temp;
1237 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1241 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1245 return recv(pipe_fd, buf, (int)sz, 0);
1250 return ws_read(pipe_fd, buf, sz);
1256 * Thread function that reads from a pipe and pushes the data
1257 * to the main application thread.
1260 * XXX Right now we use async queues for basic signaling. The main thread
1261 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1262 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1263 * Iff the read is successful cap_pipe_read pushes an item onto
1264 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1265 * the queues themselves (yet).
1267 * We might want to move some of the cap_pipe_dispatch logic here so that
1268 * we can let cap_thread_read run independently, queuing up multiple reads
1269 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1271 static void *cap_thread_read(void *arg)
1273 capture_src *pcap_src;
1276 DWORD b, last_err, bytes_read;
1282 pcap_src = (capture_src *)arg;
1283 while (pcap_src->cap_pipe_err == PIPOK) {
1284 g_async_queue_pop(pcap_src->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1285 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1287 while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1288 if ((pcap_src->from_cap_socket)
1294 b = cap_pipe_read(pcap_src->cap_pipe_fd, pcap_src->cap_pipe_buf+bytes_read,
1295 pcap_src->cap_pipe_bytes_to_read - bytes_read, pcap_src->from_cap_socket);
1298 pcap_src->cap_pipe_err = PIPEOF;
1302 pcap_src->cap_pipe_err = PIPERR;
1313 /* If we try to use read() on a named pipe on Windows with partial
1314 * data it appears to return EOF.
1316 res = ReadFile(pcap_src->cap_pipe_h, pcap_src->cap_pipe_buf+bytes_read,
1317 pcap_src->cap_pipe_bytes_to_read - bytes_read,
1322 last_err = GetLastError();
1323 if (last_err == ERROR_MORE_DATA) {
1325 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1326 pcap_src->cap_pipe_err = PIPEOF;
1330 pcap_src->cap_pipe_err = PIPERR;
1333 } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1334 pcap_src->cap_pipe_err = PIPEOF;
1341 pcap_src->cap_pipe_bytes_read = bytes_read;
1342 if (pcap_src->cap_pipe_bytes_read >= pcap_src->cap_pipe_bytes_to_read) {
1343 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1345 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1351 /* Provide select() functionality for a single file descriptor
1352 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1354 * Returns the same values as select.
1357 cap_pipe_select(int pipe_fd)
1360 struct timeval timeout;
1363 FD_SET(pipe_fd, &rfds);
1365 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1366 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1368 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1371 #define DEF_TCP_PORT 19000
1374 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, int errmsgl)
1376 char *sockname = pipename + 4;
1377 struct sockaddr_in sa;
1384 memset(&sa, 0, sizeof(sa));
1386 p = strchr(sockname, ':');
1388 len = strlen(sockname);
1389 port = DEF_TCP_PORT;
1393 port = strtoul(p + 1, &p, 10);
1394 if (*p || port > 65535) {
1403 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1405 if (!ws_inet_pton4(buf, (guint32 *)&sa.sin_addr)) {
1409 sa.sin_family = AF_INET;
1410 sa.sin_port = g_htons((u_short)port);
1412 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1413 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1415 LPTSTR errorText = NULL;
1418 lastError = WSAGetLastError();
1419 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1420 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1421 FORMAT_MESSAGE_IGNORE_INSERTS,
1422 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1423 (LPTSTR)&errorText, 0, NULL);
1425 g_snprintf(errmsg, errmsgl,
1426 "The capture session could not be initiated due to the socket error: \n"
1428 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1430 LocalFree(errorText);
1432 " %d: %s", errno, g_strerror(errno));
1434 pcap_src->cap_pipe_err = PIPERR;
1437 cap_pipe_close(fd, TRUE);
1441 pcap_src->from_cap_socket = TRUE;
1445 g_snprintf(errmsg, errmsgl,
1446 "The capture session could not be initiated because\n"
1447 "\"%s\" is not a valid socket specification", pipename);
1448 pcap_src->cap_pipe_err = PIPERR;
1452 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1456 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1460 closesocket(pipe_fd);
1467 /* Mimic pcap_open_live() for pipe captures
1469 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1470 * open it, and read the header.
1472 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1473 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1475 cap_pipe_open_live(char *pipename,
1476 capture_src *pcap_src,
1477 struct pcap_hdr *hdr,
1478 char *errmsg, int errmsgl)
1481 ws_statb64 pipe_stat;
1482 struct sockaddr_un sa;
1487 char* extcap_pipe_name;
1491 gboolean extcap_pipe = FALSE;
1492 interface_options interface_opts;
1495 int fd = -1, sel_ret;
1498 pcap_src->cap_pipe_fd = -1;
1500 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1503 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1506 * XXX - this blocks until a pcap per-file header has been written to
1507 * the pipe, so it could block indefinitely.
1509 if (strcmp(pipename, "-") == 0) {
1511 fd = 0; /* read from stdin */
1513 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1515 } else if (!strncmp(pipename, "TCP@", 4)) {
1516 if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1522 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
1527 if ( g_strrstr(interface_opts.name, EXTCAP_PIPE_PREFIX) != NULL )
1531 if (ws_stat64(pipename, &pipe_stat) < 0) {
1532 if (errno == ENOENT || errno == ENOTDIR)
1533 pcap_src->cap_pipe_err = PIPNEXIST;
1535 g_snprintf(errmsg, errmsgl,
1536 "The capture session could not be initiated "
1537 "due to error getting information on pipe/socket: %s.", g_strerror(errno));
1538 pcap_src->cap_pipe_err = PIPERR;
1542 if (S_ISFIFO(pipe_stat.st_mode)) {
1543 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1545 g_snprintf(errmsg, errmsgl,
1546 "The capture session could not be initiated "
1547 "due to error on pipe open: %s.", g_strerror(errno));
1548 pcap_src->cap_pipe_err = PIPERR;
1551 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1552 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1554 g_snprintf(errmsg, errmsgl,
1555 "The capture session could not be initiated "
1556 "due to error on socket create: %s.", g_strerror(errno));
1557 pcap_src->cap_pipe_err = PIPERR;
1560 sa.sun_family = AF_UNIX;
1562 * The Single UNIX Specification says:
1564 * The size of sun_path has intentionally been left undefined.
1565 * This is because different implementations use different sizes.
1566 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1567 * of 104. Since most implementations originate from BSD versions,
1568 * the size is typically in the range 92 to 108.
1570 * Applications should not assume a particular length for sun_path
1571 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1575 * The <sys/un.h> header shall define the sockaddr_un structure,
1576 * which shall include at least the following members:
1578 * sa_family_t sun_family Address family.
1579 * char sun_path[] Socket pathname.
1581 * so we assume that it's an array, with a specified size,
1582 * and that the size reflects the maximum path length.
1584 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1585 /* Path name too long */
1586 g_snprintf(errmsg, errmsgl,
1587 "The capture session coud not be initiated "
1588 "due to error on socket connect: Path name too long.");
1589 pcap_src->cap_pipe_err = PIPERR;
1593 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1595 g_snprintf(errmsg, errmsgl,
1596 "The capture session coud not be initiated "
1597 "due to error on socket connect: %s.", g_strerror(errno));
1598 pcap_src->cap_pipe_err = PIPERR;
1603 if (S_ISCHR(pipe_stat.st_mode)) {
1605 * Assume the user specified an interface on a system where
1606 * interfaces are in /dev. Pretend we haven't seen it.
1608 pcap_src->cap_pipe_err = PIPNEXIST;
1610 g_snprintf(errmsg, errmsgl,
1611 "The capture session could not be initiated because\n"
1612 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1613 pcap_src->cap_pipe_err = PIPERR;
1619 #define PIPE_STR "\\pipe\\"
1620 /* Under Windows, named pipes _must_ have the form
1621 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1623 pncopy = g_strdup(pipename);
1624 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1625 pos = strchr(pncopy + 3, '\\');
1626 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1633 g_snprintf(errmsg, errmsgl,
1634 "The capture session could not be initiated because\n"
1635 "\"%s\" is neither an interface nor a pipe.", pipename);
1636 pcap_src->cap_pipe_err = PIPNEXIST;
1640 extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
1641 extcap_pipe = strstr(interface_opts.name, extcap_pipe_name) ? TRUE : FALSE;
1642 g_free(extcap_pipe_name);
1645 /* Wait for the pipe to appear */
1650 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1653 pcap_src->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1654 OPEN_EXISTING, 0, NULL);
1656 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE)
1659 if (GetLastError() != ERROR_PIPE_BUSY) {
1660 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1661 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1662 g_snprintf(errmsg, errmsgl,
1663 "The capture session on \"%s\" could not be started "
1664 "due to error on pipe open: %s (error %d).",
1665 pipename, utf_16to8(err_str), GetLastError());
1667 pcap_src->cap_pipe_err = PIPERR;
1671 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1672 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1673 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1674 g_snprintf(errmsg, errmsgl,
1675 "The capture session on \"%s\" timed out during "
1676 "pipe open: %s (error %d).",
1677 pipename, utf_16to8(err_str), GetLastError());
1679 pcap_src->cap_pipe_err = PIPERR;
1686 pcap_src->from_cap_pipe = TRUE;
1689 * We start with a 2KB buffer for packet data, which should be
1690 * large enough for most regular network packets. We increase it,
1691 * up to the maximum size we allow, as necessary.
1693 pcap_src->cap_pipe_databuf = (guchar*)g_malloc(2048);
1694 pcap_src->cap_pipe_databuf_size = 2048;
1697 if (pcap_src->from_cap_socket)
1700 /* read the pcap header */
1702 while (bytes_read < sizeof magic) {
1704 g_snprintf(errmsg, errmsgl, "Invalid file descriptor.");
1708 sel_ret = cap_pipe_select(fd);
1710 g_snprintf(errmsg, errmsgl,
1711 "Unexpected error from select: %s.", g_strerror(errno));
1713 } else if (sel_ret > 0) {
1714 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1715 sizeof magic-bytes_read,
1716 pcap_src->from_cap_socket);
1718 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1719 if (extcap_pipe && b <= 0)
1724 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1726 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1736 #if GLIB_CHECK_VERSION(2,31,0)
1737 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
1739 g_thread_create(&cap_thread_read, pcap_src, FALSE, NULL);
1742 pcap_src->cap_pipe_buf = (char *) &magic;
1743 pcap_src->cap_pipe_bytes_read = 0;
1744 pcap_src->cap_pipe_bytes_to_read = sizeof(magic);
1745 /* We don't have to worry about cap_pipe_read_mtx here */
1746 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1747 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1748 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1749 if (pcap_src->cap_pipe_bytes_read <= 0 && extcap_pipe)
1752 if (pcap_src->cap_pipe_bytes_read <= 0) {
1753 if (pcap_src->cap_pipe_bytes_read == 0)
1754 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1756 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1765 case PCAP_NSEC_MAGIC:
1766 /* Host that wrote it has our byte order, and was running
1767 a program using either standard or ss990417 libpcap. */
1768 pcap_src->cap_pipe_byte_swapped = FALSE;
1769 pcap_src->cap_pipe_modified = FALSE;
1770 pcap_src->ts_nsec = magic == PCAP_NSEC_MAGIC;
1772 case PCAP_MODIFIED_MAGIC:
1773 /* Host that wrote it has our byte order, but was running
1774 a program using either ss990915 or ss991029 libpcap. */
1775 pcap_src->cap_pipe_byte_swapped = FALSE;
1776 pcap_src->cap_pipe_modified = TRUE;
1778 case PCAP_SWAPPED_MAGIC:
1779 case PCAP_SWAPPED_NSEC_MAGIC:
1780 /* Host that wrote it has a byte order opposite to ours,
1781 and was running a program using either standard or
1782 ss990417 libpcap. */
1783 pcap_src->cap_pipe_byte_swapped = TRUE;
1784 pcap_src->cap_pipe_modified = FALSE;
1785 pcap_src->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
1787 case PCAP_SWAPPED_MODIFIED_MAGIC:
1788 /* Host that wrote it out has a byte order opposite to
1789 ours, and was running a program using either ss990915
1790 or ss991029 libpcap. */
1791 pcap_src->cap_pipe_byte_swapped = TRUE;
1792 pcap_src->cap_pipe_modified = TRUE;
1794 case BLOCK_TYPE_SHB:
1795 /* This isn't pcap, it's pcapng. We don't yet support
1797 g_snprintf(errmsg, errmsgl, "Capturing from a pipe doesn't support pcapng format.");
1800 /* Not a pcap type we know about, or not pcap at all. */
1801 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format or not libpcap data.");
1806 if (pcap_src->from_cap_socket)
1809 /* Read the rest of the header */
1811 while (bytes_read < sizeof(struct pcap_hdr)) {
1812 sel_ret = cap_pipe_select(fd);
1814 g_snprintf(errmsg, errmsgl,
1815 "Unexpected error from select: %s.", g_strerror(errno));
1817 } else if (sel_ret > 0) {
1818 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
1819 sizeof(struct pcap_hdr) - bytes_read,
1820 pcap_src->from_cap_socket);
1823 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1825 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s.",
1835 pcap_src->cap_pipe_buf = (char *) hdr;
1836 pcap_src->cap_pipe_bytes_read = 0;
1837 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1838 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1839 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1840 if (pcap_src->cap_pipe_bytes_read <= 0) {
1841 if (pcap_src->cap_pipe_bytes_read == 0)
1842 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1844 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s.",
1851 if (pcap_src->cap_pipe_byte_swapped) {
1852 /* Byte-swap the header fields about which we care. */
1853 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
1854 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
1855 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
1856 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
1858 pcap_src->linktype = hdr->network;
1860 if (pcap_src->linktype == DLT_DBUS) {
1862 * The maximum D-Bus message size is 128MB, so allow packets up
1865 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_DBUS;
1868 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
1870 if (hdr->version_major < 2) {
1871 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1875 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
1876 pcap_src->cap_pipe_err = PIPOK;
1877 pcap_src->cap_pipe_fd = fd;
1881 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1882 pcap_src->cap_pipe_err = PIPERR;
1883 cap_pipe_close(fd, pcap_src->from_cap_socket);
1884 pcap_src->cap_pipe_fd = -1;
1886 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1891 /* We read one record from the pipe, take care of byte order in the record
1892 * header, write the record to the capture file, and update capture statistics. */
1894 cap_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, int errmsgl)
1896 struct pcap_pkthdr phdr;
1897 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1900 #if !GLIB_CHECK_VERSION(2,31,18)
1909 #ifdef LOG_CAPTURE_VERBOSE
1910 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1913 switch (pcap_src->cap_pipe_state) {
1915 case STATE_EXPECT_REC_HDR:
1917 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
1920 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
1921 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_modified ?
1922 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1923 pcap_src->cap_pipe_bytes_read = 0;
1926 pcap_src->cap_pipe_buf = (char *) &pcap_src->cap_pipe_rechdr;
1927 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1928 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1933 case STATE_READ_REC_HDR:
1935 if (pcap_src->from_cap_socket)
1938 b = cap_pipe_read(pcap_src->cap_pipe_fd, ((char *)&pcap_src->cap_pipe_rechdr)+pcap_src->cap_pipe_bytes_read,
1939 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read, pcap_src->from_cap_socket);
1942 result = PD_PIPE_EOF;
1944 result = PD_PIPE_ERR;
1947 pcap_src->cap_pipe_bytes_read += b;
1951 #if GLIB_CHECK_VERSION(2,31,18)
1952 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
1954 g_get_current_time(&wait_time);
1955 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
1956 q_status = g_async_queue_timed_pop(pcap_src->cap_pipe_done_q, &wait_time);
1958 if (pcap_src->cap_pipe_err == PIPEOF) {
1959 result = PD_PIPE_EOF;
1961 } else if (pcap_src->cap_pipe_err == PIPERR) {
1962 result = PD_PIPE_ERR;
1970 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
1972 result = PD_REC_HDR_READ;
1975 case STATE_EXPECT_DATA:
1977 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
1980 pcap_src->cap_pipe_state = STATE_READ_DATA;
1981 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_rechdr.hdr.incl_len;
1982 pcap_src->cap_pipe_bytes_read = 0;
1985 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
1986 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1987 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1992 case STATE_READ_DATA:
1994 if (pcap_src->from_cap_socket)
1997 b = cap_pipe_read(pcap_src->cap_pipe_fd,
1998 pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read,
1999 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read,
2000 pcap_src->from_cap_socket);
2003 result = PD_PIPE_EOF;
2005 result = PD_PIPE_ERR;
2008 pcap_src->cap_pipe_bytes_read += b;
2013 #if GLIB_CHECK_VERSION(2,31,18)
2014 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2016 g_get_current_time(&wait_time);
2017 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2018 q_status = g_async_queue_timed_pop(pcap_src->cap_pipe_done_q, &wait_time);
2019 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2020 if (pcap_src->cap_pipe_err == PIPEOF) {
2021 result = PD_PIPE_EOF;
2023 } else if (pcap_src->cap_pipe_err == PIPERR) {
2024 result = PD_PIPE_ERR;
2032 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2034 result = PD_DATA_READ;
2038 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2041 } /* switch (pcap_src->cap_pipe_state) */
2044 * We've now read as much data as we were expecting, so process it.
2048 case PD_REC_HDR_READ:
2049 /* We've read the header. Take care of byte order. */
2050 cap_pipe_adjust_header(pcap_src->cap_pipe_byte_swapped, &pcap_src->cap_pipe_hdr,
2051 &pcap_src->cap_pipe_rechdr.hdr);
2052 if (pcap_src->cap_pipe_rechdr.hdr.incl_len > pcap_src->cap_pipe_max_pkt_size) {
2054 * The record contains more data than the advertised/allowed in the
2055 * pcap header, do not try to read more data (do not change to
2056 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2057 * instead stop with an error.
2059 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2060 ld->packet_count+1, pcap_src->cap_pipe_rechdr.hdr.incl_len);
2064 if (pcap_src->cap_pipe_rechdr.hdr.incl_len > pcap_src->cap_pipe_databuf_size) {
2066 * Grow the buffer to the packet size, rounded up to a power of
2069 new_bufsize = pcap_src->cap_pipe_rechdr.hdr.incl_len;
2071 * http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2074 new_bufsize |= new_bufsize >> 1;
2075 new_bufsize |= new_bufsize >> 2;
2076 new_bufsize |= new_bufsize >> 4;
2077 new_bufsize |= new_bufsize >> 8;
2078 new_bufsize |= new_bufsize >> 16;
2080 pcap_src->cap_pipe_databuf = (guchar*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2081 pcap_src->cap_pipe_databuf_size = new_bufsize;
2085 * The record has some data following the header, try to read it next
2088 if (pcap_src->cap_pipe_rechdr.hdr.incl_len) {
2089 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2094 * No data following the record header? Then no more data needs to be
2095 * read and we will fallthrough and emit an empty packet.
2099 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2100 phdr.ts.tv_sec = pcap_src->cap_pipe_rechdr.hdr.ts_sec;
2101 phdr.ts.tv_usec = pcap_src->cap_pipe_rechdr.hdr.ts_usec;
2102 phdr.caplen = pcap_src->cap_pipe_rechdr.hdr.incl_len;
2103 phdr.len = pcap_src->cap_pipe_rechdr.hdr.orig_len;
2106 capture_loop_queue_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2108 capture_loop_write_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2110 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2114 pcap_src->cap_pipe_err = PIPEOF;
2119 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2120 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2121 g_snprintf(errmsg, errmsgl,
2122 "Error reading from pipe: %s (error %d)",
2123 utf_16to8(err_str), GetLastError());
2126 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2134 pcap_src->cap_pipe_err = PIPERR;
2135 /* Return here rather than inside the switch to prevent GCC warning */
2140 /** Open the capture input file (pcap or capture pipe).
2141 * Returns TRUE if it succeeds, FALSE otherwise. */
2143 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2144 char *errmsg, size_t errmsg_len,
2145 char *secondary_errmsg, size_t secondary_errmsg_len)
2147 gchar open_err_str[PCAP_ERRBUF_SIZE];
2148 gchar *sync_msg_str;
2149 interface_options interface_opts;
2150 capture_src *pcap_src;
2154 WORD wVersionRequested;
2158 /* XXX - opening Winsock on tshark? */
2160 /* Initialize Windows Socket if we are in a Win32 OS
2161 This needs to be done before querying the interface for network/netmask */
2163 /* XXX - do we really require 1.1 or earlier?
2164 Are there any versions that support only 2.0 or higher? */
2165 wVersionRequested = MAKEWORD(1, 1);
2166 err = WSAStartup(wVersionRequested, &wsaData);
2170 case WSASYSNOTREADY:
2171 g_snprintf(errmsg, (gulong) errmsg_len,
2172 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2175 case WSAVERNOTSUPPORTED:
2176 g_snprintf(errmsg, (gulong) errmsg_len,
2177 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2178 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2181 case WSAEINPROGRESS:
2182 g_snprintf(errmsg, (gulong) errmsg_len,
2183 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2187 g_snprintf(errmsg, (gulong) errmsg_len,
2188 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2192 g_snprintf(errmsg, (gulong) errmsg_len,
2193 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2197 g_snprintf(errmsg, (gulong) errmsg_len,
2198 "Couldn't initialize Windows Sockets: error %d", err);
2201 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2205 if ((use_threads == FALSE) &&
2206 (capture_opts->ifaces->len > 1)) {
2207 g_snprintf(errmsg, (gulong) errmsg_len,
2208 "Using threads is required for capturing on multiple interfaces.");
2212 for (i = 0; i < capture_opts->ifaces->len; i++) {
2213 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2214 pcap_src = (capture_src *)g_malloc(sizeof (capture_src));
2215 if (pcap_src == NULL) {
2216 g_snprintf(errmsg, (gulong) errmsg_len,
2217 "Could not allocate memory.");
2220 pcap_src->received = 0;
2221 pcap_src->dropped = 0;
2222 pcap_src->flushed = 0;
2223 pcap_src->pcap_h = NULL;
2224 #ifdef MUST_DO_SELECT
2225 pcap_src->pcap_fd = -1;
2227 pcap_src->pcap_err = FALSE;
2228 pcap_src->interface_id = i;
2229 pcap_src->tid = NULL;
2230 pcap_src->snaplen = 0;
2231 pcap_src->linktype = -1;
2232 pcap_src->ts_nsec = FALSE;
2233 pcap_src->from_cap_pipe = FALSE;
2234 pcap_src->from_cap_socket = FALSE;
2235 memset(&pcap_src->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2236 memset(&pcap_src->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2238 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2240 pcap_src->cap_pipe_fd = -1;
2241 pcap_src->cap_pipe_modified = FALSE;
2242 pcap_src->cap_pipe_byte_swapped = FALSE;
2244 pcap_src->cap_pipe_buf = NULL;
2246 pcap_src->cap_pipe_bytes_to_read = 0;
2247 pcap_src->cap_pipe_bytes_read = 0;
2248 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2249 pcap_src->cap_pipe_err = PIPOK;
2251 #if GLIB_CHECK_VERSION(2,31,0)
2252 pcap_src->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2253 g_mutex_init(pcap_src->cap_pipe_read_mtx);
2255 pcap_src->cap_pipe_read_mtx = g_mutex_new();
2257 pcap_src->cap_pipe_pending_q = g_async_queue_new();
2258 pcap_src->cap_pipe_done_q = g_async_queue_new();
2260 g_array_append_val(ld->pcaps, pcap_src);
2262 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2263 pcap_src->pcap_h = open_capture_device(capture_opts, &interface_opts,
2264 CAP_READ_TIMEOUT, &open_err_str);
2266 if (pcap_src->pcap_h != NULL) {
2267 /* we've opened "iface" as a network device */
2269 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2270 /* Find out if we're getting nanosecond-precision time stamps */
2271 pcap_src->ts_nsec = have_high_resolution_timestamp(pcap_src->pcap_h);
2274 #if defined(HAVE_PCAP_SETSAMPLING)
2275 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2276 struct pcap_samp *samp;
2278 if ((samp = pcap_setsampling(pcap_src->pcap_h)) != NULL) {
2279 switch (interface_opts.sampling_method) {
2280 case CAPTURE_SAMP_BY_COUNT:
2281 samp->method = PCAP_SAMP_1_EVERY_N;
2284 case CAPTURE_SAMP_BY_TIMER:
2285 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2289 sync_msg_str = g_strdup_printf(
2290 "Unknown sampling method %d specified,\n"
2291 "continue without packet sampling",
2292 interface_opts.sampling_method);
2293 report_capture_error("Couldn't set the capture "
2294 "sampling", sync_msg_str);
2295 g_free(sync_msg_str);
2297 samp->value = interface_opts.sampling_param;
2299 report_capture_error("Couldn't set the capture sampling",
2300 "Cannot get packet sampling data structure");
2305 /* setting the data link type only works on real interfaces */
2306 if (!set_pcap_datalink(pcap_src->pcap_h, interface_opts.linktype,
2307 interface_opts.name,
2309 secondary_errmsg, secondary_errmsg_len)) {
2312 pcap_src->linktype = get_pcap_datalink(pcap_src->pcap_h, interface_opts.name);
2314 /* We couldn't open "iface" as a network device. */
2315 /* Try to open it as a pipe */
2316 cap_pipe_open_live(interface_opts.name, pcap_src, &pcap_src->cap_pipe_hdr, errmsg, (int) errmsg_len);
2319 if (pcap_src->cap_pipe_fd == -1) {
2321 if (pcap_src->cap_pipe_h == INVALID_HANDLE_VALUE) {
2323 if (pcap_src->cap_pipe_err == PIPNEXIST) {
2325 * We tried opening as an interface, and that failed,
2326 * so we tried to open it as a pipe, but the pipe
2327 * doesn't exist. Report the error message for
2330 get_capture_device_open_failure_messages(open_err_str,
2331 interface_opts.name,
2335 secondary_errmsg_len);
2338 * Else pipe (or file) does exist and cap_pipe_open_live() has
2343 /* cap_pipe_open_live() succeeded; don't want
2344 error message from pcap_open_live() */
2345 open_err_str[0] = '\0';
2349 /* XXX - will this work for tshark? */
2350 #ifdef MUST_DO_SELECT
2351 if (!pcap_src->from_cap_pipe) {
2352 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2353 pcap_src->pcap_fd = pcap_get_selectable_fd(pcap_src->pcap_h);
2355 pcap_src->pcap_fd = pcap_fileno(pcap_src->pcap_h);
2360 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2361 returned a warning; print it, but keep capturing. */
2362 if (open_err_str[0] != '\0') {
2363 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2364 report_capture_error(sync_msg_str, "");
2365 g_free(sync_msg_str);
2367 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2368 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2371 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2372 /* to remove any suid privileges. */
2373 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2374 /* (euid/egid have already previously been set to ruid/rgid. */
2375 /* (See comment in main() for details) */
2377 relinquish_special_privs_perm();
2379 relinquish_all_capabilities();
2384 /* close the capture input file (pcap or capture pipe) */
2385 static void capture_loop_close_input(loop_data *ld)
2388 capture_src *pcap_src;
2390 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2392 for (i = 0; i < ld->pcaps->len; i++) {
2393 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2394 /* Pipe, or capture device? */
2395 if (pcap_src->from_cap_pipe) {
2396 /* Pipe. If open, close the capture pipe "input file". */
2397 if (pcap_src->cap_pipe_fd >= 0) {
2398 cap_pipe_close(pcap_src->cap_pipe_fd, pcap_src->from_cap_socket);
2399 pcap_src->cap_pipe_fd = -1;
2402 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE) {
2403 CloseHandle(pcap_src->cap_pipe_h);
2404 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2407 if (pcap_src->cap_pipe_databuf != NULL) {
2408 /* Free the buffer. */
2409 g_free(pcap_src->cap_pipe_databuf);
2410 pcap_src->cap_pipe_databuf = NULL;
2413 /* Capture device. If open, close the pcap_t. */
2414 if (pcap_src->pcap_h != NULL) {
2415 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_src->pcap_h);
2416 pcap_close(pcap_src->pcap_h);
2417 pcap_src->pcap_h = NULL;
2425 /* Shut down windows sockets */
2431 /* init the capture filter */
2432 static initfilter_status_t
2433 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2434 const gchar * name, const gchar * cfilter)
2436 struct bpf_program fcode;
2438 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2440 /* capture filters only work on real interfaces */
2441 if (cfilter && !from_cap_pipe) {
2442 /* A capture filter was specified; set it up. */
2443 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2444 /* Treat this specially - our caller might try to compile this
2445 as a display filter and, if that succeeds, warn the user that
2446 the display and capture filter syntaxes are different. */
2447 return INITFILTER_BAD_FILTER;
2449 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2450 #ifdef HAVE_PCAP_FREECODE
2451 pcap_freecode(&fcode);
2453 return INITFILTER_OTHER_ERROR;
2455 #ifdef HAVE_PCAP_FREECODE
2456 pcap_freecode(&fcode);
2460 return INITFILTER_NO_ERROR;
2464 /* set up to write to the already-opened capture output file/files */
2466 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2470 capture_src *pcap_src;
2471 interface_options interface_opts;
2472 gboolean successful;
2474 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2476 if ((capture_opts->use_pcapng == FALSE) &&
2477 (capture_opts->ifaces->len > 1)) {
2478 g_snprintf(errmsg, errmsg_len,
2479 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
2483 /* Set up to write to the capture file. */
2484 if (capture_opts->multi_files_on) {
2485 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2487 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2488 if (ld->pdh == NULL) {
2493 if (capture_opts->use_pcapng) {
2495 GString *cpu_info_str;
2496 GString *os_info_str;
2498 cpu_info_str = g_string_new("");
2499 os_info_str = g_string_new("");
2500 get_cpu_info(cpu_info_str);
2501 get_os_version_info(os_info_str);
2503 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2504 successful = pcapng_write_session_header_block(ld->pdh,
2505 (const char *)capture_opts->capture_comment, /* Comment */
2506 cpu_info_str->str, /* HW */
2507 os_info_str->str, /* OS */
2509 -1, /* section_length */
2512 g_string_free(cpu_info_str, TRUE);
2515 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2516 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2517 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2518 if (pcap_src->from_cap_pipe) {
2519 pcap_src->snaplen = pcap_src->cap_pipe_hdr.snaplen;
2521 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
2523 successful = pcapng_write_interface_description_block(global_ld.pdh,
2524 NULL, /* OPT_COMMENT 1 */
2525 interface_opts.name, /* IDB_NAME 2 */
2526 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2527 interface_opts.cfilter, /* IDB_FILTER 11 */
2528 os_info_str->str, /* IDB_OS 12 */
2531 &(global_ld.bytes_written),
2532 0, /* IDB_IF_SPEED 8 */
2533 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2537 g_string_free(os_info_str, TRUE);
2540 pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
2541 if (pcap_src->from_cap_pipe) {
2542 pcap_src->snaplen = pcap_src->cap_pipe_hdr.snaplen;
2544 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
2546 successful = libpcap_write_file_header(ld->pdh, pcap_src->linktype, pcap_src->snaplen,
2547 pcap_src->ts_nsec, &ld->bytes_written, &err);
2555 if (ld->pdh == NULL) {
2556 /* We couldn't set up to write to the capture file. */
2557 /* XXX - use cf_open_error_message from tshark instead? */
2562 g_snprintf(errmsg, errmsg_len,
2563 "The file to which the capture would be"
2564 " saved (\"%s\") could not be opened: Error %d.",
2565 capture_opts->save_file, err);
2567 g_snprintf(errmsg, errmsg_len,
2568 "The file to which the capture would be"
2569 " saved (\"%s\") could not be opened: %s.",
2570 capture_opts->save_file, g_strerror(err));
2582 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2586 capture_src *pcap_src;
2587 guint64 end_time = create_timestamp();
2589 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2591 if (capture_opts->multi_files_on) {
2592 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2594 if (capture_opts->use_pcapng) {
2595 for (i = 0; i < global_ld.pcaps->len; i++) {
2596 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
2597 if (!pcap_src->from_cap_pipe) {
2598 guint64 isb_ifrecv, isb_ifdrop;
2599 struct pcap_stat stats;
2601 if (pcap_stats(pcap_src->pcap_h, &stats) >= 0) {
2602 isb_ifrecv = pcap_src->received;
2603 isb_ifdrop = stats.ps_drop + pcap_src->dropped + pcap_src->flushed;
2605 isb_ifrecv = G_MAXUINT64;
2606 isb_ifdrop = G_MAXUINT64;
2608 pcapng_write_interface_statistics_block(ld->pdh,
2611 "Counters provided by dumpcap",
2620 if (fclose(ld->pdh) == EOF) {
2621 if (err_close != NULL) {
2631 /* dispatch incoming packets (pcap or capture pipe)
2633 * Waits for incoming packets to be available, and calls pcap_dispatch()
2634 * to cause them to be processed.
2636 * Returns the number of packets which were processed.
2638 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2639 * packet-batching behaviour does not cause packets to get held back
2643 capture_loop_dispatch(loop_data *ld,
2644 char *errmsg, int errmsg_len, capture_src *pcap_src)
2647 gint packet_count_before;
2652 packet_count_before = ld->packet_count;
2653 if (pcap_src->from_cap_pipe) {
2654 /* dispatch from capture pipe */
2655 #ifdef LOG_CAPTURE_VERBOSE
2656 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2659 sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
2661 if (sel_ret < 0 && errno != EINTR) {
2662 g_snprintf(errmsg, errmsg_len,
2663 "Unexpected error from select: %s", g_strerror(errno));
2664 report_capture_error(errmsg, please_report);
2669 * "select()" says we can read from the pipe without blocking
2672 inpkts = cap_pipe_dispatch(ld, pcap_src, errmsg, errmsg_len);
2682 /* dispatch from pcap */
2683 #ifdef MUST_DO_SELECT
2685 * If we have "pcap_get_selectable_fd()", we use it to get the
2686 * descriptor on which to select; if that's -1, it means there
2687 * is no descriptor on which you can do a "select()" (perhaps
2688 * because you're capturing on a special device, and that device's
2689 * driver unfortunately doesn't support "select()", in which case
2690 * we don't do the select - which means it might not be possible
2691 * to stop a capture until a packet arrives. If that's unacceptable,
2692 * plead with whoever supplies the software for that device to add
2693 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2694 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2695 * later, so it can use pcap_breakloop().
2697 #ifdef LOG_CAPTURE_VERBOSE
2698 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2700 if (pcap_src->pcap_fd != -1) {
2701 sel_ret = cap_pipe_select(pcap_src->pcap_fd);
2704 * "select()" says we can read from it without blocking; go for
2707 * We don't have pcap_breakloop(), so we only process one packet
2708 * per pcap_dispatch() call, to allow a signal to stop the
2709 * processing immediately, rather than processing all packets
2710 * in a batch before quitting.
2713 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
2715 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
2719 /* Error, rather than pcap_breakloop(). */
2720 pcap_src->pcap_err = TRUE;
2722 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2725 if (sel_ret < 0 && errno != EINTR) {
2726 g_snprintf(errmsg, errmsg_len,
2727 "Unexpected error from select: %s", g_strerror(errno));
2728 report_capture_error(errmsg, please_report);
2734 #endif /* MUST_DO_SELECT */
2736 /* dispatch from pcap without select */
2738 #ifdef LOG_CAPTURE_VERBOSE
2739 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2743 * On Windows, we don't support asynchronously telling a process to
2744 * stop capturing; instead, we check for an indication on a pipe
2745 * after processing packets. We therefore process only one packet
2746 * at a time, so that we can check the pipe after every packet.
2749 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
2751 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
2755 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
2757 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_src);
2762 /* Error, rather than pcap_breakloop(). */
2763 pcap_src->pcap_err = TRUE;
2765 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2767 #else /* pcap_next_ex */
2768 #ifdef LOG_CAPTURE_VERBOSE
2769 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2771 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2774 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2775 * see https://wiki.wireshark.org/CaptureSetup/WinPcapRemote
2776 * This should be fixed in the WinPcap 4.0 alpha release.
2778 * For reference, an example remote interface:
2779 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2782 /* emulate dispatch from pcap */
2785 struct pcap_pkthdr *pkt_header;
2790 (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
2792 capture_loop_queue_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
2794 capture_loop_write_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
2799 pcap_src->pcap_err = TRUE;
2803 #endif /* pcap_next_ex */
2807 #ifdef LOG_CAPTURE_VERBOSE
2808 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2811 return ld->packet_count - packet_count_before;
2815 /* Isolate the Universally Unique Identifier from the interface. Basically, we
2816 * want to grab only the characters between the '{' and '}' delimiters.
2818 * Returns a GString that must be freed with g_string_free(). */
2820 isolate_uuid(const char *iface)
2825 ptr = strchr(iface, '{');
2827 return g_string_new(iface);
2828 gstr = g_string_new(ptr + 1);
2830 ptr = strchr(gstr->str, '}');
2834 gstr = g_string_truncate(gstr, ptr - gstr->str);
2839 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2840 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2842 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2843 char *errmsg, int errmsg_len)
2846 gchar *capfile_name;
2847 gchar *prefix, *suffix;
2848 gboolean is_tempfile;
2850 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2851 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
2853 if (capture_opts->save_file != NULL) {
2854 /* We return to the caller while the capture is in progress.
2855 * Therefore we need to take a copy of save_file in
2856 * case the caller destroys it after we return.
2858 capfile_name = g_strdup(capture_opts->save_file);
2860 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2861 if (capture_opts->multi_files_on) {
2862 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2863 g_snprintf(errmsg, errmsg_len,
2864 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2865 g_free(capfile_name);
2868 if (strcmp(capfile_name, "-") == 0) {
2869 /* write to stdout */
2872 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2873 _setmode(1, O_BINARY);
2876 } /* if (...output_to_pipe ... */
2879 if (capture_opts->multi_files_on) {
2880 /* ringbuffer is enabled */
2881 *save_file_fd = ringbuf_init(capfile_name,
2882 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
2883 capture_opts->group_read_access);
2885 /* we need the ringbuf name */
2886 if (*save_file_fd != -1) {
2887 g_free(capfile_name);
2888 capfile_name = g_strdup(ringbuf_current_filename());
2891 /* Try to open/create the specified file for use as a capture buffer. */
2892 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2893 (capture_opts->group_read_access) ? 0640 : 0600);
2896 is_tempfile = FALSE;
2898 /* Choose a random name for the temporary capture buffer */
2899 if (global_capture_opts.ifaces->len > 1) {
2900 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
2901 if (capture_opts->use_pcapng) {
2908 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
2910 /* use the generic portion of the interface guid to form the basis of the filename */
2911 if (strncmp("NPF_{", basename, 5)==0)
2913 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
2915 iface = isolate_uuid(basename);
2917 basename = g_strdup(iface->str);
2918 g_string_free(iface, TRUE);
2921 /* generate the temp file name prefix and suffix */
2922 if (capture_opts->use_pcapng) {
2923 prefix = g_strconcat("wireshark_", basename, NULL);
2926 prefix = g_strconcat("wireshark_", basename, NULL);
2931 *save_file_fd = create_tempfile(&tmpname, prefix, suffix);
2933 capfile_name = g_strdup(tmpname);
2937 /* did we fail to open the output file? */
2938 if (*save_file_fd == -1) {
2940 g_snprintf(errmsg, errmsg_len,
2941 "The temporary file to which the capture would be saved (\"%s\") "
2942 "could not be opened: %s.", capfile_name, g_strerror(errno));
2944 if (capture_opts->multi_files_on) {
2945 ringbuf_error_cleanup();
2948 g_snprintf(errmsg, errmsg_len,
2949 "The file to which the capture would be saved (\"%s\") "
2950 "could not be opened: %s.", capfile_name,
2953 g_free(capfile_name);
2957 if (capture_opts->save_file != NULL) {
2958 g_free(capture_opts->save_file);
2960 capture_opts->save_file = capfile_name;
2961 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2962 "g_free(capfile_name)". */
2968 /* Do the work of handling either the file size or file duration capture
2969 conditions being reached, and switching files or stopping. */
2971 do_file_switch_or_stop(capture_options *capture_opts,
2972 condition *cnd_autostop_files,
2973 condition *cnd_autostop_size,
2974 condition *cnd_file_duration,
2975 condition *cnd_file_interval)
2978 capture_src *pcap_src;
2979 interface_options interface_opts;
2980 gboolean successful;
2982 if (capture_opts->multi_files_on) {
2983 if (cnd_autostop_files != NULL &&
2984 cnd_eval(cnd_autostop_files, (guint64)++global_ld.autostop_files)) {
2985 /* no files left: stop here */
2986 global_ld.go = FALSE;
2990 /* Switch to the next ringbuffer file */
2991 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2992 &global_ld.save_file_fd, &global_ld.err)) {
2994 /* File switch succeeded: reset the conditions */
2995 global_ld.bytes_written = 0;
2996 if (capture_opts->use_pcapng) {
2998 GString *cpu_info_str;
2999 GString *os_info_str;
3001 cpu_info_str = g_string_new("");
3002 os_info_str = g_string_new("");
3003 get_cpu_info(cpu_info_str);
3004 get_os_version_info(os_info_str);
3006 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
3007 successful = pcapng_write_session_header_block(global_ld.pdh,
3008 (const char *)capture_opts->capture_comment, /* Comment */
3009 cpu_info_str->str, /* HW */
3010 os_info_str->str, /* OS */
3012 -1, /* section_length */
3013 &(global_ld.bytes_written),
3015 g_string_free(cpu_info_str, TRUE);
3018 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3019 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3020 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3021 successful = pcapng_write_interface_description_block(global_ld.pdh,
3022 NULL, /* OPT_COMMENT 1 */
3023 interface_opts.name, /* IDB_NAME 2 */
3024 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3025 interface_opts.cfilter, /* IDB_FILTER 11 */
3026 os_info_str->str, /* IDB_OS 12 */
3029 &(global_ld.bytes_written),
3030 0, /* IDB_IF_SPEED 8 */
3031 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3035 g_string_free(os_info_str, TRUE);
3038 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3039 successful = libpcap_write_file_header(global_ld.pdh, pcap_src->linktype, pcap_src->snaplen,
3040 pcap_src->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3043 fclose(global_ld.pdh);
3044 global_ld.pdh = NULL;
3045 global_ld.go = FALSE;
3048 if (cnd_autostop_size)
3049 cnd_reset(cnd_autostop_size);
3050 if (cnd_file_duration)
3051 cnd_reset(cnd_file_duration);
3052 if (cnd_file_interval)
3053 cnd_reset(cnd_file_interval);
3054 fflush(global_ld.pdh);
3056 report_packet_count(global_ld.inpkts_to_sync_pipe);
3057 global_ld.inpkts_to_sync_pipe = 0;
3058 report_new_capture_file(capture_opts->save_file);
3060 /* File switch failed: stop here */
3061 global_ld.go = FALSE;
3065 /* single file, stop now */
3066 global_ld.go = FALSE;
3073 pcap_read_handler(void* arg)
3075 capture_src *pcap_src;
3076 char errmsg[MSG_MAX_LENGTH+1];
3078 pcap_src = (capture_src *)arg;
3080 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3081 pcap_src->interface_id);
3083 while (global_ld.go) {
3084 /* dispatch incoming packets */
3085 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_src);
3087 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3088 pcap_src->interface_id);
3089 g_thread_exit(NULL);
3093 /* Do the low-level work of a capture.
3094 Returns TRUE if it succeeds, FALSE otherwise. */
3096 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3099 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3101 struct timeval upd_time, cur_time;
3105 condition *cnd_file_duration = NULL;
3106 condition *cnd_file_interval = NULL;
3107 condition *cnd_autostop_files = NULL;
3108 condition *cnd_autostop_size = NULL;
3109 condition *cnd_autostop_duration = NULL;
3112 gboolean cfilter_error = FALSE;
3113 char errmsg[MSG_MAX_LENGTH+1];
3114 char secondary_errmsg[MSG_MAX_LENGTH+1];
3115 capture_src *pcap_src;
3116 interface_options interface_opts;
3117 guint i, error_index = 0;
3120 *secondary_errmsg = '\0';
3122 /* init the loop data */
3123 global_ld.go = TRUE;
3124 global_ld.packet_count = 0;
3126 global_ld.report_packet_count = FALSE;
3128 if (capture_opts->has_autostop_packets)
3129 global_ld.packet_max = capture_opts->autostop_packets;
3131 global_ld.packet_max = 0; /* no limit */
3132 global_ld.inpkts_to_sync_pipe = 0;
3133 global_ld.err = 0; /* no error seen yet */
3134 global_ld.pdh = NULL;
3135 global_ld.autostop_files = 0;
3136 global_ld.save_file_fd = -1;
3138 /* We haven't yet gotten the capture statistics. */
3139 *stats_known = FALSE;
3141 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3142 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3144 /* open the "input file" from network interface or capture pipe */
3145 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3146 secondary_errmsg, sizeof(secondary_errmsg))) {
3149 for (i = 0; i < capture_opts->ifaces->len; i++) {
3150 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3151 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3152 /* init the input filter from the network interface (capture pipe will do nothing) */
3154 * When remote capturing WinPCap crashes when the capture filter
3155 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3158 switch (capture_loop_init_filter(pcap_src->pcap_h, pcap_src->from_cap_pipe,
3159 interface_opts.name,
3160 interface_opts.cfilter?interface_opts.cfilter:"")) {
3162 case INITFILTER_NO_ERROR:
3165 case INITFILTER_BAD_FILTER:
3166 cfilter_error = TRUE;
3168 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
3171 case INITFILTER_OTHER_ERROR:
3172 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3173 pcap_geterr(pcap_src->pcap_h));
3174 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3179 /* If we're supposed to write to a capture file, open it for output
3180 (temporary/specified name/ringbuffer) */
3181 if (capture_opts->saving_to_file) {
3182 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3183 errmsg, sizeof(errmsg))) {
3187 /* set up to write to the already-opened capture output file/files */
3188 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3193 /* XXX - capture SIGTERM and close the capture, in case we're on a
3194 Linux 2.0[.x] system and you have to explicitly close the capture
3195 stream in order to turn promiscuous mode off? We need to do that
3196 in other places as well - and I don't think that works all the
3197 time in any case, due to libpcap bugs. */
3199 /* Well, we should be able to start capturing.
3201 Sync out the capture file, so the header makes it to the file system,
3202 and send a "capture started successfully and capture file created"
3203 message to our parent so that they'll open the capture file and
3204 update its windows to indicate that we have a live capture in
3206 fflush(global_ld.pdh);
3207 report_new_capture_file(capture_opts->save_file);
3210 /* initialize capture stop (and alike) conditions */
3211 init_capture_stop_conditions();
3212 /* create stop conditions */
3213 if (capture_opts->has_autostop_filesize) {
3214 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3215 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3218 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3220 if (capture_opts->has_autostop_duration)
3221 cnd_autostop_duration =
3222 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3224 if (capture_opts->multi_files_on) {
3225 if (capture_opts->has_file_duration)
3227 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3229 if (capture_opts->has_autostop_files)
3230 cnd_autostop_files =
3231 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_files);
3233 if (capture_opts->has_file_interval)
3235 cnd_new(CND_CLASS_INTERVAL, capture_opts->file_interval);
3238 /* init the time values */
3240 upd_time = GetTickCount();
3242 gettimeofday(&upd_time, NULL);
3244 start_time = create_timestamp();
3245 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3246 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3248 /* WOW, everything is prepared! */
3249 /* please fasten your seat belts, we will enter now the actual capture loop */
3251 pcap_queue = g_async_queue_new();
3252 pcap_queue_bytes = 0;
3253 pcap_queue_packets = 0;
3254 for (i = 0; i < global_ld.pcaps->len; i++) {
3255 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3256 #if GLIB_CHECK_VERSION(2,31,0)
3257 /* XXX - Add an interface name here? */
3258 pcap_src->tid = g_thread_new("Capture read", pcap_read_handler, pcap_src);
3260 pcap_src->tid = g_thread_create(pcap_read_handler, pcap_src, TRUE, NULL);
3264 while (global_ld.go) {
3265 /* dispatch incoming packets */
3267 pcap_queue_element *queue_element;
3268 #if GLIB_CHECK_VERSION(2,31,18)
3270 g_async_queue_lock(pcap_queue);
3271 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3273 GTimeVal write_thread_time;
3275 g_get_current_time(&write_thread_time);
3276 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3277 g_async_queue_lock(pcap_queue);
3278 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3280 if (queue_element) {
3281 pcap_queue_bytes -= queue_element->phdr.caplen;
3282 pcap_queue_packets -= 1;
3284 g_async_queue_unlock(pcap_queue);
3285 if (queue_element) {
3286 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3287 "Dequeued a packet of length %d captured on interface %d.",
3288 queue_element->phdr.caplen, queue_element->pcap_src->interface_id);
3290 capture_loop_write_packet_cb((u_char *) queue_element->pcap_src,
3291 &queue_element->phdr,
3293 g_free(queue_element->pd);
3294 g_free(queue_element);
3300 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3301 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3302 sizeof(errmsg), pcap_src);
3305 /* Were we asked to print packet counts by the SIGINFO handler? */
3306 if (global_ld.report_packet_count) {
3307 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3308 plurality(global_ld.packet_count, "", "s"));
3309 global_ld.report_packet_count = FALSE;
3314 /* any news from our parent (signal pipe)? -> just stop the capture */
3315 if (!signal_pipe_check_running()) {
3316 global_ld.go = FALSE;
3321 global_ld.inpkts_to_sync_pipe += inpkts;
3323 /* check capture size condition */
3324 if (cnd_autostop_size != NULL &&
3325 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3326 /* Capture size limit reached, do we have another file? */
3327 if (!do_file_switch_or_stop(capture_opts,
3333 } /* cnd_autostop_size */
3334 if (capture_opts->output_to_pipe) {
3335 fflush(global_ld.pdh);
3339 /* Only update once every 500ms so as not to overload slow displays.
3340 * This also prevents too much context-switching between the dumpcap
3341 * and wireshark processes.
3343 #define DUMPCAP_UPD_TIME 500
3346 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3347 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3349 gettimeofday(&cur_time, NULL);
3350 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3351 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3354 upd_time = cur_time;
3357 if (pcap_stats(pch, stats) >= 0) {
3358 *stats_known = TRUE;
3361 /* Let the parent process know. */
3362 if (global_ld.inpkts_to_sync_pipe) {
3364 fflush(global_ld.pdh);
3366 /* Send our parent a message saying we've written out
3367 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3369 report_packet_count(global_ld.inpkts_to_sync_pipe);
3371 global_ld.inpkts_to_sync_pipe = 0;
3374 /* check capture duration condition */
3375 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3376 /* The maximum capture time has elapsed; stop the capture. */
3377 global_ld.go = FALSE;
3381 /* check capture file duration condition */
3382 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3383 /* duration limit reached, do we have another file? */
3384 if (!do_file_switch_or_stop(capture_opts,
3390 } /* cnd_file_duration */
3392 /* check capture file interval condition */
3393 if (cnd_file_interval != NULL && cnd_eval(cnd_file_interval)) {
3394 /* end of interval reached, do we have another file? */
3395 if (!do_file_switch_or_stop(capture_opts,
3401 } /* cnd_file_interval */
3405 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3407 pcap_queue_element *queue_element;
3409 for (i = 0; i < global_ld.pcaps->len; i++) {
3410 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3411 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3412 pcap_src->interface_id);
3413 g_thread_join(pcap_src->tid);
3414 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3415 pcap_src->interface_id);
3418 g_async_queue_lock(pcap_queue);
3419 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3420 if (queue_element) {
3421 pcap_queue_bytes -= queue_element->phdr.caplen;
3422 pcap_queue_packets -= 1;
3424 g_async_queue_unlock(pcap_queue);
3425 if (queue_element == NULL) {
3428 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3429 "Dequeued a packet of length %d captured on interface %d.",
3430 queue_element->phdr.caplen, queue_element->pcap_src->interface_id);
3431 capture_loop_write_packet_cb((u_char *)queue_element->pcap_src,
3432 &queue_element->phdr,
3434 g_free(queue_element->pd);
3435 g_free(queue_element);
3436 global_ld.inpkts_to_sync_pipe += 1;
3437 if (capture_opts->output_to_pipe) {
3438 fflush(global_ld.pdh);
3444 /* delete stop conditions */
3445 if (cnd_file_duration != NULL)
3446 cnd_delete(cnd_file_duration);
3447 if (cnd_file_interval != NULL)
3448 cnd_delete(cnd_file_interval);
3449 if (cnd_autostop_files != NULL)
3450 cnd_delete(cnd_autostop_files);
3451 if (cnd_autostop_size != NULL)
3452 cnd_delete(cnd_autostop_size);
3453 if (cnd_autostop_duration != NULL)
3454 cnd_delete(cnd_autostop_duration);
3456 /* did we have a pcap (input) error? */
3457 for (i = 0; i < capture_opts->ifaces->len; i++) {
3458 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3459 if (pcap_src->pcap_err) {
3460 /* On Linux, if an interface goes down while you're capturing on it,
3461 you'll get a "recvfrom: Network is down" or
3462 "The interface went down" error (ENETDOWN).
3463 (At least you will if g_strerror() doesn't show a local translation
3466 On FreeBSD, DragonFly BSD, and macOS, if a network adapter
3467 disappears while you're capturing on it, you'll get a
3468 "read: Device not configured" error (ENXIO). (See previous
3469 parenthetical note.)
3471 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3473 These should *not* be reported to the Wireshark developers. */
3476 cap_err_str = pcap_geterr(pcap_src->pcap_h);
3477 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3478 strcmp(cap_err_str, "The interface went down") == 0 ||
3479 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3480 strcmp(cap_err_str, "read: I/O error") == 0 ||
3481 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3482 report_capture_error("The network adapter on which the capture was being done "
3483 "is no longer running; the capture has stopped.",
3486 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3488 report_capture_error(errmsg, please_report);
3491 } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
3492 report_capture_error(errmsg, "");
3496 /* did we have an output error while capturing? */
3497 if (global_ld.err == 0) {
3500 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3501 global_ld.err, FALSE);
3502 report_capture_error(errmsg, please_report);
3506 if (capture_opts->saving_to_file) {
3507 /* close the output file */
3508 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3512 /* there might be packets not yet notified to the parent */
3513 /* (do this after closing the file, so all packets are already flushed) */
3514 if (global_ld.inpkts_to_sync_pipe) {
3516 report_packet_count(global_ld.inpkts_to_sync_pipe);
3517 global_ld.inpkts_to_sync_pipe = 0;
3520 /* If we've displayed a message about a write error, there's no point
3521 in displaying another message about an error on close. */
3522 if (!close_ok && write_ok) {
3523 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3525 report_capture_error(errmsg, "");
3529 * XXX We exhibit different behaviour between normal mode and sync mode
3530 * when the pipe is stdin and not already at EOF. If we're a child, the
3531 * parent's stdin isn't closed, so if the user starts another capture,
3532 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3533 * will say "Unrecognized libpcap format". On the other hand, in normal
3534 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3537 report_capture_count(TRUE);
3539 /* get packet drop statistics from pcap */
3540 for (i = 0; i < capture_opts->ifaces->len; i++) {
3542 guint32 pcap_dropped = 0;
3544 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3545 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3546 received = pcap_src->received;
3547 if (pcap_src->pcap_h != NULL) {
3548 g_assert(!pcap_src->from_cap_pipe);
3549 /* Get the capture statistics, so we know how many packets were dropped. */
3551 * Older versions of libpcap didn't set ps_ifdrop on some
3552 * platforms; initialize it to 0 to handle that.
3554 stats->ps_ifdrop = 0;
3555 if (pcap_stats(pcap_src->pcap_h, stats) >= 0) {
3556 *stats_known = TRUE;
3557 /* Let the parent process know. */
3558 pcap_dropped += stats->ps_drop;
3560 g_snprintf(errmsg, sizeof(errmsg),
3561 "Can't get packet-drop statistics: %s",
3562 pcap_geterr(pcap_src->pcap_h));
3563 report_capture_error(errmsg, please_report);
3566 report_packet_drops(received, pcap_dropped, pcap_src->dropped, pcap_src->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
3569 /* close the input file (pcap or capture pipe) */
3570 capture_loop_close_input(&global_ld);
3572 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
3574 /* ok, if the write and the close were successful. */
3575 return write_ok && close_ok;
3578 if (capture_opts->multi_files_on) {
3579 /* cleanup ringbuffer */
3580 ringbuf_error_cleanup();
3582 /* We can't use the save file, and we have no FILE * for the stream
3583 to close in order to close it, so close the FD directly. */
3584 if (global_ld.save_file_fd != -1) {
3585 ws_close(global_ld.save_file_fd);
3588 /* We couldn't even start the capture, so get rid of the capture
3590 if (capture_opts->save_file != NULL) {
3591 ws_unlink(capture_opts->save_file);
3592 g_free(capture_opts->save_file);
3595 capture_opts->save_file = NULL;
3597 report_cfilter_error(capture_opts, error_index, errmsg);
3599 report_capture_error(errmsg, secondary_errmsg);
3601 /* close the input file (pcap or cap_pipe) */
3602 capture_loop_close_input(&global_ld);
3604 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3611 capture_loop_stop(void)
3613 #ifdef HAVE_PCAP_BREAKLOOP
3615 capture_src *pcap_src;
3617 for (i = 0; i < global_ld.pcaps->len; i++) {
3618 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3619 if (pcap_src->pcap_h != NULL)
3620 pcap_breakloop(pcap_src->pcap_h);
3623 global_ld.go = FALSE;
3628 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3629 int err, gboolean is_close)
3634 g_snprintf(errmsg, errmsglen,
3635 "Not all the packets could be written to the file"
3636 " to which the capture was being saved\n"
3637 "(\"%s\") because there is no space left on the file system\n"
3638 "on which that file resides.",
3644 g_snprintf(errmsg, errmsglen,
3645 "Not all the packets could be written to the file"
3646 " to which the capture was being saved\n"
3647 "(\"%s\") because you are too close to, or over,"
3648 " your disk quota\n"
3649 "on the file system on which that file resides.",
3656 g_snprintf(errmsg, errmsglen,
3657 "The file to which the capture was being saved\n"
3658 "(\"%s\") could not be closed: %s.",
3659 fname, g_strerror(err));
3661 g_snprintf(errmsg, errmsglen,
3662 "An error occurred while writing to the file"
3663 " to which the capture was being saved\n"
3665 fname, g_strerror(err));
3672 /* one packet was captured, process it */
3674 capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
3677 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
3679 guint ts_mul = pcap_src->ts_nsec ? 1000000000 : 1000000;
3681 /* We may be called multiple times from pcap_dispatch(); if we've set
3682 the "stop capturing" flag, ignore this packet, as we're not
3683 supposed to be saving any more packets. */
3684 if (!global_ld.go) {
3685 pcap_src->flushed++;
3689 if (global_ld.pdh) {
3690 gboolean successful;
3692 /* We're supposed to write the packet to a file; do so.
3693 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3694 "ld->err" to the error. */
3695 if (global_capture_opts.use_pcapng) {
3696 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
3698 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3699 phdr->caplen, phdr->len,
3700 pcap_src->interface_id,
3703 &global_ld.bytes_written, &err);
3705 successful = libpcap_write_packet(global_ld.pdh,
3706 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3707 phdr->caplen, phdr->len,
3709 &global_ld.bytes_written, &err);
3712 global_ld.go = FALSE;
3713 global_ld.err = err;
3714 pcap_src->dropped++;
3716 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3717 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3718 "Wrote a packet of length %d captured on interface %u.",
3719 phdr->caplen, pcap_src->interface_id);
3721 global_ld.packet_count++;
3722 pcap_src->received++;
3723 /* if the user told us to stop after x packets, do we already have enough? */
3724 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
3725 global_ld.go = FALSE;
3731 /* one packet was captured, queue it */
3733 capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
3736 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
3737 pcap_queue_element *queue_element;
3738 gboolean limit_reached;
3740 /* We may be called multiple times from pcap_dispatch(); if we've set
3741 the "stop capturing" flag, ignore this packet, as we're not
3742 supposed to be saving any more packets. */
3743 if (!global_ld.go) {
3744 pcap_src->flushed++;
3748 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
3749 if (queue_element == NULL) {
3750 pcap_src->dropped++;
3753 queue_element->pcap_src = pcap_src;
3754 queue_element->phdr = *phdr;
3755 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
3756 if (queue_element->pd == NULL) {
3757 pcap_src->dropped++;
3758 g_free(queue_element);
3761 memcpy(queue_element->pd, pd, phdr->caplen);
3762 g_async_queue_lock(pcap_queue);
3763 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
3764 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
3765 limit_reached = FALSE;
3766 g_async_queue_push_unlocked(pcap_queue, queue_element);
3767 pcap_queue_bytes += phdr->caplen;
3768 pcap_queue_packets += 1;
3770 limit_reached = TRUE;
3772 g_async_queue_unlock(pcap_queue);
3773 if (limit_reached) {
3774 pcap_src->dropped++;
3775 g_free(queue_element->pd);
3776 g_free(queue_element);
3777 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3778 "Dropped a packet of length %d captured on interface %u.",
3779 phdr->caplen, pcap_src->interface_id);
3781 pcap_src->received++;
3782 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3783 "Queued a packet of length %d captured on interface %u.",
3784 phdr->caplen, pcap_src->interface_id);
3786 /* I don't want to hold the mutex over the debug output. So the
3787 output may be wrong */
3788 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3789 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
3790 pcap_queue_bytes, pcap_queue_packets);
3794 set_80211_channel(const char *iface, const char *opt)
3798 guint32 center_freq1 = 0;
3799 guint32 center_freq2 = 0;
3802 gchar **options = NULL;
3804 options = g_strsplit_set(opt, ",", 4);
3805 for (args = 0; options[args]; args++);
3808 freq = get_nonzero_guint32(options[0], "802.11 channel frequency");
3810 if (args >= 1 && options[1]) {
3811 type = ws80211_str_to_chan_type(options[1]);
3813 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
3819 if (args >= 2 && options[2])
3820 center_freq1 = get_nonzero_guint32(options[2], "VHT center frequency");
3822 if (args >= 3 && options[3])
3823 center_freq2 = get_nonzero_guint32(options[3], "VHT center frequency 2");
3825 ret = ws80211_init();
3827 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
3831 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
3834 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
3840 pipe_write_block(2, SP_SUCCESS, NULL);
3843 g_strfreev(options);
3848 get_dumpcap_compiled_info(GString *str)
3850 /* Capture libraries */
3851 g_string_append(str, ", ");
3852 get_compiled_caplibs_version(str);
3856 get_dumpcap_runtime_info(GString *str)
3858 /* Capture libraries */
3859 g_string_append(str, ", ");
3860 get_runtime_caplibs_version(str);
3863 /* And now our feature presentation... [ fade to music ] */
3865 main(int argc, char *argv[])
3867 GString *comp_info_str;
3868 GString *runtime_info_str;
3870 static const struct option long_options[] = {
3871 {"help", no_argument, NULL, 'h'},
3872 {"version", no_argument, NULL, 'v'},
3873 LONGOPT_CAPTURE_COMMON
3877 gboolean arg_error = FALSE;
3883 struct sigaction action, oldaction;
3886 gboolean start_capture = TRUE;
3887 gboolean stats_known;
3888 struct pcap_stat stats;
3889 GLogLevelFlags log_flags;
3890 gboolean list_interfaces = FALSE;
3891 gboolean list_link_layer_types = FALSE;
3892 #ifdef HAVE_BPF_IMAGE
3893 gboolean print_bpf_code = FALSE;
3895 gboolean set_chan = FALSE;
3896 gchar *set_chan_arg = NULL;
3897 gboolean machine_readable = FALSE;
3898 gboolean print_statistics = FALSE;
3899 int status, run_once_args = 0;
3902 #if defined(__APPLE__) && defined(__LP64__)
3903 struct utsname osinfo;
3907 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
3909 /* Get the compile-time version information string */
3910 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
3912 /* Get the run-time version information string */
3913 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
3915 /* Add it to the information to be reported on a crash. */
3916 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
3921 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
3922 g_string_free(comp_info_str, TRUE);
3923 g_string_free(runtime_info_str, TRUE);
3926 arg_list_utf_16to8(argc, argv);
3927 create_app_running_mutex();
3930 * Initialize our DLL search path. MUST be called before LoadLibrary
3933 ws_init_dll_search_path();
3936 #ifdef HAVE_BPF_IMAGE
3937 #define OPTSTRING_d "d"
3939 #define OPTSTRING_d ""
3942 #ifdef HAVE_PCAP_REMOTE
3943 #define OPTSTRING_r "r"
3944 #define OPTSTRING_u "u"
3946 #define OPTSTRING_r ""
3947 #define OPTSTRING_u ""
3950 #ifdef HAVE_PCAP_SETSAMPLING
3951 #define OPTSTRING_m "m:"
3953 #define OPTSTRING_m ""
3956 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
3958 #ifdef DEBUG_CHILD_DUMPCAP
3959 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3960 fprintf (stderr, "Unable to open debug log file .\n");
3965 #if defined(__APPLE__) && defined(__LP64__)
3967 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
3968 * a bug workaround - timeouts less than 1 second don't work with libpcap
3969 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3970 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
3971 * The problem is extremely unlikely to be reintroduced in a future
3974 if (uname(&osinfo) == 0) {
3976 * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
3977 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3978 * number of 10.0.0, not 10.1.0 - go figure).
3980 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
3981 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
3982 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
3983 need_timeout_workaround = TRUE;
3988 * Determine if dumpcap is being requested to run in a special
3989 * capture_child mode by going thru the command line args to see if
3990 * a -Z is present. (-Z is a hidden option).
3992 * The primary result of running in capture_child mode is that
3993 * all messages sent out on stderr are in a special type/len/string
3994 * format to allow message processing by type. These messages include
3995 * error messages if dumpcap fails to start the operation it was
3996 * requested to do, as well as various "status" messages which are sent
3997 * when an actual capture is in progress, and a "success" message sent
3998 * if dumpcap was requested to perform an operation other than a
4001 * Capture_child mode would normally be requested by a parent process
4002 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4003 * to which dumpcap stderr has been redirected. It might also have
4004 * another pipe to obtain dumpcap stdout output; for operations other
4005 * than a capture, that information is formatted specially for easier
4006 * parsing by the parent process.
4008 * Capture_child mode needs to be determined immediately upon
4009 * startup so that any messages generated by dumpcap in this mode
4010 * (eg: during initialization) will be formatted properly.
4013 for (i=1; i<argc; i++) {
4014 if (strcmp("-Z", argv[i]) == 0) {
4015 capture_child = TRUE;
4016 machine_readable = TRUE; /* request machine-readable output */
4018 /* set output pipe to binary mode, to avoid ugly text conversions */
4019 _setmode(2, O_BINARY);
4024 /* The default_log_handler will use stdout, which makes trouble in */
4025 /* capture child mode, as it uses stdout for its sync_pipe. */
4026 /* So: the filtering is done in the console_log_handler and not here.*/
4027 /* We set the log handlers right up front to make sure that any log */
4028 /* messages when running as child will be sent back to the parent */
4029 /* with the correct format. */
4034 G_LOG_LEVEL_CRITICAL|
4035 G_LOG_LEVEL_WARNING|
4036 G_LOG_LEVEL_MESSAGE|
4040 G_LOG_FLAG_RECURSION);
4042 g_log_set_handler(NULL,
4044 console_log_handler, NULL /* user_data */);
4045 g_log_set_handler(LOG_DOMAIN_MAIN,
4047 console_log_handler, NULL /* user_data */);
4048 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4050 console_log_handler, NULL /* user_data */);
4051 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4053 console_log_handler, NULL /* user_data */);
4055 /* Initialize the pcaps list */
4056 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(capture_src *));
4058 #if !GLIB_CHECK_VERSION(2,31,0)
4059 /* Initialize the thread system */
4060 g_thread_init(NULL);
4064 /* Load wpcap if possible. Do this before collecting the run-time version information */
4067 /* ... and also load the packet.dll from wpcap */
4068 /* XXX - currently not required, may change later. */
4069 /*wpcap_packet_load();*/
4071 /* Start windows sockets */
4072 result = WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4075 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_ERROR,
4076 "ERROR: WSAStartup failed with error: %d", result);
4080 /* Set handler for Ctrl+C key */
4081 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4083 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4084 and exit. Do the same with SIGPIPE, in case, for example,
4085 we're writing to our standard output and it's a pipe.
4086 Do the same with SIGHUP if it's not being ignored (if we're
4087 being run under nohup, it might be ignored, in which case we
4088 should leave it ignored).
4090 XXX - apparently, Coverity complained that part of action
4091 wasn't initialized. Perhaps it's running on Linux, where
4092 struct sigaction has an ignored "sa_restorer" element and
4093 where "sa_handler" and "sa_sigaction" might not be two
4094 members of a union. */
4095 memset(&action, 0, sizeof(action));
4096 action.sa_handler = capture_cleanup_handler;
4098 * Arrange that system calls not get restarted, because when
4099 * our signal handler returns we don't want to restart
4100 * a call that was waiting for packets to arrive.
4102 action.sa_flags = 0;
4103 sigemptyset(&action.sa_mask);
4104 sigaction(SIGTERM, &action, NULL);
4105 sigaction(SIGINT, &action, NULL);
4106 sigaction(SIGPIPE, &action, NULL);
4107 sigaction(SIGHUP, NULL, &oldaction);
4108 if (oldaction.sa_handler == SIG_DFL)
4109 sigaction(SIGHUP, &action, NULL);
4112 /* Catch SIGINFO and, if we get it and we're capturing in
4113 quiet mode, report the number of packets we've captured. */
4114 action.sa_handler = report_counts_siginfo;
4115 action.sa_flags = SA_RESTART;
4116 sigemptyset(&action.sa_mask);
4117 sigaction(SIGINFO, &action, NULL);
4118 #endif /* SIGINFO */
4122 enable_kernel_bpf_jit_compiler();
4125 /* ----------------------------------------------------------------- */
4126 /* Privilege and capability handling */
4128 /* 1. Running not as root or suid root; no special capabilities. */
4131 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4134 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4136 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4137 /* capabilities; Drop all other capabilities; */
4138 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4139 /* else: after pcap_open_live() in capture_loop_open_input() */
4140 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4141 /* (Note: this means that the process, although logged in */
4142 /* as root, does not have various permissions such as the */
4143 /* ability to bypass file access permissions). */
4144 /* XXX: Should we just leave capabilities alone in this case */
4145 /* so that user gets expected effect that root can do */
4148 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4150 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4151 /* else: after pcap_open_live() in capture_loop_open_input() */
4152 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4153 /* pcap_open_live). */
4155 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4157 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4158 /* capabilities; Drop all other capabilities; */
4159 /* Drop suid privileges (euid=ruid); */
4160 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4161 /* else: after pcap_open_live() in capture_loop_open_input() */
4162 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4164 /* XXX: For some Linux versions/distros with capabilities */
4165 /* a 'normal' process with any capabilities cannot be */
4166 /* 'killed' (signaled) from another (same uid) non-privileged */
4168 /* For example: If (non-suid) Wireshark forks a */
4169 /* child suid dumpcap which acts as described here (case 5), */
4170 /* Wireshark will be unable to kill (signal) the child */
4171 /* dumpcap process until the capabilities have been dropped */
4172 /* (after pcap_open_live()). */
4173 /* This behaviour will apparently be changed in the kernel */
4174 /* to allow the kill (signal) in this case. */
4175 /* See the following for details: */
4176 /* https://www.mail-archive.com/ [wrapped] */
4177 /* linux-security-module@vger.kernel.org/msg02913.html */
4179 /* It is therefore conceivable that if dumpcap somehow hangs */
4180 /* in pcap_open_live or before that wireshark will not */
4181 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4182 /* In this case, exiting wireshark will kill the child */
4183 /* dumpcap process. */
4185 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4186 /* capabilities; Using libcap. Note: capset cmd (which see) */
4187 /* used to assign capabilities to file. */
4189 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4190 /* else: after pcap_open_live() in capture_loop_open_input() */
4191 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4193 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4194 /* longer required (similar to capture). */
4196 /* ----------------------------------------------------------------- */
4198 init_process_policies();
4201 /* If 'started with special privileges' (and using libcap) */
4202 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4203 /* Set euid/egid = ruid/rgid to remove suid privileges */
4204 relinquish_privs_except_capture();
4207 /* Set the initial values in the capture options. This might be overwritten
4208 by the command line parameters. */
4209 capture_opts_init(&global_capture_opts);
4210 /* We always save to a file - if no file was specified, we save to a
4212 global_capture_opts.saving_to_file = TRUE;
4213 global_capture_opts.has_ring_num_files = TRUE;
4215 /* Pass on capture_child mode for capture_opts */
4216 global_capture_opts.capture_child = capture_child;
4218 /* Now get our args */
4219 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4221 case 'h': /* Print help and exit */
4222 printf("Dumpcap (Wireshark) %s\n"
4223 "Capture network packets and dump them into a pcapng or pcap file.\n"
4224 "See https://www.wireshark.org for more information.\n",
4225 get_ws_vcs_version_info());
4226 print_usage(stdout);
4229 case 'v': /* Show version and exit */
4230 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4231 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4232 show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4233 g_string_free(comp_info_str, TRUE);
4234 g_string_free(runtime_info_str, TRUE);
4237 /*** capture option specific ***/
4238 case 'a': /* autostop criteria */
4239 case 'b': /* Ringbuffer option */
4240 case 'c': /* Capture x packets */
4241 case 'f': /* capture filter */
4242 case 'g': /* enable group read access on file(s) */
4243 case 'i': /* Use interface x */
4244 case 'n': /* Use pcapng format */
4245 case 'p': /* Don't capture in promiscuous mode */
4246 case 'P': /* Use pcap format */
4247 case 's': /* Set the snapshot (capture) length */
4248 case 'w': /* Write to capture file x */
4249 case 'y': /* Set the pcap data link type */
4250 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4251 #ifdef HAVE_PCAP_REMOTE
4252 case 'u': /* Use UDP for data transfer */
4253 case 'r': /* Capture own RPCAP traffic too */
4254 case 'A': /* Authentication */
4256 #ifdef HAVE_PCAP_SETSAMPLING
4257 case 'm': /* Sampling */
4259 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4260 case 'B': /* Buffer size */
4262 #ifdef HAVE_PCAP_CREATE
4263 case 'I': /* Monitor mode */
4265 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4270 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4272 capture_child = TRUE;
4274 /* set output pipe to binary mode, to avoid ugly text conversions */
4275 _setmode(2, O_BINARY);
4277 * optarg = the control ID, aka the PPID, currently used for the
4280 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4281 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4282 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4283 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4285 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4286 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4287 "Signal pipe: Unable to open %s. Dead parent?",
4295 case 'q': /* Quiet */
4301 /*** all non capture option specific ***/
4302 case 'D': /* Print a list of capture devices and exit */
4303 if (!list_interfaces) {
4304 list_interfaces = TRUE;
4308 case 'L': /* Print list of link-layer types and exit */
4309 if (!list_link_layer_types) {
4310 list_link_layer_types = TRUE;
4314 #ifdef HAVE_BPF_IMAGE
4315 case 'd': /* Print BPF code for capture filter and exit */
4316 if (!print_bpf_code) {
4317 print_bpf_code = TRUE;
4322 case 'S': /* Print interface statistics once a second */
4323 if (!print_statistics) {
4324 print_statistics = TRUE;
4328 case 'k': /* Set wireless channel */
4331 set_chan_arg = optarg;
4334 cmdarg_err("Only one -k flag may be specified");
4338 case 'M': /* For -D, -L, and -S, print machine-readable output */
4339 machine_readable = TRUE;
4342 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4345 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4348 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4350 case '?': /* Bad flag - print usage message */
4359 /* user specified file name as regular command-line argument */
4360 /* XXX - use it as the capture file name (or something else)? */
4366 * Extra command line arguments were specified; complain.
4367 * XXX - interpret as capture filter, as tcpdump and tshark do?
4369 cmdarg_err("Invalid argument: %s", argv[0]);
4374 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4377 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4378 /* Use some default if the user hasn't specified some */
4379 /* XXX: Are these defaults good enough? */
4380 pcap_queue_byte_limit = 1000 * 1000;
4381 pcap_queue_packet_limit = 1000;
4384 print_usage(stderr);
4388 if (run_once_args > 1) {
4389 #ifdef HAVE_BPF_IMAGE
4390 cmdarg_err("Only one of -D, -L, -d, -k, or -S may be supplied.");
4392 cmdarg_err("Only one of -D, -L, -k, or -S may be supplied.");
4395 } else if (run_once_args == 1) {
4396 /* We're supposed to print some information, rather than
4397 to capture traffic; did they specify a ring buffer option? */
4398 if (global_capture_opts.multi_files_on) {
4399 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4403 /* We're supposed to capture traffic; */
4405 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4406 if (global_capture_opts.ifaces->len > 1) {
4408 global_capture_opts.use_pcapng = TRUE;
4411 if (global_capture_opts.capture_comment &&
4412 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4413 /* XXX - for ringbuffer, should we apply the comment to each file? */
4414 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4418 /* Was the ring buffer option specified and, if so, does it make sense? */
4419 if (global_capture_opts.multi_files_on) {
4420 /* Ring buffer works only under certain conditions:
4421 a) ring buffer does not work with temporary files;
4422 b) it makes no sense to enable the ring buffer if the maximum
4423 file size is set to "infinite". */
4424 if (global_capture_opts.save_file == NULL) {
4425 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4426 global_capture_opts.multi_files_on = FALSE;
4428 if (!global_capture_opts.has_autostop_filesize &&
4429 !global_capture_opts.has_file_duration &&
4430 !global_capture_opts.has_file_interval) {
4431 cmdarg_err("Ring buffer requested, but no maximum capture file size, duration"
4432 "or interval were specified.");
4434 /* XXX - this must be redesigned as the conditions changed */
4435 global_capture_opts.multi_files_on = FALSE;
4438 if (global_capture_opts.has_file_duration && global_capture_opts.has_file_interval) {
4439 cmdarg_err("Ring buffer file duration and interval can't be used at the same time.");
4446 * "-D" requires no interface to be selected; it's supposed to list
4449 if (list_interfaces) {
4450 /* Get the list of interfaces */
4455 if_list = capture_interface_list(&err, &err_str,NULL);
4456 if (if_list == NULL) {
4459 * If we're being run by another program, just give them
4460 * an empty list of interfaces, don't report this as
4461 * an error; that lets them decide whether to report
4462 * this as an error or not.
4464 if (!machine_readable) {
4465 cmdarg_err("There are no interfaces on which a capture can be done");
4469 cmdarg_err("%s", err_str);
4475 if (machine_readable) /* tab-separated values to stdout */
4476 print_machine_readable_interfaces(if_list);
4478 capture_opts_print_interfaces(if_list);
4479 free_interface_list(if_list);
4484 * "-S" requires no interface to be selected; it gives statistics
4485 * for all interfaces.
4487 if (print_statistics) {
4488 status = print_statistics_loop(machine_readable);
4493 interface_options interface_opts;
4495 if (global_capture_opts.ifaces->len != 1) {
4496 cmdarg_err("Need one interface");
4500 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4501 status = set_80211_channel(interface_opts.name, set_chan_arg);
4506 * "-L", "-d", and capturing act on a particular interface, so we have to
4507 * have an interface; if none was specified, pick a default.
4509 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4511 /* cmdarg_err() already called .... */
4515 if (list_link_layer_types) {
4516 /* Get the list of link-layer types for the capture device. */
4517 if_capabilities_t *caps;
4521 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4522 interface_options interface_opts;
4524 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4526 caps = get_if_capabilities(&interface_opts, &err_str);
4528 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4529 "Please check to make sure you have sufficient permissions, and that\n"
4530 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4534 if (caps->data_link_types == NULL) {
4535 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4538 if (machine_readable) /* tab-separated values to stdout */
4539 /* XXX: We need to change the format and adopt consumers */
4540 print_machine_readable_if_capabilities(caps);
4542 /* XXX: We might want to print also the interface name */
4543 capture_opts_print_if_capabilities(caps, interface_opts.name,
4544 interface_opts.monitor_mode);
4545 free_if_capabilities(caps);
4550 /* We're supposed to do a capture, or print the BPF code for a filter. */
4552 /* Let the user know what interfaces were chosen. */
4553 if (capture_child) {
4554 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4555 interface_options interface_opts;
4557 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4558 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4559 interface_opts.name);
4562 str = g_string_new("");
4564 if (global_capture_opts.ifaces->len < 2)
4566 if (global_capture_opts.ifaces->len < 4)
4569 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4570 interface_options interface_opts;
4572 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4574 if (global_capture_opts.ifaces->len > 2) {
4575 g_string_append_printf(str, ",");
4577 g_string_append_printf(str, " ");
4578 if (j == global_capture_opts.ifaces->len - 1) {
4579 g_string_append_printf(str, "and ");
4582 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4585 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4587 fprintf(stderr, "Capturing on %s\n", str->str);
4588 g_string_free(str, TRUE);
4591 /* Process the snapshot length, as that affects the generated BPF code. */
4592 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4594 #ifdef HAVE_BPF_IMAGE
4595 if (print_bpf_code) {
4596 show_filter_code(&global_capture_opts);
4601 /* We're supposed to do a capture. Process the ring buffer arguments. */
4602 capture_opts_trim_ring_num_files(&global_capture_opts);
4604 /* flush stderr prior to starting the main capture loop */
4607 /* Now start the capture. */
4608 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4612 /* capture failed */
4615 return 0; /* never here, make compiler happy */
4620 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4621 const char *message, gpointer user_data _U_)
4628 /* ignore log message, if log_level isn't interesting */
4629 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4630 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4635 switch(log_level & G_LOG_LEVEL_MASK) {
4636 case G_LOG_LEVEL_ERROR:
4639 case G_LOG_LEVEL_CRITICAL:
4642 case G_LOG_LEVEL_WARNING:
4645 case G_LOG_LEVEL_MESSAGE:
4648 case G_LOG_LEVEL_INFO:
4651 case G_LOG_LEVEL_DEBUG:
4655 fprintf(stderr, "unknown log_level %d\n", log_level);
4657 g_assert_not_reached();
4660 /* Generate the output message */
4661 if (log_level & G_LOG_LEVEL_MESSAGE) {
4662 /* normal user messages without additional infos */
4663 msg = g_strdup_printf("%s\n", message);
4665 /* create a "timestamp" */
4667 today = localtime(&curr);
4669 /* info/debug messages with additional infos */
4671 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4672 today->tm_hour, today->tm_min, today->tm_sec,
4673 log_domain != NULL ? log_domain : "",
4676 msg = g_strdup_printf("Time not representable %8s %s %s\n",
4677 log_domain != NULL ? log_domain : "",
4681 /* DEBUG & INFO msgs (if we're debugging today) */
4682 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4683 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4684 #ifdef DEBUG_DUMPCAP
4685 fprintf(stderr, "%s", msg);
4688 #ifdef DEBUG_CHILD_DUMPCAP
4689 fprintf(debug_log, "%s", msg);
4697 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4698 /* to parent especially formatted if dumpcap running as child. */
4699 if (capture_child) {
4700 sync_pipe_errmsg_to_parent(2, msg, "");
4702 fprintf(stderr, "%s", msg);
4709 /****************************************************************************************************************/
4710 /* indication report routines */
4714 report_packet_count(unsigned int packet_count)
4716 char tmp[SP_DECISIZE+1+1];
4717 static unsigned int count = 0;
4719 if (capture_child) {
4720 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
4721 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4722 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4724 count += packet_count;
4725 fprintf(stderr, "\rPackets: %u ", count);
4726 /* stderr could be line buffered */
4732 report_new_capture_file(const char *filename)
4734 if (capture_child) {
4735 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4736 pipe_write_block(2, SP_FILE, filename);
4740 * Prevent a SIGINFO handler from writing to the standard error
4741 * while we're doing so; instead, have it just set a flag telling
4742 * us to print that information when we're done.
4745 #endif /* SIGINFO */
4746 fprintf(stderr, "File: %s\n", filename);
4747 /* stderr could be line buffered */
4752 * Allow SIGINFO handlers to write.
4757 * If a SIGINFO handler asked us to write out capture counts, do so.
4760 report_counts_for_siginfo();
4761 #endif /* SIGINFO */
4766 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4768 interface_options interface_opts;
4769 char tmp[MSG_MAX_LENGTH+1+6];
4771 if (i < capture_opts->ifaces->len) {
4772 if (capture_child) {
4773 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4774 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4775 pipe_write_block(2, SP_BAD_FILTER, tmp);
4778 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
4779 * the error message below.
4781 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
4783 "Invalid capture filter \"%s\" for interface '%s'.\n"
4785 "That string isn't a valid capture filter (%s).\n"
4786 "See the User's Guide for a description of the capture filter syntax.",
4787 interface_opts.cfilter, interface_opts.name, errmsg);
4793 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4795 if (capture_child) {
4796 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4797 "Primary Error: %s", error_msg);
4798 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4799 "Secondary Error: %s", secondary_error_msg);
4800 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4802 cmdarg_err("%s", error_msg);
4803 if (secondary_error_msg[0] != '\0')
4804 cmdarg_err_cont("%s", secondary_error_msg);
4809 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
4811 char tmp[SP_DECISIZE+1+1];
4812 guint32 total_drops = pcap_drops + drops + flushed;
4814 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
4816 if (capture_child) {
4817 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4818 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
4819 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
4820 /* XXX: Need to provide interface id, changes to consumers required. */
4821 pipe_write_block(2, SP_DROPS, tmp);
4824 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
4825 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
4826 received ? 100.0 * received / (received + total_drops) : 0.0);
4827 /* stderr could be line buffered */
4833 /************************************************************************************************/
4834 /* signal_pipe handling */
4839 signal_pipe_check_running(void)
4841 /* any news from our parent? -> just stop the capture */
4845 /* if we are running standalone, no check required */
4846 if (!capture_child) {
4850 if (!sig_pipe_name || !sig_pipe_handle) {
4851 /* This shouldn't happen */
4852 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4853 "Signal pipe: No name or handle");
4858 * XXX - We should have the process ID of the parent (from the "-Z" flag)
4859 * at this point. Should we check to see if the parent is still alive,
4860 * e.g. by using OpenProcess?
4863 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
4865 if (!result || avail > 0) {
4866 /* peek failed or some bytes really available */
4867 /* (if not piping from stdin this would fail) */
4868 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4869 "Signal pipe: Stop capture: %s", sig_pipe_name);
4870 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4871 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
4872 sig_pipe_handle, result, avail);
4875 /* pipe ok and no bytes available */
4882 * Editor modelines - https://www.wireshark.org/tools/modelines.html
4887 * indent-tabs-mode: nil
4890 * vi: set shiftwidth=4 tabstop=8 expandtab:
4891 * :indentSize=4:tabSize=8:noTabs=true: