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, " filesize:NUM - switch to next file after NUM KB\n");
528 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
529 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
530 fprintf(output, " -P use libpcap format instead of pcapng\n");
531 fprintf(output, " --capture-comment <comment>\n");
532 fprintf(output, " add a capture comment to the output file\n");
533 fprintf(output, " (only for pcapng)\n");
534 fprintf(output, "\n");
535 fprintf(output, "Miscellaneous:\n");
536 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
537 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
538 fprintf(output, " within dumpcap\n");
539 fprintf(output, " -t use a separate thread per interface\n");
540 fprintf(output, " -q don't report packet capture counts\n");
541 fprintf(output, " -v print version information and exit\n");
542 fprintf(output, " -h display this help and exit\n");
543 fprintf(output, "\n");
545 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
546 fprintf(output, "You might want to reset it\n");
547 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
548 fprintf(output, "\n");
550 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
551 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
552 fprintf(output, "\n");
553 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
557 * Report an error in command-line arguments.
558 * If we're a capture child, send a message back to the parent, otherwise
562 dumpcap_cmdarg_err(const char *fmt, va_list ap)
566 /* Generate a 'special format' message back to parent */
567 msg = g_strdup_vprintf(fmt, ap);
568 sync_pipe_errmsg_to_parent(2, msg, "");
571 fprintf(stderr, "dumpcap: ");
572 vfprintf(stderr, fmt, ap);
573 fprintf(stderr, "\n");
578 * Report additional information for an error in command-line arguments.
579 * If we're a capture child, send a message back to the parent, otherwise
583 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
587 msg = g_strdup_vprintf(fmt, ap);
588 sync_pipe_errmsg_to_parent(2, msg, "");
591 vfprintf(stderr, fmt, ap);
592 fprintf(stderr, "\n");
598 #if 0 /* Set to enable capability debugging */
599 /* see 'man cap_to_text()' for explanation of output */
600 /* '=' means 'all= ' ie: no capabilities */
601 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
603 print_caps(const char *pfx) {
604 cap_t caps = cap_get_proc();
605 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
606 "%s: EUID: %d Capabilities: %s", pfx,
607 geteuid(), cap_to_text(caps, NULL));
610 print_caps(const char *pfx _U_) {
615 relinquish_all_capabilities(void)
617 /* Drop any and all capabilities this process may have. */
618 /* Allowed whether or not process has any privileges. */
619 cap_t caps = cap_init(); /* all capabilities initialized to off */
620 print_caps("Pre-clear");
621 if (cap_set_proc(caps)) {
622 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
624 print_caps("Post-clear");
630 get_capture_device_open_failure_messages(const char *open_err_str,
632 char *errmsg, size_t errmsg_len,
633 char *secondary_errmsg,
634 size_t secondary_errmsg_len)
637 const char *libpcap_warn;
638 static const char ppamsg[] = "can't find PPA for ";
641 g_snprintf(errmsg, (gulong) errmsg_len,
642 "The capture session could not be initiated on interface '%s' (%s).",
643 iface, open_err_str);
646 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
648 "In order to capture packets, WinPcap must be installed; see\n"
650 " https://www.winpcap.org/\n"
652 "for a downloadable version of WinPcap and for instructions on how to install\n"
655 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
657 "Please check that \"%s\" is the proper interface.\n"
660 "Help can be found on the following pages:\n"
662 " https://wiki.wireshark.org/WinPcap\n"
663 " https://wiki.wireshark.org/CaptureSetup\n",
667 /* If we got a "can't find PPA for X" message, warn the user (who
668 is running dumpcap on HP-UX) that they don't have a version of
669 libpcap that properly handles HP-UX (libpcap 0.6.x and later
670 versions, which properly handle HP-UX, say "can't find /dev/dlpi
671 PPA for X" rather than "can't find PPA for X"). */
672 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
675 "You are running (T)Wireshark with a version of the libpcap library\n"
676 "that doesn't handle HP-UX network devices well; this means that\n"
677 "(T)Wireshark may not be able to capture packets.\n"
679 "To fix this, you should install libpcap 0.6.2, or a later version\n"
680 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
681 "packaged binary form from the Software Porting And Archive Centre\n"
682 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
683 "at the URL lists a number of mirror sites.";
687 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
688 "Please check to make sure you have sufficient permissions, and that you have "
689 "the proper interface or pipe specified.%s", libpcap_warn);
694 compile_capture_filter(const char *iface, pcap_t *pcap_h,
695 struct bpf_program *fcode, const char *cfilter)
697 bpf_u_int32 netnum, netmask;
698 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
700 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
702 * Well, we can't get the netmask for this interface; it's used
703 * only for filters that check for broadcast IP addresses, so
704 * we just punt and use 0. It might be nice to warn the user,
705 * but that's a pain in a GUI application, as it'd involve popping
706 * up a message box, and it's not clear how often this would make
707 * a difference (only filters that check for IP broadcast addresses
711 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
716 * Sigh. Older versions of libpcap don't properly declare the
717 * third argument to pcap_compile() as a const pointer. Cast
721 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
727 #ifdef HAVE_BPF_IMAGE
729 show_filter_code(capture_options *capture_opts)
731 interface_options interface_opts;
733 gchar open_err_str[PCAP_ERRBUF_SIZE];
734 char errmsg[MSG_MAX_LENGTH+1];
735 char secondary_errmsg[MSG_MAX_LENGTH+1];
736 struct bpf_program fcode;
737 struct bpf_insn *insn;
741 for (j = 0; j < capture_opts->ifaces->len; j++) {
742 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
743 pcap_h = open_capture_device(capture_opts, &interface_opts,
744 CAP_READ_TIMEOUT, &open_err_str);
745 if (pcap_h == NULL) {
746 /* Open failed; get messages */
747 get_capture_device_open_failure_messages(open_err_str,
749 errmsg, sizeof errmsg,
751 sizeof secondary_errmsg);
752 /* And report them */
753 report_capture_error(errmsg, secondary_errmsg);
757 /* Set the link-layer type. */
758 if (!set_pcap_datalink(pcap_h, interface_opts.linktype, interface_opts.name,
759 errmsg, sizeof errmsg,
760 secondary_errmsg, sizeof secondary_errmsg)) {
762 report_capture_error(errmsg, secondary_errmsg);
766 /* OK, try to compile the capture filter. */
767 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
768 interface_opts.cfilter)) {
770 report_cfilter_error(capture_opts, j, errmsg);
775 /* Now print the filter code. */
776 insn = fcode.bf_insns;
778 for (i = 0; i < fcode.bf_len; insn++, i++)
779 printf("%s\n", bpf_image(insn, i));
781 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
782 /* to remove any suid privileges. */
783 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
784 /* (euid/egid have already previously been set to ruid/rgid. */
785 /* (See comment in main() for details) */
787 relinquish_special_privs_perm();
789 relinquish_all_capabilities();
792 /* Let our parent know we succeeded. */
793 pipe_write_block(2, SP_SUCCESS, NULL);
800 * capture_interface_list() is expected to do the right thing to get
801 * a list of interfaces.
803 * In most of the programs in the Wireshark suite, "the right thing"
804 * is to run dumpcap and ask it for the list, because dumpcap may
805 * be the only program in the suite with enough privileges to get
808 * In dumpcap itself, however, we obviously can't run dumpcap to
809 * ask for the list. Therefore, our capture_interface_list() should
810 * just call get_interface_list().
813 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
815 return get_interface_list(err, err_str);
818 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
820 * Output a machine readable list of the interfaces
821 * This list is retrieved by the sync_interface_list_open() function
822 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
825 print_machine_readable_interfaces(GList *if_list)
832 char addr_str[ADDRSTRLEN];
835 /* Let our parent know we succeeded. */
836 pipe_write_block(2, SP_SUCCESS, NULL);
839 i = 1; /* Interface id number */
840 for (if_entry = g_list_first(if_list); if_entry != NULL;
841 if_entry = g_list_next(if_entry)) {
842 if_info = (if_info_t *)if_entry->data;
843 printf("%d. %s\t", i++, if_info->name);
846 * Print the contents of the if_entry struct in a parseable format.
847 * Each if_entry element is tab-separated. Addresses are comma-
850 /* XXX - Make sure our description doesn't contain a tab */
851 if (if_info->vendor_description != NULL)
852 printf("%s\t", if_info->vendor_description);
856 /* XXX - Make sure our friendly name doesn't contain a tab */
857 if (if_info->friendly_name != NULL)
858 printf("%s\t", if_info->friendly_name);
862 printf("%i\t", if_info->type);
864 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
865 addr = g_slist_next(addr)) {
866 if (addr != g_slist_nth(if_info->addrs, 0))
869 if_addr = (if_addr_t *)addr->data;
870 switch(if_addr->ifat_type) {
872 if (ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str,
874 printf("%s", addr_str);
876 printf("<unknown IPv4>");
880 if (ws_inet_ntop6(&if_addr->addr.ip6_addr,
881 addr_str, ADDRSTRLEN)) {
882 printf("%s", addr_str);
884 printf("<unknown IPv6>");
888 printf("<type unknown %i>", if_addr->ifat_type);
892 if (if_info->loopback)
893 printf("\tloopback");
897 printf("\t%s", if_info->extcap);
904 * If you change the machine-readable output format of this function,
905 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
908 print_machine_readable_if_capabilities(if_capabilities_t *caps)
911 data_link_info_t *data_link_info;
912 const gchar *desc_str;
915 /* Let our parent know we succeeded. */
916 pipe_write_block(2, SP_SUCCESS, NULL);
919 if (caps->can_set_rfmon)
923 for (lt_entry = caps->data_link_types; lt_entry != NULL;
924 lt_entry = g_list_next(lt_entry)) {
925 data_link_info = (data_link_info_t *)lt_entry->data;
926 if (data_link_info->description != NULL)
927 desc_str = data_link_info->description;
929 desc_str = "(not supported)";
930 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
940 /* Print the number of packets captured for each interface until we're killed. */
942 print_statistics_loop(gboolean machine_readable)
944 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
950 char errbuf[PCAP_ERRBUF_SIZE];
953 if_list = get_interface_list(&err, &err_str);
954 if (if_list == NULL) {
956 cmdarg_err("There are no interfaces on which a capture can be done");
958 cmdarg_err("%s", err_str);
964 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
965 if_info = (if_info_t *)if_entry->data;
968 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
969 * connections. We avoid collecting stats on them.
971 if (!strncmp(if_info->name, "nf", 2)) {
972 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
978 #ifdef HAVE_PCAP_OPEN
979 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
981 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
985 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
986 if_stat->name = g_strdup(if_info->name);
988 stat_list = g_list_append(stat_list, if_stat);
993 cmdarg_err("There are no interfaces on which a capture can be done");
998 /* Let our parent know we succeeded. */
999 pipe_write_block(2, SP_SUCCESS, NULL);
1002 if (!machine_readable) {
1003 printf("%-15s %10s %10s\n", "Interface", "Received",
1007 global_ld.go = TRUE;
1008 while (global_ld.go) {
1009 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1010 if_stat = (if_stat_t *)stat_entry->data;
1011 pcap_stats(if_stat->pch, &ps);
1013 if (!machine_readable) {
1014 printf("%-15s %10u %10u\n", if_stat->name,
1015 ps.ps_recv, ps.ps_drop);
1017 printf("%s\t%u\t%u\n", if_stat->name,
1018 ps.ps_recv, ps.ps_drop);
1023 /* If we have a dummy signal pipe check it */
1024 if (!signal_pipe_check_running()) {
1025 global_ld.go = FALSE;
1033 /* XXX - Not reached. Should we look for 'q' in stdin? */
1034 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1035 if_stat = (if_stat_t *)stat_entry->data;
1036 pcap_close(if_stat->pch);
1037 g_free(if_stat->name);
1040 g_list_free(stat_list);
1041 free_interface_list(if_list);
1049 capture_cleanup_handler(DWORD dwCtrlType)
1051 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1052 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1053 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1054 like SIGTERM at least when the machine's shutting down.
1056 For now, if we're running as a command rather than a capture child,
1057 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1058 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1059 in that way on UN*X.
1061 If we're not running as a capture child, we might be running as
1062 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1063 user logs out. (XXX - can we explicitly check whether we're
1064 running as a service?) */
1066 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1067 "Console: Control signal");
1068 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1069 "Console: Control signal, CtrlType: %u", dwCtrlType);
1071 /* Keep capture running if we're a service and a user logs off */
1072 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1073 capture_loop_stop();
1081 capture_cleanup_handler(int signum _U_)
1083 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1084 SIGTERM. We assume that if the user wanted it to keep running
1085 after they logged out, they'd have nohupped it. */
1087 /* Note: don't call g_log() in the signal handler: if we happened to be in
1088 * g_log() in process context when the signal came in, g_log will detect
1089 * the "recursion" and abort.
1092 capture_loop_stop();
1098 report_capture_count(gboolean reportit)
1100 /* Don't print this if we're a capture child. */
1101 if (!capture_child && reportit) {
1102 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packet_count);
1103 /* stderr could be line buffered */
1111 report_counts_for_siginfo(void)
1113 report_capture_count(quiet);
1114 infoprint = FALSE; /* we just reported it */
1118 report_counts_siginfo(int signum _U_)
1120 int sav_errno = errno;
1122 /* If we've been told to delay printing, just set a flag asking
1123 that we print counts (if we're supposed to), otherwise print
1124 the count of packets captured (if we're supposed to). */
1128 report_counts_for_siginfo();
1131 #endif /* SIGINFO */
1134 exit_main(int status)
1137 /* Shutdown windows sockets */
1140 /* can be helpful for debugging */
1141 #ifdef DEBUG_DUMPCAP
1142 printf("Press any key\n");
1148 capture_opts_cleanup(&global_capture_opts);
1154 * If we were linked with libcap (not related to libpcap), make sure we have
1155 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1156 * (See comment in main() for details)
1159 relinquish_privs_except_capture(void)
1161 /* If 'started_with_special_privs' (ie: suid) then enable for
1162 * ourself the NET_ADMIN and NET_RAW capabilities and then
1163 * drop our suid privileges.
1165 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1166 * stuff we don't need (and shouldn't have).
1167 * CAP_NET_RAW: Packet capture (raw sockets).
1170 if (started_with_special_privs()) {
1171 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1172 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1174 cap_t caps = cap_init(); /* all capabilities initialized to off */
1176 print_caps("Pre drop, pre set");
1178 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1179 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1182 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1183 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1185 if (cap_set_proc(caps)) {
1186 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1188 print_caps("Pre drop, post set");
1190 relinquish_special_privs_perm();
1192 print_caps("Post drop, pre set");
1193 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1194 if (cap_set_proc(caps)) {
1195 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1197 print_caps("Post drop, post set");
1203 #endif /* HAVE_LIBCAP */
1205 /* Take care of byte order in the libpcap headers read from pipes.
1206 * (function taken from wiretap/libpcap.c) */
1208 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1211 /* Byte-swap the record header fields. */
1212 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1213 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1214 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1215 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1218 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1219 swapped, in order to match the BPF header layout.
1221 Unfortunately, some files were, according to a comment in the "libpcap"
1222 source, written with version 2.3 in their headers but without the
1223 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1224 would make no sense - we assume that we need to swap them. */
1225 if (hdr->version_major == 2 &&
1226 (hdr->version_minor < 3 ||
1227 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1230 temp = rechdr->orig_len;
1231 rechdr->orig_len = rechdr->incl_len;
1232 rechdr->incl_len = temp;
1236 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1240 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1244 return recv(pipe_fd, buf, (int)sz, 0);
1249 return ws_read(pipe_fd, buf, sz);
1255 * Thread function that reads from a pipe and pushes the data
1256 * to the main application thread.
1259 * XXX Right now we use async queues for basic signaling. The main thread
1260 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1261 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1262 * Iff the read is successful cap_pipe_read pushes an item onto
1263 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1264 * the queues themselves (yet).
1266 * We might want to move some of the cap_pipe_dispatch logic here so that
1267 * we can let cap_thread_read run independently, queuing up multiple reads
1268 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1270 static void *cap_thread_read(void *arg)
1272 capture_src *pcap_src;
1275 DWORD b, last_err, bytes_read;
1281 pcap_src = (capture_src *)arg;
1282 while (pcap_src->cap_pipe_err == PIPOK) {
1283 g_async_queue_pop(pcap_src->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1284 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1286 while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1287 if ((pcap_src->from_cap_socket)
1293 b = cap_pipe_read(pcap_src->cap_pipe_fd, pcap_src->cap_pipe_buf+bytes_read,
1294 pcap_src->cap_pipe_bytes_to_read - bytes_read, pcap_src->from_cap_socket);
1297 pcap_src->cap_pipe_err = PIPEOF;
1301 pcap_src->cap_pipe_err = PIPERR;
1312 /* If we try to use read() on a named pipe on Windows with partial
1313 * data it appears to return EOF.
1315 res = ReadFile(pcap_src->cap_pipe_h, pcap_src->cap_pipe_buf+bytes_read,
1316 pcap_src->cap_pipe_bytes_to_read - bytes_read,
1321 last_err = GetLastError();
1322 if (last_err == ERROR_MORE_DATA) {
1324 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1325 pcap_src->cap_pipe_err = PIPEOF;
1329 pcap_src->cap_pipe_err = PIPERR;
1332 } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1333 pcap_src->cap_pipe_err = PIPEOF;
1340 pcap_src->cap_pipe_bytes_read = bytes_read;
1341 if (pcap_src->cap_pipe_bytes_read >= pcap_src->cap_pipe_bytes_to_read) {
1342 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1344 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1350 /* Provide select() functionality for a single file descriptor
1351 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1353 * Returns the same values as select.
1356 cap_pipe_select(int pipe_fd)
1359 struct timeval timeout;
1362 FD_SET(pipe_fd, &rfds);
1364 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1365 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1367 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1370 #define DEF_TCP_PORT 19000
1373 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, int errmsgl)
1375 char *sockname = pipename + 4;
1376 struct sockaddr_in sa;
1383 memset(&sa, 0, sizeof(sa));
1385 p = strchr(sockname, ':');
1387 len = strlen(sockname);
1388 port = DEF_TCP_PORT;
1392 port = strtoul(p + 1, &p, 10);
1393 if (*p || port > 65535) {
1402 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1404 if (!ws_inet_pton4(buf, (guint32 *)&sa.sin_addr)) {
1408 sa.sin_family = AF_INET;
1409 sa.sin_port = g_htons((u_short)port);
1411 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1412 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1414 LPTSTR errorText = NULL;
1417 lastError = WSAGetLastError();
1418 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1419 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1420 FORMAT_MESSAGE_IGNORE_INSERTS,
1421 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1422 (LPTSTR)&errorText, 0, NULL);
1424 g_snprintf(errmsg, errmsgl,
1425 "The capture session could not be initiated due to the socket error: \n"
1427 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1429 LocalFree(errorText);
1431 " %d: %s", errno, g_strerror(errno));
1433 pcap_src->cap_pipe_err = PIPERR;
1436 cap_pipe_close(fd, TRUE);
1440 pcap_src->from_cap_socket = TRUE;
1444 g_snprintf(errmsg, errmsgl,
1445 "The capture session could not be initiated because\n"
1446 "\"%s\" is not a valid socket specification", pipename);
1447 pcap_src->cap_pipe_err = PIPERR;
1451 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1455 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1459 closesocket(pipe_fd);
1466 /* Mimic pcap_open_live() for pipe captures
1468 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1469 * open it, and read the header.
1471 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1472 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1474 cap_pipe_open_live(char *pipename,
1475 capture_src *pcap_src,
1476 struct pcap_hdr *hdr,
1477 char *errmsg, int errmsgl)
1480 ws_statb64 pipe_stat;
1481 struct sockaddr_un sa;
1486 char* extcap_pipe_name;
1490 gboolean extcap_pipe = FALSE;
1491 interface_options interface_opts;
1494 int fd = -1, sel_ret;
1497 pcap_src->cap_pipe_fd = -1;
1499 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1502 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1505 * XXX - this blocks until a pcap per-file header has been written to
1506 * the pipe, so it could block indefinitely.
1508 if (strcmp(pipename, "-") == 0) {
1510 fd = 0; /* read from stdin */
1512 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1514 } else if (!strncmp(pipename, "TCP@", 4)) {
1515 if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1521 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
1526 if ( g_strrstr(interface_opts.name, EXTCAP_PIPE_PREFIX) != NULL )
1530 if (ws_stat64(pipename, &pipe_stat) < 0) {
1531 if (errno == ENOENT || errno == ENOTDIR)
1532 pcap_src->cap_pipe_err = PIPNEXIST;
1534 g_snprintf(errmsg, errmsgl,
1535 "The capture session could not be initiated "
1536 "due to error getting information on pipe/socket: %s.", g_strerror(errno));
1537 pcap_src->cap_pipe_err = PIPERR;
1541 if (S_ISFIFO(pipe_stat.st_mode)) {
1542 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1544 g_snprintf(errmsg, errmsgl,
1545 "The capture session could not be initiated "
1546 "due to error on pipe open: %s.", g_strerror(errno));
1547 pcap_src->cap_pipe_err = PIPERR;
1550 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1551 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1553 g_snprintf(errmsg, errmsgl,
1554 "The capture session could not be initiated "
1555 "due to error on socket create: %s.", g_strerror(errno));
1556 pcap_src->cap_pipe_err = PIPERR;
1559 sa.sun_family = AF_UNIX;
1561 * The Single UNIX Specification says:
1563 * The size of sun_path has intentionally been left undefined.
1564 * This is because different implementations use different sizes.
1565 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1566 * of 104. Since most implementations originate from BSD versions,
1567 * the size is typically in the range 92 to 108.
1569 * Applications should not assume a particular length for sun_path
1570 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1574 * The <sys/un.h> header shall define the sockaddr_un structure,
1575 * which shall include at least the following members:
1577 * sa_family_t sun_family Address family.
1578 * char sun_path[] Socket pathname.
1580 * so we assume that it's an array, with a specified size,
1581 * and that the size reflects the maximum path length.
1583 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1584 /* Path name too long */
1585 g_snprintf(errmsg, errmsgl,
1586 "The capture session coud not be initiated "
1587 "due to error on socket connect: Path name too long.");
1588 pcap_src->cap_pipe_err = PIPERR;
1592 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1594 g_snprintf(errmsg, errmsgl,
1595 "The capture session coud not be initiated "
1596 "due to error on socket connect: %s.", g_strerror(errno));
1597 pcap_src->cap_pipe_err = PIPERR;
1602 if (S_ISCHR(pipe_stat.st_mode)) {
1604 * Assume the user specified an interface on a system where
1605 * interfaces are in /dev. Pretend we haven't seen it.
1607 pcap_src->cap_pipe_err = PIPNEXIST;
1609 g_snprintf(errmsg, errmsgl,
1610 "The capture session could not be initiated because\n"
1611 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1612 pcap_src->cap_pipe_err = PIPERR;
1618 #define PIPE_STR "\\pipe\\"
1619 /* Under Windows, named pipes _must_ have the form
1620 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1622 pncopy = g_strdup(pipename);
1623 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1624 pos = strchr(pncopy + 3, '\\');
1625 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1632 g_snprintf(errmsg, errmsgl,
1633 "The capture session could not be initiated because\n"
1634 "\"%s\" is neither an interface nor a pipe.", pipename);
1635 pcap_src->cap_pipe_err = PIPNEXIST;
1639 extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
1640 extcap_pipe = strstr(interface_opts.name, extcap_pipe_name) ? TRUE : FALSE;
1641 g_free(extcap_pipe_name);
1644 /* Wait for the pipe to appear */
1649 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1652 pcap_src->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1653 OPEN_EXISTING, 0, NULL);
1655 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE)
1658 if (GetLastError() != ERROR_PIPE_BUSY) {
1659 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1660 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1661 g_snprintf(errmsg, errmsgl,
1662 "The capture session on \"%s\" could not be started "
1663 "due to error on pipe open: %s (error %d).",
1664 pipename, utf_16to8(err_str), GetLastError());
1666 pcap_src->cap_pipe_err = PIPERR;
1670 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1671 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1672 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1673 g_snprintf(errmsg, errmsgl,
1674 "The capture session on \"%s\" timed out during "
1675 "pipe open: %s (error %d).",
1676 pipename, utf_16to8(err_str), GetLastError());
1678 pcap_src->cap_pipe_err = PIPERR;
1685 pcap_src->from_cap_pipe = TRUE;
1688 * We start with a 2KB buffer for packet data, which should be
1689 * large enough for most regular network packets. We increase it,
1690 * up to the maximum size we allow, as necessary.
1692 pcap_src->cap_pipe_databuf = (guchar*)g_malloc(2048);
1693 pcap_src->cap_pipe_databuf_size = 2048;
1696 if (pcap_src->from_cap_socket)
1699 /* read the pcap header */
1701 while (bytes_read < sizeof magic) {
1703 g_snprintf(errmsg, errmsgl, "Invalid file descriptor.");
1707 sel_ret = cap_pipe_select(fd);
1709 g_snprintf(errmsg, errmsgl,
1710 "Unexpected error from select: %s.", g_strerror(errno));
1712 } else if (sel_ret > 0) {
1713 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1714 sizeof magic-bytes_read,
1715 pcap_src->from_cap_socket);
1717 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1718 if (extcap_pipe && b <= 0)
1723 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1725 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1735 #if GLIB_CHECK_VERSION(2,31,0)
1736 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
1738 g_thread_create(&cap_thread_read, pcap_src, FALSE, NULL);
1741 pcap_src->cap_pipe_buf = (char *) &magic;
1742 pcap_src->cap_pipe_bytes_read = 0;
1743 pcap_src->cap_pipe_bytes_to_read = sizeof(magic);
1744 /* We don't have to worry about cap_pipe_read_mtx here */
1745 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1746 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1747 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1748 if (pcap_src->cap_pipe_bytes_read <= 0 && extcap_pipe)
1751 if (pcap_src->cap_pipe_bytes_read <= 0) {
1752 if (pcap_src->cap_pipe_bytes_read == 0)
1753 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1755 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1764 case PCAP_NSEC_MAGIC:
1765 /* Host that wrote it has our byte order, and was running
1766 a program using either standard or ss990417 libpcap. */
1767 pcap_src->cap_pipe_byte_swapped = FALSE;
1768 pcap_src->cap_pipe_modified = FALSE;
1769 pcap_src->ts_nsec = magic == PCAP_NSEC_MAGIC;
1771 case PCAP_MODIFIED_MAGIC:
1772 /* Host that wrote it has our byte order, but was running
1773 a program using either ss990915 or ss991029 libpcap. */
1774 pcap_src->cap_pipe_byte_swapped = FALSE;
1775 pcap_src->cap_pipe_modified = TRUE;
1777 case PCAP_SWAPPED_MAGIC:
1778 case PCAP_SWAPPED_NSEC_MAGIC:
1779 /* Host that wrote it has a byte order opposite to ours,
1780 and was running a program using either standard or
1781 ss990417 libpcap. */
1782 pcap_src->cap_pipe_byte_swapped = TRUE;
1783 pcap_src->cap_pipe_modified = FALSE;
1784 pcap_src->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
1786 case PCAP_SWAPPED_MODIFIED_MAGIC:
1787 /* Host that wrote it out has a byte order opposite to
1788 ours, and was running a program using either ss990915
1789 or ss991029 libpcap. */
1790 pcap_src->cap_pipe_byte_swapped = TRUE;
1791 pcap_src->cap_pipe_modified = TRUE;
1793 case BLOCK_TYPE_SHB:
1794 /* This isn't pcap, it's pcapng. We don't yet support
1796 g_snprintf(errmsg, errmsgl, "Capturing from a pipe doesn't support pcapng format.");
1799 /* Not a pcap type we know about, or not pcap at all. */
1800 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format or not libpcap data.");
1805 if (pcap_src->from_cap_socket)
1808 /* Read the rest of the header */
1810 while (bytes_read < sizeof(struct pcap_hdr)) {
1811 sel_ret = cap_pipe_select(fd);
1813 g_snprintf(errmsg, errmsgl,
1814 "Unexpected error from select: %s.", g_strerror(errno));
1816 } else if (sel_ret > 0) {
1817 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
1818 sizeof(struct pcap_hdr) - bytes_read,
1819 pcap_src->from_cap_socket);
1822 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1824 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s.",
1834 pcap_src->cap_pipe_buf = (char *) hdr;
1835 pcap_src->cap_pipe_bytes_read = 0;
1836 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1837 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1838 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1839 if (pcap_src->cap_pipe_bytes_read <= 0) {
1840 if (pcap_src->cap_pipe_bytes_read == 0)
1841 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1843 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s.",
1850 if (pcap_src->cap_pipe_byte_swapped) {
1851 /* Byte-swap the header fields about which we care. */
1852 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
1853 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
1854 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
1855 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
1857 pcap_src->linktype = hdr->network;
1859 if (pcap_src->linktype == DLT_DBUS) {
1861 * The maximum D-Bus message size is 128MB, so allow packets up
1864 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_DBUS;
1867 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
1869 if (hdr->version_major < 2) {
1870 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1874 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
1875 pcap_src->cap_pipe_err = PIPOK;
1876 pcap_src->cap_pipe_fd = fd;
1880 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1881 pcap_src->cap_pipe_err = PIPERR;
1882 cap_pipe_close(fd, pcap_src->from_cap_socket);
1883 pcap_src->cap_pipe_fd = -1;
1885 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1890 /* We read one record from the pipe, take care of byte order in the record
1891 * header, write the record to the capture file, and update capture statistics. */
1893 cap_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, int errmsgl)
1895 struct pcap_pkthdr phdr;
1896 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1899 #if !GLIB_CHECK_VERSION(2,31,18)
1908 #ifdef LOG_CAPTURE_VERBOSE
1909 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1912 switch (pcap_src->cap_pipe_state) {
1914 case STATE_EXPECT_REC_HDR:
1916 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
1919 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
1920 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_modified ?
1921 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1922 pcap_src->cap_pipe_bytes_read = 0;
1925 pcap_src->cap_pipe_buf = (char *) &pcap_src->cap_pipe_rechdr;
1926 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1927 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1932 case STATE_READ_REC_HDR:
1934 if (pcap_src->from_cap_socket)
1937 b = cap_pipe_read(pcap_src->cap_pipe_fd, ((char *)&pcap_src->cap_pipe_rechdr)+pcap_src->cap_pipe_bytes_read,
1938 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read, pcap_src->from_cap_socket);
1941 result = PD_PIPE_EOF;
1943 result = PD_PIPE_ERR;
1946 pcap_src->cap_pipe_bytes_read += b;
1950 #if GLIB_CHECK_VERSION(2,31,18)
1951 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
1953 g_get_current_time(&wait_time);
1954 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
1955 q_status = g_async_queue_timed_pop(pcap_src->cap_pipe_done_q, &wait_time);
1957 if (pcap_src->cap_pipe_err == PIPEOF) {
1958 result = PD_PIPE_EOF;
1960 } else if (pcap_src->cap_pipe_err == PIPERR) {
1961 result = PD_PIPE_ERR;
1969 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
1971 result = PD_REC_HDR_READ;
1974 case STATE_EXPECT_DATA:
1976 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
1979 pcap_src->cap_pipe_state = STATE_READ_DATA;
1980 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_rechdr.hdr.incl_len;
1981 pcap_src->cap_pipe_bytes_read = 0;
1984 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
1985 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1986 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1991 case STATE_READ_DATA:
1993 if (pcap_src->from_cap_socket)
1996 b = cap_pipe_read(pcap_src->cap_pipe_fd,
1997 pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read,
1998 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read,
1999 pcap_src->from_cap_socket);
2002 result = PD_PIPE_EOF;
2004 result = PD_PIPE_ERR;
2007 pcap_src->cap_pipe_bytes_read += b;
2012 #if GLIB_CHECK_VERSION(2,31,18)
2013 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2015 g_get_current_time(&wait_time);
2016 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2017 q_status = g_async_queue_timed_pop(pcap_src->cap_pipe_done_q, &wait_time);
2018 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2019 if (pcap_src->cap_pipe_err == PIPEOF) {
2020 result = PD_PIPE_EOF;
2022 } else if (pcap_src->cap_pipe_err == PIPERR) {
2023 result = PD_PIPE_ERR;
2031 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2033 result = PD_DATA_READ;
2037 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2040 } /* switch (pcap_src->cap_pipe_state) */
2043 * We've now read as much data as we were expecting, so process it.
2047 case PD_REC_HDR_READ:
2048 /* We've read the header. Take care of byte order. */
2049 cap_pipe_adjust_header(pcap_src->cap_pipe_byte_swapped, &pcap_src->cap_pipe_hdr,
2050 &pcap_src->cap_pipe_rechdr.hdr);
2051 if (pcap_src->cap_pipe_rechdr.hdr.incl_len > pcap_src->cap_pipe_max_pkt_size) {
2053 * The record contains more data than the advertised/allowed in the
2054 * pcap header, do not try to read more data (do not change to
2055 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2056 * instead stop with an error.
2058 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2059 ld->packet_count+1, pcap_src->cap_pipe_rechdr.hdr.incl_len);
2063 if (pcap_src->cap_pipe_rechdr.hdr.incl_len > pcap_src->cap_pipe_databuf_size) {
2065 * Grow the buffer to the packet size, rounded up to a power of
2068 new_bufsize = pcap_src->cap_pipe_rechdr.hdr.incl_len;
2070 * http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2073 new_bufsize |= new_bufsize >> 1;
2074 new_bufsize |= new_bufsize >> 2;
2075 new_bufsize |= new_bufsize >> 4;
2076 new_bufsize |= new_bufsize >> 8;
2077 new_bufsize |= new_bufsize >> 16;
2079 pcap_src->cap_pipe_databuf = (guchar*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2080 pcap_src->cap_pipe_databuf_size = new_bufsize;
2084 * The record has some data following the header, try to read it next
2087 if (pcap_src->cap_pipe_rechdr.hdr.incl_len) {
2088 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2093 * No data following the record header? Then no more data needs to be
2094 * read and we will fallthrough and emit an empty packet.
2098 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2099 phdr.ts.tv_sec = pcap_src->cap_pipe_rechdr.hdr.ts_sec;
2100 phdr.ts.tv_usec = pcap_src->cap_pipe_rechdr.hdr.ts_usec;
2101 phdr.caplen = pcap_src->cap_pipe_rechdr.hdr.incl_len;
2102 phdr.len = pcap_src->cap_pipe_rechdr.hdr.orig_len;
2105 capture_loop_queue_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2107 capture_loop_write_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2109 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2113 pcap_src->cap_pipe_err = PIPEOF;
2118 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2119 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2120 g_snprintf(errmsg, errmsgl,
2121 "Error reading from pipe: %s (error %d)",
2122 utf_16to8(err_str), GetLastError());
2125 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2133 pcap_src->cap_pipe_err = PIPERR;
2134 /* Return here rather than inside the switch to prevent GCC warning */
2139 /** Open the capture input file (pcap or capture pipe).
2140 * Returns TRUE if it succeeds, FALSE otherwise. */
2142 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2143 char *errmsg, size_t errmsg_len,
2144 char *secondary_errmsg, size_t secondary_errmsg_len)
2146 gchar open_err_str[PCAP_ERRBUF_SIZE];
2147 gchar *sync_msg_str;
2148 interface_options interface_opts;
2149 capture_src *pcap_src;
2153 WORD wVersionRequested;
2157 /* XXX - opening Winsock on tshark? */
2159 /* Initialize Windows Socket if we are in a Win32 OS
2160 This needs to be done before querying the interface for network/netmask */
2162 /* XXX - do we really require 1.1 or earlier?
2163 Are there any versions that support only 2.0 or higher? */
2164 wVersionRequested = MAKEWORD(1, 1);
2165 err = WSAStartup(wVersionRequested, &wsaData);
2169 case WSASYSNOTREADY:
2170 g_snprintf(errmsg, (gulong) errmsg_len,
2171 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2174 case WSAVERNOTSUPPORTED:
2175 g_snprintf(errmsg, (gulong) errmsg_len,
2176 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2177 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2180 case WSAEINPROGRESS:
2181 g_snprintf(errmsg, (gulong) errmsg_len,
2182 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2186 g_snprintf(errmsg, (gulong) errmsg_len,
2187 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2191 g_snprintf(errmsg, (gulong) errmsg_len,
2192 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2196 g_snprintf(errmsg, (gulong) errmsg_len,
2197 "Couldn't initialize Windows Sockets: error %d", err);
2200 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2204 if ((use_threads == FALSE) &&
2205 (capture_opts->ifaces->len > 1)) {
2206 g_snprintf(errmsg, (gulong) errmsg_len,
2207 "Using threads is required for capturing on multiple interfaces.");
2211 for (i = 0; i < capture_opts->ifaces->len; i++) {
2212 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2213 pcap_src = (capture_src *)g_malloc(sizeof (capture_src));
2214 if (pcap_src == NULL) {
2215 g_snprintf(errmsg, (gulong) errmsg_len,
2216 "Could not allocate memory.");
2219 pcap_src->received = 0;
2220 pcap_src->dropped = 0;
2221 pcap_src->flushed = 0;
2222 pcap_src->pcap_h = NULL;
2223 #ifdef MUST_DO_SELECT
2224 pcap_src->pcap_fd = -1;
2226 pcap_src->pcap_err = FALSE;
2227 pcap_src->interface_id = i;
2228 pcap_src->tid = NULL;
2229 pcap_src->snaplen = 0;
2230 pcap_src->linktype = -1;
2231 pcap_src->ts_nsec = FALSE;
2232 pcap_src->from_cap_pipe = FALSE;
2233 pcap_src->from_cap_socket = FALSE;
2234 memset(&pcap_src->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2235 memset(&pcap_src->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2237 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2239 pcap_src->cap_pipe_fd = -1;
2240 pcap_src->cap_pipe_modified = FALSE;
2241 pcap_src->cap_pipe_byte_swapped = FALSE;
2243 pcap_src->cap_pipe_buf = NULL;
2245 pcap_src->cap_pipe_bytes_to_read = 0;
2246 pcap_src->cap_pipe_bytes_read = 0;
2247 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2248 pcap_src->cap_pipe_err = PIPOK;
2250 #if GLIB_CHECK_VERSION(2,31,0)
2251 pcap_src->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2252 g_mutex_init(pcap_src->cap_pipe_read_mtx);
2254 pcap_src->cap_pipe_read_mtx = g_mutex_new();
2256 pcap_src->cap_pipe_pending_q = g_async_queue_new();
2257 pcap_src->cap_pipe_done_q = g_async_queue_new();
2259 g_array_append_val(ld->pcaps, pcap_src);
2261 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2262 pcap_src->pcap_h = open_capture_device(capture_opts, &interface_opts,
2263 CAP_READ_TIMEOUT, &open_err_str);
2265 if (pcap_src->pcap_h != NULL) {
2266 /* we've opened "iface" as a network device */
2268 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2269 /* Find out if we're getting nanosecond-precision time stamps */
2270 pcap_src->ts_nsec = have_high_resolution_timestamp(pcap_src->pcap_h);
2273 #if defined(HAVE_PCAP_SETSAMPLING)
2274 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2275 struct pcap_samp *samp;
2277 if ((samp = pcap_setsampling(pcap_src->pcap_h)) != NULL) {
2278 switch (interface_opts.sampling_method) {
2279 case CAPTURE_SAMP_BY_COUNT:
2280 samp->method = PCAP_SAMP_1_EVERY_N;
2283 case CAPTURE_SAMP_BY_TIMER:
2284 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2288 sync_msg_str = g_strdup_printf(
2289 "Unknown sampling method %d specified,\n"
2290 "continue without packet sampling",
2291 interface_opts.sampling_method);
2292 report_capture_error("Couldn't set the capture "
2293 "sampling", sync_msg_str);
2294 g_free(sync_msg_str);
2296 samp->value = interface_opts.sampling_param;
2298 report_capture_error("Couldn't set the capture sampling",
2299 "Cannot get packet sampling data structure");
2304 /* setting the data link type only works on real interfaces */
2305 if (!set_pcap_datalink(pcap_src->pcap_h, interface_opts.linktype,
2306 interface_opts.name,
2308 secondary_errmsg, secondary_errmsg_len)) {
2311 pcap_src->linktype = get_pcap_datalink(pcap_src->pcap_h, interface_opts.name);
2313 /* We couldn't open "iface" as a network device. */
2314 /* Try to open it as a pipe */
2315 cap_pipe_open_live(interface_opts.name, pcap_src, &pcap_src->cap_pipe_hdr, errmsg, (int) errmsg_len);
2318 if (pcap_src->cap_pipe_fd == -1) {
2320 if (pcap_src->cap_pipe_h == INVALID_HANDLE_VALUE) {
2322 if (pcap_src->cap_pipe_err == PIPNEXIST) {
2324 * We tried opening as an interface, and that failed,
2325 * so we tried to open it as a pipe, but the pipe
2326 * doesn't exist. Report the error message for
2329 get_capture_device_open_failure_messages(open_err_str,
2330 interface_opts.name,
2334 secondary_errmsg_len);
2337 * Else pipe (or file) does exist and cap_pipe_open_live() has
2342 /* cap_pipe_open_live() succeeded; don't want
2343 error message from pcap_open_live() */
2344 open_err_str[0] = '\0';
2348 /* XXX - will this work for tshark? */
2349 #ifdef MUST_DO_SELECT
2350 if (!pcap_src->from_cap_pipe) {
2351 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2352 pcap_src->pcap_fd = pcap_get_selectable_fd(pcap_src->pcap_h);
2354 pcap_src->pcap_fd = pcap_fileno(pcap_src->pcap_h);
2359 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2360 returned a warning; print it, but keep capturing. */
2361 if (open_err_str[0] != '\0') {
2362 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2363 report_capture_error(sync_msg_str, "");
2364 g_free(sync_msg_str);
2366 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2367 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2370 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2371 /* to remove any suid privileges. */
2372 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2373 /* (euid/egid have already previously been set to ruid/rgid. */
2374 /* (See comment in main() for details) */
2376 relinquish_special_privs_perm();
2378 relinquish_all_capabilities();
2383 /* close the capture input file (pcap or capture pipe) */
2384 static void capture_loop_close_input(loop_data *ld)
2387 capture_src *pcap_src;
2389 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2391 for (i = 0; i < ld->pcaps->len; i++) {
2392 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2393 /* Pipe, or capture device? */
2394 if (pcap_src->from_cap_pipe) {
2395 /* Pipe. If open, close the capture pipe "input file". */
2396 if (pcap_src->cap_pipe_fd >= 0) {
2397 cap_pipe_close(pcap_src->cap_pipe_fd, pcap_src->from_cap_socket);
2398 pcap_src->cap_pipe_fd = -1;
2401 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE) {
2402 CloseHandle(pcap_src->cap_pipe_h);
2403 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2406 if (pcap_src->cap_pipe_databuf != NULL) {
2407 /* Free the buffer. */
2408 g_free(pcap_src->cap_pipe_databuf);
2409 pcap_src->cap_pipe_databuf = NULL;
2412 /* Capture device. If open, close the pcap_t. */
2413 if (pcap_src->pcap_h != NULL) {
2414 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_src->pcap_h);
2415 pcap_close(pcap_src->pcap_h);
2416 pcap_src->pcap_h = NULL;
2424 /* Shut down windows sockets */
2430 /* init the capture filter */
2431 static initfilter_status_t
2432 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2433 const gchar * name, const gchar * cfilter)
2435 struct bpf_program fcode;
2437 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2439 /* capture filters only work on real interfaces */
2440 if (cfilter && !from_cap_pipe) {
2441 /* A capture filter was specified; set it up. */
2442 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2443 /* Treat this specially - our caller might try to compile this
2444 as a display filter and, if that succeeds, warn the user that
2445 the display and capture filter syntaxes are different. */
2446 return INITFILTER_BAD_FILTER;
2448 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2449 #ifdef HAVE_PCAP_FREECODE
2450 pcap_freecode(&fcode);
2452 return INITFILTER_OTHER_ERROR;
2454 #ifdef HAVE_PCAP_FREECODE
2455 pcap_freecode(&fcode);
2459 return INITFILTER_NO_ERROR;
2463 /* set up to write to the already-opened capture output file/files */
2465 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2469 capture_src *pcap_src;
2470 interface_options interface_opts;
2471 gboolean successful;
2473 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2475 if ((capture_opts->use_pcapng == FALSE) &&
2476 (capture_opts->ifaces->len > 1)) {
2477 g_snprintf(errmsg, errmsg_len,
2478 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
2482 /* Set up to write to the capture file. */
2483 if (capture_opts->multi_files_on) {
2484 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2486 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2487 if (ld->pdh == NULL) {
2492 if (capture_opts->use_pcapng) {
2494 GString *cpu_info_str;
2495 GString *os_info_str;
2497 cpu_info_str = g_string_new("");
2498 os_info_str = g_string_new("");
2499 get_cpu_info(cpu_info_str);
2500 get_os_version_info(os_info_str);
2502 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2503 successful = pcapng_write_session_header_block(ld->pdh,
2504 (const char *)capture_opts->capture_comment, /* Comment */
2505 cpu_info_str->str, /* HW */
2506 os_info_str->str, /* OS */
2508 -1, /* section_length */
2513 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2514 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2515 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2516 if (pcap_src->from_cap_pipe) {
2517 pcap_src->snaplen = pcap_src->cap_pipe_hdr.snaplen;
2519 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
2521 successful = pcapng_write_interface_description_block(global_ld.pdh,
2522 NULL, /* OPT_COMMENT 1 */
2523 interface_opts.name, /* IDB_NAME 2 */
2524 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2525 interface_opts.cfilter, /* IDB_FILTER 11 */
2526 os_info_str->str, /* IDB_OS 12 */
2529 &(global_ld.bytes_written),
2530 0, /* IDB_IF_SPEED 8 */
2531 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2535 g_string_free(os_info_str, TRUE);
2538 pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
2539 if (pcap_src->from_cap_pipe) {
2540 pcap_src->snaplen = pcap_src->cap_pipe_hdr.snaplen;
2542 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
2544 successful = libpcap_write_file_header(ld->pdh, pcap_src->linktype, pcap_src->snaplen,
2545 pcap_src->ts_nsec, &ld->bytes_written, &err);
2553 if (ld->pdh == NULL) {
2554 /* We couldn't set up to write to the capture file. */
2555 /* XXX - use cf_open_error_message from tshark instead? */
2560 g_snprintf(errmsg, errmsg_len,
2561 "The file to which the capture would be"
2562 " saved (\"%s\") could not be opened: Error %d.",
2563 capture_opts->save_file, err);
2565 g_snprintf(errmsg, errmsg_len,
2566 "The file to which the capture would be"
2567 " saved (\"%s\") could not be opened: %s.",
2568 capture_opts->save_file, g_strerror(err));
2580 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2584 capture_src *pcap_src;
2585 guint64 end_time = create_timestamp();
2587 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2589 if (capture_opts->multi_files_on) {
2590 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2592 if (capture_opts->use_pcapng) {
2593 for (i = 0; i < global_ld.pcaps->len; i++) {
2594 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
2595 if (!pcap_src->from_cap_pipe) {
2596 guint64 isb_ifrecv, isb_ifdrop;
2597 struct pcap_stat stats;
2599 if (pcap_stats(pcap_src->pcap_h, &stats) >= 0) {
2600 isb_ifrecv = pcap_src->received;
2601 isb_ifdrop = stats.ps_drop + pcap_src->dropped + pcap_src->flushed;
2603 isb_ifrecv = G_MAXUINT64;
2604 isb_ifdrop = G_MAXUINT64;
2606 pcapng_write_interface_statistics_block(ld->pdh,
2609 "Counters provided by dumpcap",
2618 if (fclose(ld->pdh) == EOF) {
2619 if (err_close != NULL) {
2629 /* dispatch incoming packets (pcap or capture pipe)
2631 * Waits for incoming packets to be available, and calls pcap_dispatch()
2632 * to cause them to be processed.
2634 * Returns the number of packets which were processed.
2636 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2637 * packet-batching behaviour does not cause packets to get held back
2641 capture_loop_dispatch(loop_data *ld,
2642 char *errmsg, int errmsg_len, capture_src *pcap_src)
2645 gint packet_count_before;
2650 packet_count_before = ld->packet_count;
2651 if (pcap_src->from_cap_pipe) {
2652 /* dispatch from capture pipe */
2653 #ifdef LOG_CAPTURE_VERBOSE
2654 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2657 sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
2659 if (sel_ret < 0 && errno != EINTR) {
2660 g_snprintf(errmsg, errmsg_len,
2661 "Unexpected error from select: %s", g_strerror(errno));
2662 report_capture_error(errmsg, please_report);
2667 * "select()" says we can read from the pipe without blocking
2670 inpkts = cap_pipe_dispatch(ld, pcap_src, errmsg, errmsg_len);
2680 /* dispatch from pcap */
2681 #ifdef MUST_DO_SELECT
2683 * If we have "pcap_get_selectable_fd()", we use it to get the
2684 * descriptor on which to select; if that's -1, it means there
2685 * is no descriptor on which you can do a "select()" (perhaps
2686 * because you're capturing on a special device, and that device's
2687 * driver unfortunately doesn't support "select()", in which case
2688 * we don't do the select - which means it might not be possible
2689 * to stop a capture until a packet arrives. If that's unacceptable,
2690 * plead with whoever supplies the software for that device to add
2691 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2692 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2693 * later, so it can use pcap_breakloop().
2695 #ifdef LOG_CAPTURE_VERBOSE
2696 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2698 if (pcap_src->pcap_fd != -1) {
2699 sel_ret = cap_pipe_select(pcap_src->pcap_fd);
2702 * "select()" says we can read from it without blocking; go for
2705 * We don't have pcap_breakloop(), so we only process one packet
2706 * per pcap_dispatch() call, to allow a signal to stop the
2707 * processing immediately, rather than processing all packets
2708 * in a batch before quitting.
2711 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
2713 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
2717 /* Error, rather than pcap_breakloop(). */
2718 pcap_src->pcap_err = TRUE;
2720 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2723 if (sel_ret < 0 && errno != EINTR) {
2724 g_snprintf(errmsg, errmsg_len,
2725 "Unexpected error from select: %s", g_strerror(errno));
2726 report_capture_error(errmsg, please_report);
2732 #endif /* MUST_DO_SELECT */
2734 /* dispatch from pcap without select */
2736 #ifdef LOG_CAPTURE_VERBOSE
2737 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2741 * On Windows, we don't support asynchronously telling a process to
2742 * stop capturing; instead, we check for an indication on a pipe
2743 * after processing packets. We therefore process only one packet
2744 * at a time, so that we can check the pipe after every packet.
2747 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
2749 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
2753 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
2755 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_src);
2760 /* Error, rather than pcap_breakloop(). */
2761 pcap_src->pcap_err = TRUE;
2763 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2765 #else /* pcap_next_ex */
2766 #ifdef LOG_CAPTURE_VERBOSE
2767 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2769 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2772 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2773 * see https://wiki.wireshark.org/CaptureSetup/WinPcapRemote
2774 * This should be fixed in the WinPcap 4.0 alpha release.
2776 * For reference, an example remote interface:
2777 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2780 /* emulate dispatch from pcap */
2783 struct pcap_pkthdr *pkt_header;
2788 (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
2790 capture_loop_queue_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
2792 capture_loop_write_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
2797 pcap_src->pcap_err = TRUE;
2801 #endif /* pcap_next_ex */
2805 #ifdef LOG_CAPTURE_VERBOSE
2806 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2809 return ld->packet_count - packet_count_before;
2813 /* Isolate the Universally Unique Identifier from the interface. Basically, we
2814 * want to grab only the characters between the '{' and '}' delimiters.
2816 * Returns a GString that must be freed with g_string_free(). */
2818 isolate_uuid(const char *iface)
2823 ptr = strchr(iface, '{');
2825 return g_string_new(iface);
2826 gstr = g_string_new(ptr + 1);
2828 ptr = strchr(gstr->str, '}');
2832 gstr = g_string_truncate(gstr, ptr - gstr->str);
2837 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2838 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2840 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2841 char *errmsg, int errmsg_len)
2844 gchar *capfile_name;
2845 gchar *prefix, *suffix;
2846 gboolean is_tempfile;
2848 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2849 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
2851 if (capture_opts->save_file != NULL) {
2852 /* We return to the caller while the capture is in progress.
2853 * Therefore we need to take a copy of save_file in
2854 * case the caller destroys it after we return.
2856 capfile_name = g_strdup(capture_opts->save_file);
2858 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2859 if (capture_opts->multi_files_on) {
2860 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2861 g_snprintf(errmsg, errmsg_len,
2862 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2863 g_free(capfile_name);
2866 if (strcmp(capfile_name, "-") == 0) {
2867 /* write to stdout */
2870 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2871 _setmode(1, O_BINARY);
2874 } /* if (...output_to_pipe ... */
2877 if (capture_opts->multi_files_on) {
2878 /* ringbuffer is enabled */
2879 *save_file_fd = ringbuf_init(capfile_name,
2880 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
2881 capture_opts->group_read_access);
2883 /* we need the ringbuf name */
2884 if (*save_file_fd != -1) {
2885 g_free(capfile_name);
2886 capfile_name = g_strdup(ringbuf_current_filename());
2889 /* Try to open/create the specified file for use as a capture buffer. */
2890 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2891 (capture_opts->group_read_access) ? 0640 : 0600);
2894 is_tempfile = FALSE;
2896 /* Choose a random name for the temporary capture buffer */
2897 if (global_capture_opts.ifaces->len > 1) {
2898 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
2899 if (capture_opts->use_pcapng) {
2906 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
2908 /* use the generic portion of the interface guid to form the basis of the filename */
2909 if (strncmp("NPF_{", basename, 5)==0)
2911 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
2913 iface = isolate_uuid(basename);
2915 basename = g_strdup(iface->str);
2916 g_string_free(iface, TRUE);
2919 /* generate the temp file name prefix and suffix */
2920 if (capture_opts->use_pcapng) {
2921 prefix = g_strconcat("wireshark_", basename, NULL);
2924 prefix = g_strconcat("wireshark_", basename, NULL);
2929 *save_file_fd = create_tempfile(&tmpname, prefix, suffix);
2931 capfile_name = g_strdup(tmpname);
2935 /* did we fail to open the output file? */
2936 if (*save_file_fd == -1) {
2938 g_snprintf(errmsg, errmsg_len,
2939 "The temporary file to which the capture would be saved (\"%s\") "
2940 "could not be opened: %s.", capfile_name, g_strerror(errno));
2942 if (capture_opts->multi_files_on) {
2943 ringbuf_error_cleanup();
2946 g_snprintf(errmsg, errmsg_len,
2947 "The file to which the capture would be saved (\"%s\") "
2948 "could not be opened: %s.", capfile_name,
2951 g_free(capfile_name);
2955 if (capture_opts->save_file != NULL) {
2956 g_free(capture_opts->save_file);
2958 capture_opts->save_file = capfile_name;
2959 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2960 "g_free(capfile_name)". */
2966 /* Do the work of handling either the file size or file duration capture
2967 conditions being reached, and switching files or stopping. */
2969 do_file_switch_or_stop(capture_options *capture_opts,
2970 condition *cnd_autostop_files,
2971 condition *cnd_autostop_size,
2972 condition *cnd_file_duration)
2975 capture_src *pcap_src;
2976 interface_options interface_opts;
2977 gboolean successful;
2979 if (capture_opts->multi_files_on) {
2980 if (cnd_autostop_files != NULL &&
2981 cnd_eval(cnd_autostop_files, (guint64)++global_ld.autostop_files)) {
2982 /* no files left: stop here */
2983 global_ld.go = FALSE;
2987 /* Switch to the next ringbuffer file */
2988 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2989 &global_ld.save_file_fd, &global_ld.err)) {
2991 /* File switch succeeded: reset the conditions */
2992 global_ld.bytes_written = 0;
2993 if (capture_opts->use_pcapng) {
2995 GString *cpu_info_str;
2996 GString *os_info_str;
2998 cpu_info_str = g_string_new("");
2999 os_info_str = g_string_new("");
3000 get_cpu_info(cpu_info_str);
3001 get_os_version_info(os_info_str);
3003 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
3004 successful = pcapng_write_session_header_block(global_ld.pdh,
3005 (const char *)capture_opts->capture_comment, /* Comment */
3006 cpu_info_str->str, /* HW */
3007 os_info_str->str, /* OS */
3009 -1, /* section_length */
3010 &(global_ld.bytes_written),
3014 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3015 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3016 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3017 successful = pcapng_write_interface_description_block(global_ld.pdh,
3018 NULL, /* OPT_COMMENT 1 */
3019 interface_opts.name, /* IDB_NAME 2 */
3020 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3021 interface_opts.cfilter, /* IDB_FILTER 11 */
3022 os_info_str->str, /* IDB_OS 12 */
3025 &(global_ld.bytes_written),
3026 0, /* IDB_IF_SPEED 8 */
3027 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3031 g_string_free(os_info_str, TRUE);
3034 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3035 successful = libpcap_write_file_header(global_ld.pdh, pcap_src->linktype, pcap_src->snaplen,
3036 pcap_src->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3039 fclose(global_ld.pdh);
3040 global_ld.pdh = NULL;
3041 global_ld.go = FALSE;
3044 if (cnd_autostop_size)
3045 cnd_reset(cnd_autostop_size);
3046 if (cnd_file_duration)
3047 cnd_reset(cnd_file_duration);
3048 fflush(global_ld.pdh);
3050 report_packet_count(global_ld.inpkts_to_sync_pipe);
3051 global_ld.inpkts_to_sync_pipe = 0;
3052 report_new_capture_file(capture_opts->save_file);
3054 /* File switch failed: stop here */
3055 global_ld.go = FALSE;
3059 /* single file, stop now */
3060 global_ld.go = FALSE;
3067 pcap_read_handler(void* arg)
3069 capture_src *pcap_src;
3070 char errmsg[MSG_MAX_LENGTH+1];
3072 pcap_src = (capture_src *)arg;
3074 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3075 pcap_src->interface_id);
3077 while (global_ld.go) {
3078 /* dispatch incoming packets */
3079 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_src);
3081 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3082 pcap_src->interface_id);
3083 g_thread_exit(NULL);
3087 /* Do the low-level work of a capture.
3088 Returns TRUE if it succeeds, FALSE otherwise. */
3090 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3093 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3095 struct timeval upd_time, cur_time;
3099 condition *cnd_file_duration = NULL;
3100 condition *cnd_autostop_files = NULL;
3101 condition *cnd_autostop_size = NULL;
3102 condition *cnd_autostop_duration = NULL;
3105 gboolean cfilter_error = FALSE;
3106 char errmsg[MSG_MAX_LENGTH+1];
3107 char secondary_errmsg[MSG_MAX_LENGTH+1];
3108 capture_src *pcap_src;
3109 interface_options interface_opts;
3110 guint i, error_index = 0;
3113 *secondary_errmsg = '\0';
3115 /* init the loop data */
3116 global_ld.go = TRUE;
3117 global_ld.packet_count = 0;
3119 global_ld.report_packet_count = FALSE;
3121 if (capture_opts->has_autostop_packets)
3122 global_ld.packet_max = capture_opts->autostop_packets;
3124 global_ld.packet_max = 0; /* no limit */
3125 global_ld.inpkts_to_sync_pipe = 0;
3126 global_ld.err = 0; /* no error seen yet */
3127 global_ld.pdh = NULL;
3128 global_ld.autostop_files = 0;
3129 global_ld.save_file_fd = -1;
3131 /* We haven't yet gotten the capture statistics. */
3132 *stats_known = FALSE;
3134 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3135 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3137 /* open the "input file" from network interface or capture pipe */
3138 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3139 secondary_errmsg, sizeof(secondary_errmsg))) {
3142 for (i = 0; i < capture_opts->ifaces->len; i++) {
3143 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3144 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3145 /* init the input filter from the network interface (capture pipe will do nothing) */
3147 * When remote capturing WinPCap crashes when the capture filter
3148 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3151 switch (capture_loop_init_filter(pcap_src->pcap_h, pcap_src->from_cap_pipe,
3152 interface_opts.name,
3153 interface_opts.cfilter?interface_opts.cfilter:"")) {
3155 case INITFILTER_NO_ERROR:
3158 case INITFILTER_BAD_FILTER:
3159 cfilter_error = TRUE;
3161 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
3164 case INITFILTER_OTHER_ERROR:
3165 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3166 pcap_geterr(pcap_src->pcap_h));
3167 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3172 /* If we're supposed to write to a capture file, open it for output
3173 (temporary/specified name/ringbuffer) */
3174 if (capture_opts->saving_to_file) {
3175 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3176 errmsg, sizeof(errmsg))) {
3180 /* set up to write to the already-opened capture output file/files */
3181 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3186 /* XXX - capture SIGTERM and close the capture, in case we're on a
3187 Linux 2.0[.x] system and you have to explicitly close the capture
3188 stream in order to turn promiscuous mode off? We need to do that
3189 in other places as well - and I don't think that works all the
3190 time in any case, due to libpcap bugs. */
3192 /* Well, we should be able to start capturing.
3194 Sync out the capture file, so the header makes it to the file system,
3195 and send a "capture started successfully and capture file created"
3196 message to our parent so that they'll open the capture file and
3197 update its windows to indicate that we have a live capture in
3199 fflush(global_ld.pdh);
3200 report_new_capture_file(capture_opts->save_file);
3203 /* initialize capture stop (and alike) conditions */
3204 init_capture_stop_conditions();
3205 /* create stop conditions */
3206 if (capture_opts->has_autostop_filesize) {
3207 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3208 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3211 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3213 if (capture_opts->has_autostop_duration)
3214 cnd_autostop_duration =
3215 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3217 if (capture_opts->multi_files_on) {
3218 if (capture_opts->has_file_duration)
3220 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3222 if (capture_opts->has_autostop_files)
3223 cnd_autostop_files =
3224 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_files);
3227 /* init the time values */
3229 upd_time = GetTickCount();
3231 gettimeofday(&upd_time, NULL);
3233 start_time = create_timestamp();
3234 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3235 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3237 /* WOW, everything is prepared! */
3238 /* please fasten your seat belts, we will enter now the actual capture loop */
3240 pcap_queue = g_async_queue_new();
3241 pcap_queue_bytes = 0;
3242 pcap_queue_packets = 0;
3243 for (i = 0; i < global_ld.pcaps->len; i++) {
3244 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3245 #if GLIB_CHECK_VERSION(2,31,0)
3246 /* XXX - Add an interface name here? */
3247 pcap_src->tid = g_thread_new("Capture read", pcap_read_handler, pcap_src);
3249 pcap_src->tid = g_thread_create(pcap_read_handler, pcap_src, TRUE, NULL);
3253 while (global_ld.go) {
3254 /* dispatch incoming packets */
3256 pcap_queue_element *queue_element;
3257 #if GLIB_CHECK_VERSION(2,31,18)
3259 g_async_queue_lock(pcap_queue);
3260 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3262 GTimeVal write_thread_time;
3264 g_get_current_time(&write_thread_time);
3265 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3266 g_async_queue_lock(pcap_queue);
3267 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3269 if (queue_element) {
3270 pcap_queue_bytes -= queue_element->phdr.caplen;
3271 pcap_queue_packets -= 1;
3273 g_async_queue_unlock(pcap_queue);
3274 if (queue_element) {
3275 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3276 "Dequeued a packet of length %d captured on interface %d.",
3277 queue_element->phdr.caplen, queue_element->pcap_src->interface_id);
3279 capture_loop_write_packet_cb((u_char *) queue_element->pcap_src,
3280 &queue_element->phdr,
3282 g_free(queue_element->pd);
3283 g_free(queue_element);
3289 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3290 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3291 sizeof(errmsg), pcap_src);
3294 /* Were we asked to print packet counts by the SIGINFO handler? */
3295 if (global_ld.report_packet_count) {
3296 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3297 plurality(global_ld.packet_count, "", "s"));
3298 global_ld.report_packet_count = FALSE;
3303 /* any news from our parent (signal pipe)? -> just stop the capture */
3304 if (!signal_pipe_check_running()) {
3305 global_ld.go = FALSE;
3310 global_ld.inpkts_to_sync_pipe += inpkts;
3312 /* check capture size condition */
3313 if (cnd_autostop_size != NULL &&
3314 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3315 /* Capture size limit reached, do we have another file? */
3316 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3317 cnd_autostop_size, cnd_file_duration))
3319 } /* cnd_autostop_size */
3320 if (capture_opts->output_to_pipe) {
3321 fflush(global_ld.pdh);
3325 /* Only update once every 500ms so as not to overload slow displays.
3326 * This also prevents too much context-switching between the dumpcap
3327 * and wireshark processes.
3329 #define DUMPCAP_UPD_TIME 500
3332 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3333 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3335 gettimeofday(&cur_time, NULL);
3336 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3337 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3340 upd_time = cur_time;
3343 if (pcap_stats(pch, stats) >= 0) {
3344 *stats_known = TRUE;
3347 /* Let the parent process know. */
3348 if (global_ld.inpkts_to_sync_pipe) {
3350 fflush(global_ld.pdh);
3352 /* Send our parent a message saying we've written out
3353 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3355 report_packet_count(global_ld.inpkts_to_sync_pipe);
3357 global_ld.inpkts_to_sync_pipe = 0;
3360 /* check capture duration condition */
3361 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3362 /* The maximum capture time has elapsed; stop the capture. */
3363 global_ld.go = FALSE;
3367 /* check capture file duration condition */
3368 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3369 /* duration limit reached, do we have another file? */
3370 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3371 cnd_autostop_size, cnd_file_duration))
3373 } /* cnd_file_duration */
3377 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3379 pcap_queue_element *queue_element;
3381 for (i = 0; i < global_ld.pcaps->len; i++) {
3382 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3383 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3384 pcap_src->interface_id);
3385 g_thread_join(pcap_src->tid);
3386 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3387 pcap_src->interface_id);
3390 g_async_queue_lock(pcap_queue);
3391 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3392 if (queue_element) {
3393 pcap_queue_bytes -= queue_element->phdr.caplen;
3394 pcap_queue_packets -= 1;
3396 g_async_queue_unlock(pcap_queue);
3397 if (queue_element == NULL) {
3400 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3401 "Dequeued a packet of length %d captured on interface %d.",
3402 queue_element->phdr.caplen, queue_element->pcap_src->interface_id);
3403 capture_loop_write_packet_cb((u_char *)queue_element->pcap_src,
3404 &queue_element->phdr,
3406 g_free(queue_element->pd);
3407 g_free(queue_element);
3408 global_ld.inpkts_to_sync_pipe += 1;
3409 if (capture_opts->output_to_pipe) {
3410 fflush(global_ld.pdh);
3416 /* delete stop conditions */
3417 if (cnd_file_duration != NULL)
3418 cnd_delete(cnd_file_duration);
3419 if (cnd_autostop_files != NULL)
3420 cnd_delete(cnd_autostop_files);
3421 if (cnd_autostop_size != NULL)
3422 cnd_delete(cnd_autostop_size);
3423 if (cnd_autostop_duration != NULL)
3424 cnd_delete(cnd_autostop_duration);
3426 /* did we have a pcap (input) error? */
3427 for (i = 0; i < capture_opts->ifaces->len; i++) {
3428 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3429 if (pcap_src->pcap_err) {
3430 /* On Linux, if an interface goes down while you're capturing on it,
3431 you'll get a "recvfrom: Network is down" or
3432 "The interface went down" error (ENETDOWN).
3433 (At least you will if g_strerror() doesn't show a local translation
3436 On FreeBSD, DragonFly BSD, and macOS, if a network adapter
3437 disappears while you're capturing on it, you'll get a
3438 "read: Device not configured" error (ENXIO). (See previous
3439 parenthetical note.)
3441 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3443 These should *not* be reported to the Wireshark developers. */
3446 cap_err_str = pcap_geterr(pcap_src->pcap_h);
3447 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3448 strcmp(cap_err_str, "The interface went down") == 0 ||
3449 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3450 strcmp(cap_err_str, "read: I/O error") == 0 ||
3451 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3452 report_capture_error("The network adapter on which the capture was being done "
3453 "is no longer running; the capture has stopped.",
3456 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3458 report_capture_error(errmsg, please_report);
3461 } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
3462 report_capture_error(errmsg, "");
3466 /* did we have an output error while capturing? */
3467 if (global_ld.err == 0) {
3470 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3471 global_ld.err, FALSE);
3472 report_capture_error(errmsg, please_report);
3476 if (capture_opts->saving_to_file) {
3477 /* close the output file */
3478 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3482 /* there might be packets not yet notified to the parent */
3483 /* (do this after closing the file, so all packets are already flushed) */
3484 if (global_ld.inpkts_to_sync_pipe) {
3486 report_packet_count(global_ld.inpkts_to_sync_pipe);
3487 global_ld.inpkts_to_sync_pipe = 0;
3490 /* If we've displayed a message about a write error, there's no point
3491 in displaying another message about an error on close. */
3492 if (!close_ok && write_ok) {
3493 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3495 report_capture_error(errmsg, "");
3499 * XXX We exhibit different behaviour between normal mode and sync mode
3500 * when the pipe is stdin and not already at EOF. If we're a child, the
3501 * parent's stdin isn't closed, so if the user starts another capture,
3502 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3503 * will say "Unrecognized libpcap format". On the other hand, in normal
3504 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3507 report_capture_count(TRUE);
3509 /* get packet drop statistics from pcap */
3510 for (i = 0; i < capture_opts->ifaces->len; i++) {
3512 guint32 pcap_dropped = 0;
3514 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3515 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3516 received = pcap_src->received;
3517 if (pcap_src->pcap_h != NULL) {
3518 g_assert(!pcap_src->from_cap_pipe);
3519 /* Get the capture statistics, so we know how many packets were dropped. */
3521 * Older versions of libpcap didn't set ps_ifdrop on some
3522 * platforms; initialize it to 0 to handle that.
3524 stats->ps_ifdrop = 0;
3525 if (pcap_stats(pcap_src->pcap_h, stats) >= 0) {
3526 *stats_known = TRUE;
3527 /* Let the parent process know. */
3528 pcap_dropped += stats->ps_drop;
3530 g_snprintf(errmsg, sizeof(errmsg),
3531 "Can't get packet-drop statistics: %s",
3532 pcap_geterr(pcap_src->pcap_h));
3533 report_capture_error(errmsg, please_report);
3536 report_packet_drops(received, pcap_dropped, pcap_src->dropped, pcap_src->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
3539 /* close the input file (pcap or capture pipe) */
3540 capture_loop_close_input(&global_ld);
3542 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
3544 /* ok, if the write and the close were successful. */
3545 return write_ok && close_ok;
3548 if (capture_opts->multi_files_on) {
3549 /* cleanup ringbuffer */
3550 ringbuf_error_cleanup();
3552 /* We can't use the save file, and we have no FILE * for the stream
3553 to close in order to close it, so close the FD directly. */
3554 if (global_ld.save_file_fd != -1) {
3555 ws_close(global_ld.save_file_fd);
3558 /* We couldn't even start the capture, so get rid of the capture
3560 if (capture_opts->save_file != NULL) {
3561 ws_unlink(capture_opts->save_file);
3562 g_free(capture_opts->save_file);
3565 capture_opts->save_file = NULL;
3567 report_cfilter_error(capture_opts, error_index, errmsg);
3569 report_capture_error(errmsg, secondary_errmsg);
3571 /* close the input file (pcap or cap_pipe) */
3572 capture_loop_close_input(&global_ld);
3574 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3581 capture_loop_stop(void)
3583 #ifdef HAVE_PCAP_BREAKLOOP
3585 capture_src *pcap_src;
3587 for (i = 0; i < global_ld.pcaps->len; i++) {
3588 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3589 if (pcap_src->pcap_h != NULL)
3590 pcap_breakloop(pcap_src->pcap_h);
3593 global_ld.go = FALSE;
3598 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3599 int err, gboolean is_close)
3604 g_snprintf(errmsg, errmsglen,
3605 "Not all the packets could be written to the file"
3606 " to which the capture was being saved\n"
3607 "(\"%s\") because there is no space left on the file system\n"
3608 "on which that file resides.",
3614 g_snprintf(errmsg, errmsglen,
3615 "Not all the packets could be written to the file"
3616 " to which the capture was being saved\n"
3617 "(\"%s\") because you are too close to, or over,"
3618 " your disk quota\n"
3619 "on the file system on which that file resides.",
3626 g_snprintf(errmsg, errmsglen,
3627 "The file to which the capture was being saved\n"
3628 "(\"%s\") could not be closed: %s.",
3629 fname, g_strerror(err));
3631 g_snprintf(errmsg, errmsglen,
3632 "An error occurred while writing to the file"
3633 " to which the capture was being saved\n"
3635 fname, g_strerror(err));
3642 /* one packet was captured, process it */
3644 capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
3647 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
3649 guint ts_mul = pcap_src->ts_nsec ? 1000000000 : 1000000;
3651 /* We may be called multiple times from pcap_dispatch(); if we've set
3652 the "stop capturing" flag, ignore this packet, as we're not
3653 supposed to be saving any more packets. */
3654 if (!global_ld.go) {
3655 pcap_src->flushed++;
3659 if (global_ld.pdh) {
3660 gboolean successful;
3662 /* We're supposed to write the packet to a file; do so.
3663 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3664 "ld->err" to the error. */
3665 if (global_capture_opts.use_pcapng) {
3666 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
3668 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3669 phdr->caplen, phdr->len,
3670 pcap_src->interface_id,
3673 &global_ld.bytes_written, &err);
3675 successful = libpcap_write_packet(global_ld.pdh,
3676 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3677 phdr->caplen, phdr->len,
3679 &global_ld.bytes_written, &err);
3682 global_ld.go = FALSE;
3683 global_ld.err = err;
3684 pcap_src->dropped++;
3686 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3687 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3688 "Wrote a packet of length %d captured on interface %u.",
3689 phdr->caplen, pcap_src->interface_id);
3691 global_ld.packet_count++;
3692 pcap_src->received++;
3693 /* if the user told us to stop after x packets, do we already have enough? */
3694 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
3695 global_ld.go = FALSE;
3701 /* one packet was captured, queue it */
3703 capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
3706 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
3707 pcap_queue_element *queue_element;
3708 gboolean limit_reached;
3710 /* We may be called multiple times from pcap_dispatch(); if we've set
3711 the "stop capturing" flag, ignore this packet, as we're not
3712 supposed to be saving any more packets. */
3713 if (!global_ld.go) {
3714 pcap_src->flushed++;
3718 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
3719 if (queue_element == NULL) {
3720 pcap_src->dropped++;
3723 queue_element->pcap_src = pcap_src;
3724 queue_element->phdr = *phdr;
3725 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
3726 if (queue_element->pd == NULL) {
3727 pcap_src->dropped++;
3728 g_free(queue_element);
3731 memcpy(queue_element->pd, pd, phdr->caplen);
3732 g_async_queue_lock(pcap_queue);
3733 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
3734 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
3735 limit_reached = FALSE;
3736 g_async_queue_push_unlocked(pcap_queue, queue_element);
3737 pcap_queue_bytes += phdr->caplen;
3738 pcap_queue_packets += 1;
3740 limit_reached = TRUE;
3742 g_async_queue_unlock(pcap_queue);
3743 if (limit_reached) {
3744 pcap_src->dropped++;
3745 g_free(queue_element->pd);
3746 g_free(queue_element);
3747 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3748 "Dropped a packet of length %d captured on interface %u.",
3749 phdr->caplen, pcap_src->interface_id);
3751 pcap_src->received++;
3752 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3753 "Queued a packet of length %d captured on interface %u.",
3754 phdr->caplen, pcap_src->interface_id);
3756 /* I don't want to hold the mutex over the debug output. So the
3757 output may be wrong */
3758 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3759 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
3760 pcap_queue_bytes, pcap_queue_packets);
3764 set_80211_channel(const char *iface, const char *opt)
3768 guint32 center_freq1 = 0;
3769 guint32 center_freq2 = 0;
3772 gchar **options = NULL;
3774 options = g_strsplit_set(opt, ",", 4);
3775 for (args = 0; options[args]; args++);
3778 freq = get_nonzero_guint32(options[0], "802.11 channel frequency");
3780 if (args >= 1 && options[1]) {
3781 type = ws80211_str_to_chan_type(options[1]);
3783 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
3789 if (args >= 2 && options[2])
3790 center_freq1 = get_nonzero_guint32(options[2], "VHT center frequency");
3792 if (args >= 3 && options[3])
3793 center_freq2 = get_nonzero_guint32(options[3], "VHT center frequency 2");
3795 ret = ws80211_init();
3797 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
3801 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
3804 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
3810 pipe_write_block(2, SP_SUCCESS, NULL);
3813 g_strfreev(options);
3818 get_dumpcap_compiled_info(GString *str)
3820 /* Capture libraries */
3821 g_string_append(str, ", ");
3822 get_compiled_caplibs_version(str);
3826 get_dumpcap_runtime_info(GString *str)
3828 /* Capture libraries */
3829 g_string_append(str, ", ");
3830 get_runtime_caplibs_version(str);
3833 /* And now our feature presentation... [ fade to music ] */
3835 main(int argc, char *argv[])
3837 GString *comp_info_str;
3838 GString *runtime_info_str;
3840 static const struct option long_options[] = {
3841 {"help", no_argument, NULL, 'h'},
3842 {"version", no_argument, NULL, 'v'},
3843 LONGOPT_CAPTURE_COMMON
3847 gboolean arg_error = FALSE;
3853 struct sigaction action, oldaction;
3856 gboolean start_capture = TRUE;
3857 gboolean stats_known;
3858 struct pcap_stat stats;
3859 GLogLevelFlags log_flags;
3860 gboolean list_interfaces = FALSE;
3861 gboolean list_link_layer_types = FALSE;
3862 #ifdef HAVE_BPF_IMAGE
3863 gboolean print_bpf_code = FALSE;
3865 gboolean set_chan = FALSE;
3866 gchar *set_chan_arg = NULL;
3867 gboolean machine_readable = FALSE;
3868 gboolean print_statistics = FALSE;
3869 int status, run_once_args = 0;
3872 #if defined(__APPLE__) && defined(__LP64__)
3873 struct utsname osinfo;
3877 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
3879 /* Get the compile-time version information string */
3880 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
3882 /* Get the run-time version information string */
3883 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
3885 /* Add it to the information to be reported on a crash. */
3886 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
3891 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
3892 g_string_free(comp_info_str, TRUE);
3893 g_string_free(runtime_info_str, TRUE);
3896 arg_list_utf_16to8(argc, argv);
3897 create_app_running_mutex();
3900 * Initialize our DLL search path. MUST be called before LoadLibrary
3903 ws_init_dll_search_path();
3906 #ifdef HAVE_BPF_IMAGE
3907 #define OPTSTRING_d "d"
3909 #define OPTSTRING_d ""
3912 #ifdef HAVE_PCAP_REMOTE
3913 #define OPTSTRING_r "r"
3914 #define OPTSTRING_u "u"
3916 #define OPTSTRING_r ""
3917 #define OPTSTRING_u ""
3920 #ifdef HAVE_PCAP_SETSAMPLING
3921 #define OPTSTRING_m "m:"
3923 #define OPTSTRING_m ""
3926 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
3928 #ifdef DEBUG_CHILD_DUMPCAP
3929 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3930 fprintf (stderr, "Unable to open debug log file .\n");
3935 #if defined(__APPLE__) && defined(__LP64__)
3937 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
3938 * a bug workaround - timeouts less than 1 second don't work with libpcap
3939 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3940 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
3941 * The problem is extremely unlikely to be reintroduced in a future
3944 if (uname(&osinfo) == 0) {
3946 * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
3947 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3948 * number of 10.0.0, not 10.1.0 - go figure).
3950 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
3951 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
3952 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
3953 need_timeout_workaround = TRUE;
3958 * Determine if dumpcap is being requested to run in a special
3959 * capture_child mode by going thru the command line args to see if
3960 * a -Z is present. (-Z is a hidden option).
3962 * The primary result of running in capture_child mode is that
3963 * all messages sent out on stderr are in a special type/len/string
3964 * format to allow message processing by type. These messages include
3965 * error messages if dumpcap fails to start the operation it was
3966 * requested to do, as well as various "status" messages which are sent
3967 * when an actual capture is in progress, and a "success" message sent
3968 * if dumpcap was requested to perform an operation other than a
3971 * Capture_child mode would normally be requested by a parent process
3972 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3973 * to which dumpcap stderr has been redirected. It might also have
3974 * another pipe to obtain dumpcap stdout output; for operations other
3975 * than a capture, that information is formatted specially for easier
3976 * parsing by the parent process.
3978 * Capture_child mode needs to be determined immediately upon
3979 * startup so that any messages generated by dumpcap in this mode
3980 * (eg: during initialization) will be formatted properly.
3983 for (i=1; i<argc; i++) {
3984 if (strcmp("-Z", argv[i]) == 0) {
3985 capture_child = TRUE;
3986 machine_readable = TRUE; /* request machine-readable output */
3988 /* set output pipe to binary mode, to avoid ugly text conversions */
3989 _setmode(2, O_BINARY);
3994 /* The default_log_handler will use stdout, which makes trouble in */
3995 /* capture child mode, as it uses stdout for its sync_pipe. */
3996 /* So: the filtering is done in the console_log_handler and not here.*/
3997 /* We set the log handlers right up front to make sure that any log */
3998 /* messages when running as child will be sent back to the parent */
3999 /* with the correct format. */
4004 G_LOG_LEVEL_CRITICAL|
4005 G_LOG_LEVEL_WARNING|
4006 G_LOG_LEVEL_MESSAGE|
4010 G_LOG_FLAG_RECURSION);
4012 g_log_set_handler(NULL,
4014 console_log_handler, NULL /* user_data */);
4015 g_log_set_handler(LOG_DOMAIN_MAIN,
4017 console_log_handler, NULL /* user_data */);
4018 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4020 console_log_handler, NULL /* user_data */);
4021 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4023 console_log_handler, NULL /* user_data */);
4025 /* Initialize the pcaps list */
4026 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(capture_src *));
4028 #if !GLIB_CHECK_VERSION(2,31,0)
4029 /* Initialize the thread system */
4030 g_thread_init(NULL);
4034 /* Load wpcap if possible. Do this before collecting the run-time version information */
4037 /* ... and also load the packet.dll from wpcap */
4038 /* XXX - currently not required, may change later. */
4039 /*wpcap_packet_load();*/
4041 /* Start windows sockets */
4042 result = WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4045 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_ERROR,
4046 "ERROR: WSAStartup failed with error: %d", result);
4050 /* Set handler for Ctrl+C key */
4051 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4053 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4054 and exit. Do the same with SIGPIPE, in case, for example,
4055 we're writing to our standard output and it's a pipe.
4056 Do the same with SIGHUP if it's not being ignored (if we're
4057 being run under nohup, it might be ignored, in which case we
4058 should leave it ignored).
4060 XXX - apparently, Coverity complained that part of action
4061 wasn't initialized. Perhaps it's running on Linux, where
4062 struct sigaction has an ignored "sa_restorer" element and
4063 where "sa_handler" and "sa_sigaction" might not be two
4064 members of a union. */
4065 memset(&action, 0, sizeof(action));
4066 action.sa_handler = capture_cleanup_handler;
4068 * Arrange that system calls not get restarted, because when
4069 * our signal handler returns we don't want to restart
4070 * a call that was waiting for packets to arrive.
4072 action.sa_flags = 0;
4073 sigemptyset(&action.sa_mask);
4074 sigaction(SIGTERM, &action, NULL);
4075 sigaction(SIGINT, &action, NULL);
4076 sigaction(SIGPIPE, &action, NULL);
4077 sigaction(SIGHUP, NULL, &oldaction);
4078 if (oldaction.sa_handler == SIG_DFL)
4079 sigaction(SIGHUP, &action, NULL);
4082 /* Catch SIGINFO and, if we get it and we're capturing in
4083 quiet mode, report the number of packets we've captured. */
4084 action.sa_handler = report_counts_siginfo;
4085 action.sa_flags = SA_RESTART;
4086 sigemptyset(&action.sa_mask);
4087 sigaction(SIGINFO, &action, NULL);
4088 #endif /* SIGINFO */
4092 enable_kernel_bpf_jit_compiler();
4095 /* ----------------------------------------------------------------- */
4096 /* Privilege and capability handling */
4098 /* 1. Running not as root or suid root; no special capabilities. */
4101 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4104 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4106 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4107 /* capabilities; Drop all other capabilities; */
4108 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4109 /* else: after pcap_open_live() in capture_loop_open_input() */
4110 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4111 /* (Note: this means that the process, although logged in */
4112 /* as root, does not have various permissions such as the */
4113 /* ability to bypass file access permissions). */
4114 /* XXX: Should we just leave capabilities alone in this case */
4115 /* so that user gets expected effect that root can do */
4118 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4120 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4121 /* else: after pcap_open_live() in capture_loop_open_input() */
4122 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4123 /* pcap_open_live). */
4125 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4127 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4128 /* capabilities; Drop all other capabilities; */
4129 /* Drop suid privileges (euid=ruid); */
4130 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4131 /* else: after pcap_open_live() in capture_loop_open_input() */
4132 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4134 /* XXX: For some Linux versions/distros with capabilities */
4135 /* a 'normal' process with any capabilities cannot be */
4136 /* 'killed' (signaled) from another (same uid) non-privileged */
4138 /* For example: If (non-suid) Wireshark forks a */
4139 /* child suid dumpcap which acts as described here (case 5), */
4140 /* Wireshark will be unable to kill (signal) the child */
4141 /* dumpcap process until the capabilities have been dropped */
4142 /* (after pcap_open_live()). */
4143 /* This behaviour will apparently be changed in the kernel */
4144 /* to allow the kill (signal) in this case. */
4145 /* See the following for details: */
4146 /* https://www.mail-archive.com/ [wrapped] */
4147 /* linux-security-module@vger.kernel.org/msg02913.html */
4149 /* It is therefore conceivable that if dumpcap somehow hangs */
4150 /* in pcap_open_live or before that wireshark will not */
4151 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4152 /* In this case, exiting wireshark will kill the child */
4153 /* dumpcap process. */
4155 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4156 /* capabilities; Using libcap. Note: capset cmd (which see) */
4157 /* used to assign capabilities to file. */
4159 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4160 /* else: after pcap_open_live() in capture_loop_open_input() */
4161 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4163 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4164 /* longer required (similar to capture). */
4166 /* ----------------------------------------------------------------- */
4168 init_process_policies();
4171 /* If 'started with special privileges' (and using libcap) */
4172 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4173 /* Set euid/egid = ruid/rgid to remove suid privileges */
4174 relinquish_privs_except_capture();
4177 /* Set the initial values in the capture options. This might be overwritten
4178 by the command line parameters. */
4179 capture_opts_init(&global_capture_opts);
4180 /* We always save to a file - if no file was specified, we save to a
4182 global_capture_opts.saving_to_file = TRUE;
4183 global_capture_opts.has_ring_num_files = TRUE;
4185 /* Pass on capture_child mode for capture_opts */
4186 global_capture_opts.capture_child = capture_child;
4188 /* Now get our args */
4189 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4191 case 'h': /* Print help and exit */
4192 printf("Dumpcap (Wireshark) %s\n"
4193 "Capture network packets and dump them into a pcapng or pcap file.\n"
4194 "See https://www.wireshark.org for more information.\n",
4195 get_ws_vcs_version_info());
4196 print_usage(stdout);
4199 case 'v': /* Show version and exit */
4200 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4201 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4202 show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4203 g_string_free(comp_info_str, TRUE);
4204 g_string_free(runtime_info_str, TRUE);
4207 /*** capture option specific ***/
4208 case 'a': /* autostop criteria */
4209 case 'b': /* Ringbuffer option */
4210 case 'c': /* Capture x packets */
4211 case 'f': /* capture filter */
4212 case 'g': /* enable group read access on file(s) */
4213 case 'i': /* Use interface x */
4214 case 'n': /* Use pcapng format */
4215 case 'p': /* Don't capture in promiscuous mode */
4216 case 'P': /* Use pcap format */
4217 case 's': /* Set the snapshot (capture) length */
4218 case 'w': /* Write to capture file x */
4219 case 'y': /* Set the pcap data link type */
4220 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4221 #ifdef HAVE_PCAP_REMOTE
4222 case 'u': /* Use UDP for data transfer */
4223 case 'r': /* Capture own RPCAP traffic too */
4224 case 'A': /* Authentication */
4226 #ifdef HAVE_PCAP_SETSAMPLING
4227 case 'm': /* Sampling */
4229 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4230 case 'B': /* Buffer size */
4232 #ifdef HAVE_PCAP_CREATE
4233 case 'I': /* Monitor mode */
4235 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4240 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4242 capture_child = TRUE;
4244 /* set output pipe to binary mode, to avoid ugly text conversions */
4245 _setmode(2, O_BINARY);
4247 * optarg = the control ID, aka the PPID, currently used for the
4250 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4251 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4252 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4253 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4255 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4256 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4257 "Signal pipe: Unable to open %s. Dead parent?",
4265 case 'q': /* Quiet */
4271 /*** all non capture option specific ***/
4272 case 'D': /* Print a list of capture devices and exit */
4273 if (!list_interfaces) {
4274 list_interfaces = TRUE;
4278 case 'L': /* Print list of link-layer types and exit */
4279 if (!list_link_layer_types) {
4280 list_link_layer_types = TRUE;
4284 #ifdef HAVE_BPF_IMAGE
4285 case 'd': /* Print BPF code for capture filter and exit */
4286 if (!print_bpf_code) {
4287 print_bpf_code = TRUE;
4292 case 'S': /* Print interface statistics once a second */
4293 if (!print_statistics) {
4294 print_statistics = TRUE;
4298 case 'k': /* Set wireless channel */
4301 set_chan_arg = optarg;
4304 cmdarg_err("Only one -k flag may be specified");
4308 case 'M': /* For -D, -L, and -S, print machine-readable output */
4309 machine_readable = TRUE;
4312 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4315 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4318 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4320 case '?': /* Bad flag - print usage message */
4329 /* user specified file name as regular command-line argument */
4330 /* XXX - use it as the capture file name (or something else)? */
4336 * Extra command line arguments were specified; complain.
4337 * XXX - interpret as capture filter, as tcpdump and tshark do?
4339 cmdarg_err("Invalid argument: %s", argv[0]);
4344 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4347 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4348 /* Use some default if the user hasn't specified some */
4349 /* XXX: Are these defaults good enough? */
4350 pcap_queue_byte_limit = 1000 * 1000;
4351 pcap_queue_packet_limit = 1000;
4354 print_usage(stderr);
4358 if (run_once_args > 1) {
4359 #ifdef HAVE_BPF_IMAGE
4360 cmdarg_err("Only one of -D, -L, -d, -k, or -S may be supplied.");
4362 cmdarg_err("Only one of -D, -L, -k, or -S may be supplied.");
4365 } else if (run_once_args == 1) {
4366 /* We're supposed to print some information, rather than
4367 to capture traffic; did they specify a ring buffer option? */
4368 if (global_capture_opts.multi_files_on) {
4369 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4373 /* We're supposed to capture traffic; */
4375 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4376 if (global_capture_opts.ifaces->len > 1) {
4378 global_capture_opts.use_pcapng = TRUE;
4381 if (global_capture_opts.capture_comment &&
4382 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4383 /* XXX - for ringbuffer, should we apply the comment to each file? */
4384 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4388 /* Was the ring buffer option specified and, if so, does it make sense? */
4389 if (global_capture_opts.multi_files_on) {
4390 /* Ring buffer works only under certain conditions:
4391 a) ring buffer does not work with temporary files;
4392 b) it makes no sense to enable the ring buffer if the maximum
4393 file size is set to "infinite". */
4394 if (global_capture_opts.save_file == NULL) {
4395 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4396 global_capture_opts.multi_files_on = FALSE;
4398 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4399 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4401 /* XXX - this must be redesigned as the conditions changed */
4402 global_capture_opts.multi_files_on = FALSE;
4409 * "-D" requires no interface to be selected; it's supposed to list
4412 if (list_interfaces) {
4413 /* Get the list of interfaces */
4418 if_list = capture_interface_list(&err, &err_str,NULL);
4419 if (if_list == NULL) {
4422 * If we're being run by another program, just give them
4423 * an empty list of interfaces, don't report this as
4424 * an error; that lets them decide whether to report
4425 * this as an error or not.
4427 if (!machine_readable) {
4428 cmdarg_err("There are no interfaces on which a capture can be done");
4432 cmdarg_err("%s", err_str);
4438 if (machine_readable) /* tab-separated values to stdout */
4439 print_machine_readable_interfaces(if_list);
4441 capture_opts_print_interfaces(if_list);
4442 free_interface_list(if_list);
4447 * "-S" requires no interface to be selected; it gives statistics
4448 * for all interfaces.
4450 if (print_statistics) {
4451 status = print_statistics_loop(machine_readable);
4456 interface_options interface_opts;
4458 if (global_capture_opts.ifaces->len != 1) {
4459 cmdarg_err("Need one interface");
4463 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4464 status = set_80211_channel(interface_opts.name, set_chan_arg);
4469 * "-L", "-d", and capturing act on a particular interface, so we have to
4470 * have an interface; if none was specified, pick a default.
4472 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4474 /* cmdarg_err() already called .... */
4478 if (list_link_layer_types) {
4479 /* Get the list of link-layer types for the capture device. */
4480 if_capabilities_t *caps;
4484 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4485 interface_options interface_opts;
4487 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4489 caps = get_if_capabilities(&interface_opts, &err_str);
4491 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4492 "Please check to make sure you have sufficient permissions, and that\n"
4493 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4497 if (caps->data_link_types == NULL) {
4498 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4501 if (machine_readable) /* tab-separated values to stdout */
4502 /* XXX: We need to change the format and adopt consumers */
4503 print_machine_readable_if_capabilities(caps);
4505 /* XXX: We might want to print also the interface name */
4506 capture_opts_print_if_capabilities(caps, interface_opts.name,
4507 interface_opts.monitor_mode);
4508 free_if_capabilities(caps);
4513 /* We're supposed to do a capture, or print the BPF code for a filter. */
4515 /* Let the user know what interfaces were chosen. */
4516 if (capture_child) {
4517 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4518 interface_options interface_opts;
4520 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4521 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4522 interface_opts.name);
4525 str = g_string_new("");
4527 if (global_capture_opts.ifaces->len < 2)
4529 if (global_capture_opts.ifaces->len < 4)
4532 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4533 interface_options interface_opts;
4535 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4537 if (global_capture_opts.ifaces->len > 2) {
4538 g_string_append_printf(str, ",");
4540 g_string_append_printf(str, " ");
4541 if (j == global_capture_opts.ifaces->len - 1) {
4542 g_string_append_printf(str, "and ");
4545 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4548 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4550 fprintf(stderr, "Capturing on %s\n", str->str);
4551 g_string_free(str, TRUE);
4554 /* Process the snapshot length, as that affects the generated BPF code. */
4555 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4557 #ifdef HAVE_BPF_IMAGE
4558 if (print_bpf_code) {
4559 show_filter_code(&global_capture_opts);
4564 /* We're supposed to do a capture. Process the ring buffer arguments. */
4565 capture_opts_trim_ring_num_files(&global_capture_opts);
4567 /* flush stderr prior to starting the main capture loop */
4570 /* Now start the capture. */
4571 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4575 /* capture failed */
4578 return 0; /* never here, make compiler happy */
4583 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4584 const char *message, gpointer user_data _U_)
4591 /* ignore log message, if log_level isn't interesting */
4592 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4593 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4598 switch(log_level & G_LOG_LEVEL_MASK) {
4599 case G_LOG_LEVEL_ERROR:
4602 case G_LOG_LEVEL_CRITICAL:
4605 case G_LOG_LEVEL_WARNING:
4608 case G_LOG_LEVEL_MESSAGE:
4611 case G_LOG_LEVEL_INFO:
4614 case G_LOG_LEVEL_DEBUG:
4618 fprintf(stderr, "unknown log_level %d\n", log_level);
4620 g_assert_not_reached();
4623 /* Generate the output message */
4624 if (log_level & G_LOG_LEVEL_MESSAGE) {
4625 /* normal user messages without additional infos */
4626 msg = g_strdup_printf("%s\n", message);
4628 /* create a "timestamp" */
4630 today = localtime(&curr);
4632 /* info/debug messages with additional infos */
4634 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4635 today->tm_hour, today->tm_min, today->tm_sec,
4636 log_domain != NULL ? log_domain : "",
4639 msg = g_strdup_printf("Time not representable %8s %s %s\n",
4640 log_domain != NULL ? log_domain : "",
4644 /* DEBUG & INFO msgs (if we're debugging today) */
4645 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4646 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4647 #ifdef DEBUG_DUMPCAP
4648 fprintf(stderr, "%s", msg);
4651 #ifdef DEBUG_CHILD_DUMPCAP
4652 fprintf(debug_log, "%s", msg);
4660 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4661 /* to parent especially formatted if dumpcap running as child. */
4662 if (capture_child) {
4663 sync_pipe_errmsg_to_parent(2, msg, "");
4665 fprintf(stderr, "%s", msg);
4672 /****************************************************************************************************************/
4673 /* indication report routines */
4677 report_packet_count(unsigned int packet_count)
4679 char tmp[SP_DECISIZE+1+1];
4680 static unsigned int count = 0;
4682 if (capture_child) {
4683 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
4684 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4685 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4687 count += packet_count;
4688 fprintf(stderr, "\rPackets: %u ", count);
4689 /* stderr could be line buffered */
4695 report_new_capture_file(const char *filename)
4697 if (capture_child) {
4698 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4699 pipe_write_block(2, SP_FILE, filename);
4703 * Prevent a SIGINFO handler from writing to the standard error
4704 * while we're doing so; instead, have it just set a flag telling
4705 * us to print that information when we're done.
4708 #endif /* SIGINFO */
4709 fprintf(stderr, "File: %s\n", filename);
4710 /* stderr could be line buffered */
4715 * Allow SIGINFO handlers to write.
4720 * If a SIGINFO handler asked us to write out capture counts, do so.
4723 report_counts_for_siginfo();
4724 #endif /* SIGINFO */
4729 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4731 interface_options interface_opts;
4732 char tmp[MSG_MAX_LENGTH+1+6];
4734 if (i < capture_opts->ifaces->len) {
4735 if (capture_child) {
4736 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4737 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4738 pipe_write_block(2, SP_BAD_FILTER, tmp);
4741 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
4742 * the error message below.
4744 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
4746 "Invalid capture filter \"%s\" for interface '%s'.\n"
4748 "That string isn't a valid capture filter (%s).\n"
4749 "See the User's Guide for a description of the capture filter syntax.",
4750 interface_opts.cfilter, interface_opts.name, errmsg);
4756 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4758 if (capture_child) {
4759 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4760 "Primary Error: %s", error_msg);
4761 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4762 "Secondary Error: %s", secondary_error_msg);
4763 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4765 cmdarg_err("%s", error_msg);
4766 if (secondary_error_msg[0] != '\0')
4767 cmdarg_err_cont("%s", secondary_error_msg);
4772 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
4774 char tmp[SP_DECISIZE+1+1];
4775 guint32 total_drops = pcap_drops + drops + flushed;
4777 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
4779 if (capture_child) {
4780 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4781 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
4782 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
4783 /* XXX: Need to provide interface id, changes to consumers required. */
4784 pipe_write_block(2, SP_DROPS, tmp);
4787 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
4788 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
4789 received ? 100.0 * received / (received + total_drops) : 0.0);
4790 /* stderr could be line buffered */
4796 /************************************************************************************************/
4797 /* signal_pipe handling */
4802 signal_pipe_check_running(void)
4804 /* any news from our parent? -> just stop the capture */
4808 /* if we are running standalone, no check required */
4809 if (!capture_child) {
4813 if (!sig_pipe_name || !sig_pipe_handle) {
4814 /* This shouldn't happen */
4815 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4816 "Signal pipe: No name or handle");
4821 * XXX - We should have the process ID of the parent (from the "-Z" flag)
4822 * at this point. Should we check to see if the parent is still alive,
4823 * e.g. by using OpenProcess?
4826 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
4828 if (!result || avail > 0) {
4829 /* peek failed or some bytes really available */
4830 /* (if not piping from stdin this would fail) */
4831 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4832 "Signal pipe: Stop capture: %s", sig_pipe_name);
4833 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4834 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
4835 sig_pipe_handle, result, avail);
4838 /* pipe ok and no bytes available */
4845 * Editor modelines - https://www.wireshark.org/tools/modelines.html
4850 * indent-tabs-mode: nil
4853 * vi: set shiftwidth=4 tabstop=8 expandtab:
4854 * :indentSize=4:tabSize=8:noTabs=true: