3 * Wireshark - Network traffic analyzer
4 * By Gerald Combs <gerald@wireshark.org>
5 * Copyright 1998 Gerald Combs
7 * SPDX-License-Identifier: GPL-2.0-or-later
13 #include <stdlib.h> /* for exit() */
18 #include <sys/types.h>
20 #ifdef HAVE_SYS_SOCKET_H
21 #include <sys/socket.h>
24 #ifdef HAVE_NETINET_IN_H
25 #include <netinet/in.h>
32 #ifdef HAVE_ARPA_INET_H
33 #include <arpa/inet.h>
36 #if defined(__APPLE__) && defined(__LP64__)
37 #include <sys/utsname.h>
43 #include <ui/cmdarg_err.h>
44 #include <wsutil/strtoi.h>
46 #include <version_info.h>
48 #ifndef HAVE_GETOPT_LONG
49 #include "wsutil/wsgetopt.h"
53 # include <sys/prctl.h>
54 # include <sys/capability.h>
57 #include "ringbuffer.h"
59 #include "caputils/capture_ifinfo.h"
60 #include "caputils/capture-pcap-util.h"
61 #include "caputils/capture-pcap-util-int.h"
63 #include "caputils/capture-wpcap.h"
66 #include "writecap/pcapio.h"
72 #include <ui/clopts_common.h>
73 #include <wsutil/privileges.h>
75 #include "sync_pipe.h"
77 #include "capture_opts.h"
78 #include <capchild/capture_session.h>
79 #include <capchild/capture_sync.h>
81 #include "wsutil/tempfile.h"
83 #include "wsutil/file_util.h"
84 #include "wsutil/cpu_info.h"
85 #include "wsutil/os_version_info.h"
86 #include "wsutil/str_util.h"
87 #include "wsutil/inet_addr.h"
88 #include "wsutil/time_util.h"
90 #include "caputils/ws80211_utils.h"
95 * Get information about libpcap format from "wiretap/libpcap.h".
96 * Get information about pcapng format from "wiretap/pcapng_module.h".
97 * XXX - can we just use pcap_open_offline() to read the pipe?
99 #include "wiretap/libpcap.h"
100 #include "wiretap/pcapng_module.h"
101 #include "wiretap/pcapng.h"
103 /**#define DEBUG_DUMPCAP**/
104 /**#define DEBUG_CHILD_DUMPCAP**/
108 #include <conio.h> /* _getch() */
112 #ifdef DEBUG_CHILD_DUMPCAP
113 FILE *debug_log; /* for logging debug messages to */
114 /* a file if DEBUG_CHILD_DUMPCAP */
118 static GAsyncQueue *pcap_queue;
119 static gint64 pcap_queue_bytes;
120 static gint64 pcap_queue_packets;
121 static gint64 pcap_queue_byte_limit = 0;
122 static gint64 pcap_queue_packet_limit = 0;
124 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
126 static gchar *sig_pipe_name = NULL;
127 static HANDLE sig_pipe_handle = NULL;
128 static gboolean signal_pipe_check_running(void);
132 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
133 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
136 /** Stop a low-level capture (stops the capture child). */
137 static void capture_loop_stop(void);
138 /** Close a pipe, or socket if \a from_socket is TRUE */
139 static void cap_pipe_close(int pipe_fd, gboolean from_socket);
141 #if !defined (__linux__)
142 #ifndef HAVE_PCAP_BREAKLOOP
144 * We don't have pcap_breakloop(), which is the only way to ensure that
145 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
146 * won't, if the call to read the next packet or batch of packets is
147 * is interrupted by a signal on UN*X, just go back and try again to
150 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
151 * the signal handler, set a flag to stop capturing; however, without
152 * a guarantee of that sort, we can't guarantee that we'll stop capturing
153 * if the read will be retried and won't time out if no packets arrive.
155 * Therefore, on at least some platforms, we work around the lack of
156 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
157 * to wait for packets to arrive, so that we're probably going to be
158 * blocked in the select() when the signal arrives, and can just bail
159 * out of the loop at that point.
161 * However, we don't want to do that on BSD (because "select()" doesn't work
162 * correctly on BPF devices on at least some releases of some flavors of
163 * BSD), and we don't want to do it on Windows (because "select()" is
164 * something for sockets, not for arbitrary handles). (Note that "Windows"
165 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
166 * using WinPcap, not a UNIX libpcap.)
168 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
169 * on BSD times out even if no packets have arrived, so we'll eventually
170 * exit pcap_dispatch() with an indication that no packets have arrived,
171 * and will break out of the capture loop at that point.
173 * On Windows, we can't send a SIGINT to stop capturing, so none of this
174 * applies in any case.
176 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
177 * want to include it if it's not present on this platform, however.
179 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
180 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
182 # define MUST_DO_SELECT
183 # endif /* avoid select */
184 #endif /* HAVE_PCAP_BREAKLOOP */
186 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
187 * in pcap_dispatch(); on the other hand, select() works just fine there.
188 * Hence we use a select for that come what may.
190 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
191 * internally, and, with TPACKET_V3, once that's supported, it'll
192 * support timeouts, at least as I understand the way the code works.
194 #define MUST_DO_SELECT
197 /** init the capture filter */
200 INITFILTER_BAD_FILTER,
201 INITFILTER_OTHER_ERROR
202 } initfilter_status_t;
205 STATE_EXPECT_REC_HDR,
218 typedef struct _pcap_pipe_info {
219 gboolean byte_swapped; /**< TRUE if data in the pipe is byte swapped. */
220 struct pcap_hdr hdr; /**< Pcap header when capturing from a pipe */
221 struct pcaprec_modified_hdr rechdr; /**< Pcap record header when capturing from a pipe */
224 typedef struct _pcapng_pipe_info {
225 struct pcapng_block_header_s bh; /**< Pcapng general block header when capturing from a pipe */
226 GArray *src_iface_to_global; /**< Int array mapping local IDB numbers to global_ld.interface_data */
227 } pcapng_pipe_info_t;
229 struct _loop_data; /* forward declaration so we can use it in the cap_pipe_dispatch function pointer */
232 * A source of packets from which we're capturing.
234 typedef struct _capture_src {
239 #ifdef MUST_DO_SELECT
240 int pcap_fd; /**< pcap file descriptor */
247 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
248 /**< capture pipe (unix only "input file") */
249 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
250 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
251 gboolean from_pcapng; /**< TRUE if we're capturing from pcapng format */
253 pcap_pipe_info_t pcap; /**< Pcap info when capturing from a pipe */
254 pcapng_pipe_info_t pcapng; /**< Pcapng info when capturing from a pipe */
257 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
259 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
260 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
261 char * cap_pipe_databuf; /**< Pointer to the data buffer we've allocated */
262 size_t cap_pipe_databuf_size; /**< Current size of the data buffer */
263 guint cap_pipe_max_pkt_size; /**< Maximum packet size allowed */
265 char * cap_pipe_buf; /**< Pointer to the buffer we read into */
266 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
267 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
269 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
270 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
272 int (*cap_pipe_dispatch)(struct _loop_data *, struct _capture_src *, char *, size_t);
273 cap_pipe_state_t cap_pipe_state;
274 cap_pipe_err_t cap_pipe_err;
277 GMutex *cap_pipe_read_mtx;
278 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
282 typedef struct _saved_idb {
284 guint interface_id; /* capture_src->interface_id for the associated SHB */
285 guint8 *idb; /* If non-NULL, IDB read from capture_src. This is an interface specified on the command line otherwise. */
290 * Global capture loop state.
292 typedef struct _loop_data {
294 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
295 int err; /**< if non-zero, error seen while capturing */
296 gint packets_captured; /**< Number of packets we have already captured */
297 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
299 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
301 GArray *pcaps; /**< Array of capture_src's on which we're capturing */
302 gboolean pcapng_passthrough; /**< We have one source and it's pcapng. Pass its SHB and IDBs through. */
303 guint8 *saved_shb; /**< SHB to write when we have one pcapng input */
304 GArray *saved_idbs; /**< Array of saved_idb_t, written when we have a new section or output file. */
305 GRWLock saved_shb_idb_lock; /**< Saved IDB RW mutex */
309 guint64 bytes_written; /**< Bytes written for the current file. */
310 /* autostop conditions */
311 int packets_written; /**< Packets written for the current file. */
313 /* ring buffer conditions */
314 GTimer *file_duration_timer;
315 time_t next_interval_time;
319 typedef struct _pcap_queue_element {
320 capture_src *pcap_src;
322 struct pcap_pkthdr phdr;
323 struct pcapng_block_header_s bh;
326 } pcap_queue_element;
329 * Standard secondary message for unexpected errors.
331 static const char please_report[] =
332 "Please report this to the Wireshark developers.\n"
333 "https://bugs.wireshark.org/\n"
334 "(This is not a crash; please do not report it as such.)";
337 * This needs to be static, so that the SIGINT handler can clear the "go"
338 * flag and for saved_shb_idb_lock.
340 static loop_data global_ld;
343 * Timeout, in milliseconds, for reads from the stream of captured packets
344 * from a capture device.
346 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
347 * 64-bit applications, with sub-second timeouts not to work. The bug is
348 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
350 #if defined(__APPLE__) && defined(__LP64__)
351 static gboolean need_timeout_workaround;
353 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
355 #define CAP_READ_TIMEOUT 250
359 * Timeout, in microseconds, for reads from the stream of captured packets
360 * from a pipe. Pipes don't have the same problem that BPF devices do
361 * in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
362 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
363 * of the offending versions of Snow Leopard.
365 * On Windows this value is converted to milliseconds and passed to
366 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
367 * will return immediately.
370 #define PIPE_READ_TIMEOUT 100000
372 #define PIPE_READ_TIMEOUT 250000
375 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
378 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
379 const char *message, gpointer user_data _U_);
381 /* capture related options */
382 static capture_options global_capture_opts;
383 static gboolean quiet = FALSE;
384 static gboolean use_threads = FALSE;
385 static guint64 start_time;
387 static void capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
389 static void capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
391 static void capture_loop_write_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, u_char *pd);
392 static void capture_loop_queue_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, u_char *pd);
393 static void capture_loop_get_errmsg(char *errmsg, size_t errmsglen,
394 char *secondary_errmsg,
395 size_t secondary_errmsglen,
396 const char *fname, int err,
399 static void WS_NORETURN exit_main(int err);
401 static void report_new_capture_file(const char *filename);
402 static void report_packet_count(unsigned int packet_count);
403 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
404 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
405 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
407 #define MSG_MAX_LENGTH 4096
410 print_usage(FILE *output)
412 fprintf(output, "\nUsage: dumpcap [options] ...\n");
413 fprintf(output, "\n");
414 fprintf(output, "Capture interface:\n");
415 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
416 " or for remote capturing, use one of these formats:\n"
417 " rpcap://<host>/<interface>\n"
418 " TCP@<host>:<port>\n");
419 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
420 #ifdef HAVE_PCAP_CREATE
421 fprintf(output, " -s <snaplen> packet snapshot length (def: appropriate maximum)\n");
423 fprintf(output, " -s <snaplen> packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
425 fprintf(output, " -p don't capture in promiscuous mode\n");
426 #ifdef HAVE_PCAP_CREATE
427 fprintf(output, " -I capture in monitor mode, if available\n");
429 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
430 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
432 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
433 fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
434 fprintf(output, " -D print list of interfaces and exit\n");
435 fprintf(output, " -L print list of link-layer types of iface and exit\n");
436 fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
437 #ifdef HAVE_BPF_IMAGE
438 fprintf(output, " -d print generated BPF code for capture filter\n");
440 fprintf(output, " -k set channel on wifi interface:\n"
441 " <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
442 fprintf(output, " -S print statistics for each interface once per second\n");
443 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
444 fprintf(output, "\n");
445 #ifdef HAVE_PCAP_REMOTE
446 fprintf(output, "RPCAP options:\n");
447 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
448 fprintf(output, " -u use UDP for RPCAP data transfer\n");
449 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
450 #ifdef HAVE_PCAP_SETSAMPLING
451 fprintf(output, " -m <sampling type> use packet sampling\n");
452 fprintf(output, " count:NUM - capture one packet of every NUM\n");
453 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
456 fprintf(output, "Stop conditions:\n");
457 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
458 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
459 fprintf(output, " filesize:NUM - stop this file after NUM kB\n");
460 fprintf(output, " files:NUM - stop after NUM files\n");
461 fprintf(output, " packets:NUM - stop after NUM packets\n");
462 /*fprintf(output, "\n");*/
463 fprintf(output, "Output (files):\n");
464 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
465 fprintf(output, " -g enable group read access on the output file(s)\n");
466 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
467 fprintf(output, " interval:NUM - create time intervals of NUM secs\n");
468 fprintf(output, " filesize:NUM - switch to next file after NUM kB\n");
469 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
470 fprintf(output, " packets:NUM - ringbuffer: replace after NUM packets\n");
471 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
472 fprintf(output, " -P use libpcap format instead of pcapng\n");
473 fprintf(output, " --capture-comment <comment>\n");
474 fprintf(output, " add a capture comment to the output file\n");
475 fprintf(output, " (only for pcapng)\n");
476 fprintf(output, "\n");
477 fprintf(output, "Miscellaneous:\n");
478 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
479 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
480 fprintf(output, " within dumpcap\n");
481 fprintf(output, " -t use a separate thread per interface\n");
482 fprintf(output, " -q don't report packet capture counts\n");
483 fprintf(output, " -v print version information and exit\n");
484 fprintf(output, " -h display this help and exit\n");
485 fprintf(output, "\n");
487 fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
488 fprintf(output, "You might want to enable it by executing:\n");
489 fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
490 fprintf(output, "Note that this can make your system less secure!\n");
491 fprintf(output, "\n");
493 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
494 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
495 fprintf(output, "\n");
496 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
500 * Report an error in command-line arguments.
501 * If we're a capture child, send a message back to the parent, otherwise
505 dumpcap_cmdarg_err(const char *fmt, va_list ap)
509 /* Generate a 'special format' message back to parent */
510 msg = g_strdup_vprintf(fmt, ap);
511 sync_pipe_errmsg_to_parent(2, msg, "");
514 fprintf(stderr, "dumpcap: ");
515 vfprintf(stderr, fmt, ap);
516 fprintf(stderr, "\n");
521 * Report additional information for an error in command-line arguments.
522 * If we're a capture child, send a message back to the parent, otherwise
526 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
530 msg = g_strdup_vprintf(fmt, ap);
531 sync_pipe_errmsg_to_parent(2, msg, "");
534 vfprintf(stderr, fmt, ap);
535 fprintf(stderr, "\n");
541 #if 0 /* Set to enable capability debugging */
542 /* see 'man cap_to_text()' for explanation of output */
543 /* '=' means 'all= ' ie: no capabilities */
544 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
546 print_caps(const char *pfx) {
547 cap_t caps = cap_get_proc();
548 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
549 "%s: EUID: %d Capabilities: %s", pfx,
550 geteuid(), cap_to_text(caps, NULL));
554 print_caps(const char *pfx _U_) {
559 relinquish_all_capabilities(void)
561 /* Drop any and all capabilities this process may have. */
562 /* Allowed whether or not process has any privileges. */
563 cap_t caps = cap_init(); /* all capabilities initialized to off */
564 print_caps("Pre-clear");
565 if (cap_set_proc(caps)) {
566 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
568 print_caps("Post-clear");
574 * Platform-dependent suggestions for fixing permissions.
576 #if defined(__linux__)
577 #define PLATFORM_PERMISSIONS_SUGGESTION \
579 "On Debian and Debian derivatives such as Ubuntu, if you have " \
580 "installed Wireshark from a package, try running" \
582 " sudo dpkg-reconfigure wireshark-common" \
584 "selecting \"<Yes>\" in response to the question" \
586 " Should non-superusers be able to capture packets?" \
588 "adding yourself to the \"wireshark\" group by running" \
590 " sudo usermod -a -G wireshark {your username}" \
592 "and then logging out and logging back in again."
593 #elif defined(__APPLE__)
594 #define PLATFORM_PERMISSIONS_SUGGESTION \
596 "If you installed Wireshark using the package from wireshark.org, "\
597 "Try re-installing it and checking the box for the \"Set capture " \
598 "permissions on startup\" item."
600 #define PLATFORM_PERMISSIONS_SUGGESTION
604 get_pcap_failure_secondary_error_message(cap_device_open_err open_err,
605 const char *open_err_str
613 * On Windows, first make sure they *have* WinPcap installed.
617 "In order to capture packets, WinPcap must be installed; see\n"
619 " https://www.winpcap.org/\n"
621 "for a downloadable version of WinPcap and for instructions on how to install\n"
627 * Now deal with ancient versions of libpcap that, on HP-UX, don't
628 * correctly figure out how to open a device given the device name.
631 /* HP-UX-specific suggestion. */
632 static const char ppamsg[] = "can't find PPA for ";
634 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0) {
636 "You are running (T)Wireshark with a version of the libpcap library\n"
637 "that doesn't handle HP-UX network devices well; this means that\n"
638 "(T)Wireshark may not be able to capture packets.\n"
640 "To fix this, you should install libpcap 0.6.2, or a later version\n"
641 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
642 "packaged binary form from the Software Porting And Archive Centre\n"
643 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
644 "at the URL lists a number of mirror sites.";
649 * OK, now just return a largely platform-independent error that might
650 * have platform-specific suggestions at the end (for example, suggestions
651 * for how to get permission to capture).
653 if (open_err == CAP_DEVICE_OPEN_ERR_GENERIC) {
655 * We don't know what kind of error it is, so throw all the
656 * suggestions at the user.
659 "Please check to make sure you have sufficient permissions, and that you have "
660 "the proper interface or pipe specified."
661 PLATFORM_PERMISSIONS_SUGGESTION;
662 } else if (open_err == CAP_DEVICE_OPEN_ERR_PERMISSIONS) {
664 * This is a permissions error, so no need to specify any other
668 "Please check to make sure you have sufficient permissions."
669 PLATFORM_PERMISSIONS_SUGGESTION;
672 * This is not a permissons error, so no need to suggest
673 * checking permissions.
676 "Please check that you have the proper interface or pipe specified.";
681 get_capture_device_open_failure_messages(cap_device_open_err open_err,
682 const char *open_err_str,
684 char *errmsg, size_t errmsg_len,
685 char *secondary_errmsg,
686 size_t secondary_errmsg_len)
688 g_snprintf(errmsg, (gulong) errmsg_len,
689 "The capture session could not be initiated on interface '%s' (%s).",
690 iface, open_err_str);
691 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, "%s",
692 get_pcap_failure_secondary_error_message(open_err, open_err_str));
696 compile_capture_filter(const char *iface, pcap_t *pcap_h,
697 struct bpf_program *fcode, const char *cfilter)
699 bpf_u_int32 netnum, netmask;
700 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
702 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
704 * Well, we can't get the netmask for this interface; it's used
705 * only for filters that check for broadcast IP addresses, so
706 * we just punt and use 0. It might be nice to warn the user,
707 * but that's a pain in a GUI application, as it'd involve popping
708 * up a message box, and it's not clear how often this would make
709 * a difference (only filters that check for IP broadcast addresses
713 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
718 * Sigh. Older versions of libpcap don't properly declare the
719 * third argument to pcap_compile() as a const pointer. Cast
723 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
729 #ifdef HAVE_BPF_IMAGE
731 show_filter_code(capture_options *capture_opts)
733 interface_options *interface_opts;
735 cap_device_open_err open_err;
736 gchar open_err_str[PCAP_ERRBUF_SIZE];
737 char errmsg[MSG_MAX_LENGTH+1];
738 char secondary_errmsg[MSG_MAX_LENGTH+1];
739 struct bpf_program fcode;
740 struct bpf_insn *insn;
744 for (j = 0; j < capture_opts->ifaces->len; j++) {
745 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, j);
746 pcap_h = open_capture_device(capture_opts, interface_opts,
747 CAP_READ_TIMEOUT, &open_err, &open_err_str);
748 if (pcap_h == NULL) {
749 /* Open failed; get messages */
750 get_capture_device_open_failure_messages(open_err, open_err_str,
751 interface_opts->name,
752 errmsg, sizeof errmsg,
754 sizeof secondary_errmsg);
755 /* And report them */
756 report_capture_error(errmsg, secondary_errmsg);
760 /* Set the link-layer type. */
761 if (!set_pcap_datalink(pcap_h, interface_opts->linktype, interface_opts->name,
762 errmsg, sizeof errmsg,
763 secondary_errmsg, sizeof secondary_errmsg)) {
765 report_capture_error(errmsg, secondary_errmsg);
769 /* OK, try to compile the capture filter. */
770 if (!compile_capture_filter(interface_opts->name, pcap_h, &fcode,
771 interface_opts->cfilter)) {
773 report_cfilter_error(capture_opts, j, errmsg);
778 /* Now print the filter code. */
779 insn = fcode.bf_insns;
781 for (i = 0; i < fcode.bf_len; insn++, i++)
782 printf("%s\n", bpf_image(insn, i));
784 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
785 /* to remove any suid privileges. */
786 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
787 /* (euid/egid have already previously been set to ruid/rgid. */
788 /* (See comment in main() for details) */
790 relinquish_special_privs_perm();
792 relinquish_all_capabilities();
795 /* Let our parent know we succeeded. */
796 pipe_write_block(2, SP_SUCCESS, NULL);
803 * capture_interface_list() is expected to do the right thing to get
804 * a list of interfaces.
806 * In most of the programs in the Wireshark suite, "the right thing"
807 * is to run dumpcap and ask it for the list, because dumpcap may
808 * be the only program in the suite with enough privileges to get
811 * In dumpcap itself, however, we obviously can't run dumpcap to
812 * ask for the list. Therefore, our capture_interface_list() should
813 * just call get_interface_list().
816 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
818 return get_interface_list(err, err_str);
822 * Output a machine readable list of the interfaces
823 * This list is retrieved by the sync_interface_list_open() function
824 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
827 print_machine_readable_interfaces(GList *if_list)
834 char addr_str[WS_INET6_ADDRSTRLEN];
837 /* Let our parent know we succeeded. */
838 pipe_write_block(2, SP_SUCCESS, NULL);
841 i = 1; /* Interface id number */
842 for (if_entry = g_list_first(if_list); if_entry != NULL;
843 if_entry = g_list_next(if_entry)) {
844 if_info = (if_info_t *)if_entry->data;
845 printf("%d. %s\t", i++, if_info->name);
848 * Print the contents of the if_entry struct in a parseable format.
849 * Each if_entry element is tab-separated. Addresses are comma-
852 /* XXX - Make sure our description doesn't contain a tab */
853 if (if_info->vendor_description != NULL)
854 printf("%s\t", if_info->vendor_description);
858 /* XXX - Make sure our friendly name doesn't contain a tab */
859 if (if_info->friendly_name != NULL)
860 printf("%s\t", if_info->friendly_name);
864 printf("%i\t", if_info->type);
866 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
867 addr = g_slist_next(addr)) {
868 if (addr != g_slist_nth(if_info->addrs, 0))
871 if_addr = (if_addr_t *)addr->data;
872 switch(if_addr->ifat_type) {
874 printf("%s", ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str, sizeof(addr_str)));
877 printf("%s", ws_inet_ntop6(&if_addr->addr.ip6_addr, addr_str, sizeof(addr_str)));
880 printf("<type unknown %i>", if_addr->ifat_type);
884 if (if_info->loopback)
885 printf("\tloopback");
888 printf("\t%s", if_info->extcap);
894 * If you change the machine-readable output format of this function,
895 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
898 print_machine_readable_if_capabilities(if_capabilities_t *caps, int queries)
900 GList *lt_entry, *ts_entry;
901 const gchar *desc_str;
904 /* Let our parent know we succeeded. */
905 pipe_write_block(2, SP_SUCCESS, NULL);
908 if (queries & CAPS_QUERY_LINK_TYPES) {
909 if (caps->can_set_rfmon)
913 for (lt_entry = caps->data_link_types; lt_entry != NULL;
914 lt_entry = g_list_next(lt_entry)) {
915 data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
916 if (data_link_info->description != NULL)
917 desc_str = data_link_info->description;
919 desc_str = "(not supported)";
920 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
925 if (queries & CAPS_QUERY_TIMESTAMP_TYPES) {
926 for (ts_entry = caps->timestamp_types; ts_entry != NULL;
927 ts_entry = g_list_next(ts_entry)) {
928 timestamp_info_t *timestamp = (timestamp_info_t *)ts_entry->data;
929 if (timestamp->description != NULL)
930 desc_str = timestamp->description;
933 printf("%s\t%s\n", timestamp->name, desc_str);
943 /* Print the number of packets captured for each interface until we're killed. */
945 print_statistics_loop(gboolean machine_readable)
947 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
953 char errbuf[PCAP_ERRBUF_SIZE];
956 if_list = get_interface_list(&err, &err_str);
957 if (if_list == NULL) {
959 cmdarg_err("There are no interfaces on which a capture can be done");
961 cmdarg_err("%s", err_str);
967 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
968 if_info = (if_info_t *)if_entry->data;
971 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
972 * connections. We avoid collecting stats on them.
974 if (!strncmp(if_info->name, "nf", 2)) {
975 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
981 #ifdef HAVE_PCAP_OPEN
982 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
984 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
988 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
989 if_stat->name = g_strdup(if_info->name);
991 stat_list = g_list_append(stat_list, if_stat);
996 cmdarg_err("There are no interfaces on which a capture can be done");
1000 if (capture_child) {
1001 /* Let our parent know we succeeded. */
1002 pipe_write_block(2, SP_SUCCESS, NULL);
1005 if (!machine_readable) {
1006 printf("%-15s %10s %10s\n", "Interface", "Received",
1010 global_ld.go = TRUE;
1011 while (global_ld.go) {
1012 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1013 if_stat = (if_stat_t *)stat_entry->data;
1014 pcap_stats(if_stat->pch, &ps);
1016 if (!machine_readable) {
1017 printf("%-15s %10u %10u\n", if_stat->name,
1018 ps.ps_recv, ps.ps_drop);
1020 printf("%s\t%u\t%u\n", if_stat->name,
1021 ps.ps_recv, ps.ps_drop);
1026 /* If we have a dummy signal pipe check it */
1027 if (!signal_pipe_check_running()) {
1028 global_ld.go = FALSE;
1036 /* XXX - Not reached. Should we look for 'q' in stdin? */
1037 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1038 if_stat = (if_stat_t *)stat_entry->data;
1039 pcap_close(if_stat->pch);
1040 g_free(if_stat->name);
1043 g_list_free(stat_list);
1044 free_interface_list(if_list);
1052 capture_cleanup_handler(DWORD dwCtrlType)
1054 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1055 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1056 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1057 like SIGTERM at least when the machine's shutting down.
1059 For now, if we're running as a command rather than a capture child,
1060 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1061 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1062 in that way on UN*X.
1064 If we're not running as a capture child, we might be running as
1065 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1066 user logs out. (XXX - can we explicitly check whether we're
1067 running as a service?) */
1069 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1070 "Console: Control signal");
1071 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1072 "Console: Control signal, CtrlType: %lu", dwCtrlType);
1074 /* Keep capture running if we're a service and a user logs off */
1075 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1076 capture_loop_stop();
1084 capture_cleanup_handler(int signum _U_)
1086 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1087 SIGTERM. We assume that if the user wanted it to keep running
1088 after they logged out, they'd have nohupped it. */
1090 /* Note: don't call g_log() in the signal handler: if we happened to be in
1091 * g_log() in process context when the signal came in, g_log will detect
1092 * the "recursion" and abort.
1095 capture_loop_stop();
1101 report_capture_count(gboolean reportit)
1103 /* Don't print this if we're a capture child. */
1104 if (!capture_child && reportit) {
1105 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packets_captured);
1106 /* stderr could be line buffered */
1114 report_counts_for_siginfo(void)
1116 report_capture_count(quiet);
1117 infoprint = FALSE; /* we just reported it */
1121 report_counts_siginfo(int signum _U_)
1123 int sav_errno = errno;
1125 /* If we've been told to delay printing, just set a flag asking
1126 that we print counts (if we're supposed to), otherwise print
1127 the count of packets captured (if we're supposed to). */
1131 report_counts_for_siginfo();
1134 #endif /* SIGINFO */
1137 exit_main(int status)
1140 /* Shutdown windows sockets */
1143 /* can be helpful for debugging */
1144 #ifdef DEBUG_DUMPCAP
1145 printf("Press any key\n");
1151 capture_opts_cleanup(&global_capture_opts);
1157 * If we were linked with libcap (not related to libpcap), make sure we have
1158 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1159 * (See comment in main() for details)
1162 relinquish_privs_except_capture(void)
1164 /* If 'started_with_special_privs' (ie: suid) then enable for
1165 * ourself the NET_ADMIN and NET_RAW capabilities and then
1166 * drop our suid privileges.
1168 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1169 * stuff we don't need (and shouldn't have).
1170 * CAP_NET_RAW: Packet capture (raw sockets).
1173 if (started_with_special_privs()) {
1174 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1175 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1177 cap_t caps = cap_init(); /* all capabilities initialized to off */
1179 print_caps("Pre drop, pre set");
1181 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1182 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1185 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1186 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1188 if (cap_set_proc(caps)) {
1189 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1191 print_caps("Pre drop, post set");
1193 relinquish_special_privs_perm();
1195 print_caps("Post drop, pre set");
1196 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1197 if (cap_set_proc(caps)) {
1198 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1200 print_caps("Post drop, post set");
1206 #endif /* HAVE_LIBCAP */
1208 /* Take care of byte order in the libpcap headers read from pipes.
1209 * (function taken from wiretap/libpcap.c) */
1211 cap_pipe_adjust_pcap_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1214 /* Byte-swap the record header fields. */
1215 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1216 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1217 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1218 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1221 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1222 swapped, in order to match the BPF header layout.
1224 Unfortunately, some files were, according to a comment in the "libpcap"
1225 source, written with version 2.3 in their headers but without the
1226 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1227 would make no sense - we assume that we need to swap them. */
1228 if (hdr->version_major == 2 &&
1229 (hdr->version_minor < 3 ||
1230 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1233 temp = rechdr->orig_len;
1234 rechdr->orig_len = rechdr->incl_len;
1235 rechdr->incl_len = temp;
1239 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1243 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1247 return recv(pipe_fd, buf, (int)sz, 0);
1252 return ws_read(pipe_fd, buf, sz);
1258 * Thread function that reads from a pipe and pushes the data
1259 * to the main application thread.
1262 * XXX Right now we use async queues for basic signaling. The main thread
1263 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1264 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1265 * Iff the read is successful cap_pipe_read pushes an item onto
1266 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1267 * the queues themselves (yet).
1269 * We might want to move some of the cap_pipe_dispatch logic here so that
1270 * we can let cap_thread_read run independently, queuing up multiple reads
1271 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1273 static void *cap_thread_read(void *arg)
1275 capture_src *pcap_src;
1278 DWORD last_err, bytes_read;
1283 pcap_src = (capture_src *)arg;
1284 while (pcap_src->cap_pipe_err == PIPOK) {
1285 g_async_queue_pop(pcap_src->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1286 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1288 while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1289 if ((pcap_src->from_cap_socket)
1296 b = cap_pipe_read(pcap_src->cap_pipe_fd, pcap_src->cap_pipe_buf+bytes_read,
1297 pcap_src->cap_pipe_bytes_to_read - bytes_read, pcap_src->from_cap_socket);
1300 pcap_src->cap_pipe_err = PIPEOF;
1304 pcap_src->cap_pipe_err = PIPERR;
1315 /* If we try to use read() on a named pipe on Windows with partial
1316 * data it appears to return EOF.
1319 res = ReadFile(pcap_src->cap_pipe_h, pcap_src->cap_pipe_buf+bytes_read,
1320 pcap_src->cap_pipe_bytes_to_read - bytes_read,
1325 last_err = GetLastError();
1326 if (last_err == ERROR_MORE_DATA) {
1328 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1329 pcap_src->cap_pipe_err = PIPEOF;
1333 pcap_src->cap_pipe_err = PIPERR;
1336 } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1337 pcap_src->cap_pipe_err = PIPEOF;
1344 pcap_src->cap_pipe_bytes_read = bytes_read;
1345 if (pcap_src->cap_pipe_bytes_read >= pcap_src->cap_pipe_bytes_to_read) {
1346 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1348 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1354 /* Provide select() functionality for a single file descriptor
1355 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1357 * Returns the same values as select.
1360 cap_pipe_select(int pipe_fd)
1363 struct timeval timeout;
1366 FD_SET(pipe_fd, &rfds);
1368 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1369 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1371 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1374 #define DEF_TCP_PORT 19000
1377 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, size_t errmsgl)
1379 char *sockname = pipename + 4;
1380 struct sockaddr_in sa;
1387 memset(&sa, 0, sizeof(sa));
1389 p = strchr(sockname, ':');
1391 len = strlen(sockname);
1392 port = DEF_TCP_PORT;
1396 port = strtoul(p + 1, &p, 10);
1397 if (*p || port > 65535) {
1406 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1408 if (!ws_inet_pton4(buf, (guint32 *)&sa.sin_addr)) {
1412 sa.sin_family = AF_INET;
1413 sa.sin_port = g_htons((u_short)port);
1415 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1416 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1418 LPTSTR errorText = NULL;
1421 lastError = WSAGetLastError();
1422 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1423 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1424 FORMAT_MESSAGE_IGNORE_INSERTS,
1425 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1426 (LPTSTR)&errorText, 0, NULL);
1428 g_snprintf(errmsg, (gulong)errmsgl,
1429 "The capture session could not be initiated due to the socket error: \n"
1431 " %d: %s", lastError, errorText ? (char *)errorText : "Unknown");
1433 LocalFree(errorText);
1435 " %d: %s", errno, g_strerror(errno));
1437 pcap_src->cap_pipe_err = PIPERR;
1440 cap_pipe_close(fd, TRUE);
1444 pcap_src->from_cap_socket = TRUE;
1448 g_snprintf(errmsg, (gulong)errmsgl,
1449 "The capture session could not be initiated because\n"
1450 "\"%s\" is not a valid socket specification", pipename);
1451 pcap_src->cap_pipe_err = PIPERR;
1455 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1459 cap_pipe_close(int pipe_fd, gboolean from_socket)
1463 closesocket(pipe_fd);
1466 (void) from_socket; /* Mark unused, similar to Q_UNUSED */
1471 /** Read bytes from a capture source, which is assumed to be a pipe.
1473 * Returns -1, or the number of bytes read similar to read(2).
1474 * Sets pcap_src->cap_pipe_err on error or EOF.
1477 cap_pipe_read_data_bytes(capture_src *pcap_src, char *errmsg, size_t errmsgl)
1480 int fd = pcap_src->cap_pipe_fd;
1482 DWORD sz, bytes_read = 0;
1484 ssize_t sz, bytes_read = 0;
1488 #ifdef LOG_CAPTURE_VERBOSE
1489 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_read_data_bytes read %lu of %lu",
1490 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1492 sz = pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read;
1493 while (bytes_read < sz) {
1495 g_snprintf(errmsg, (gulong)errmsgl, "Invalid file descriptor.");
1496 pcap_src->cap_pipe_err = PIPNEXIST;
1500 sel_ret = cap_pipe_select(fd);
1502 g_snprintf(errmsg, (gulong)errmsgl,
1503 "Unexpected error from select: %s.", g_strerror(errno));
1504 pcap_src->cap_pipe_err = PIPERR;
1506 } else if (sel_ret > 0) {
1507 b = cap_pipe_read(fd, pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read+bytes_read,
1508 sz-bytes_read, pcap_src->from_cap_socket);
1511 g_snprintf(errmsg, (gulong)errmsgl,
1512 "End of file on pipe during cap_pipe_read.");
1513 pcap_src->cap_pipe_err = PIPEOF;
1516 LPTSTR errorText = NULL;
1517 int lastError = WSAGetLastError();
1519 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1520 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1521 FORMAT_MESSAGE_IGNORE_INSERTS,
1522 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1523 (LPTSTR)&errorText, 0, NULL);
1524 g_snprintf(errmsg, (gulong)errmsgl,
1525 "Error on pipe data during cap_pipe_read: "
1526 " %d: %s", lastError,
1527 errorText ? (char *)errorText : "Unknown");
1529 LocalFree(errorText);
1531 g_snprintf(errmsg, (gulong)errmsgl,
1532 "Error on pipe data during cap_pipe_read: %s.",
1535 pcap_src->cap_pipe_err = PIPERR;
1542 pcap_src->cap_pipe_bytes_read += bytes_read;
1543 #ifdef LOG_CAPTURE_VERBOSE
1544 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_read_data_bytes read %lu of %lu",
1545 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1550 /* Some forward declarations for breaking up cap_pipe_open_live for pcap and pcapng formats */
1551 static void pcap_pipe_open_live(int fd, capture_src *pcap_src,
1552 struct pcap_hdr *hdr,
1553 char *errmsg, size_t errmsgl,
1554 char *secondary_errmsg, size_t secondary_errmsgl);
1555 static void pcapng_pipe_open_live(int fd, capture_src *pcap_src,
1556 char *errmsg, size_t errmsgl);
1557 static int pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src,
1558 char *errmsg, size_t errmsgl);
1560 /* For problems that are probably Not Our Fault. */
1561 static char not_our_bug[] =
1562 "Please report this to the developers of the program writing to the pipe.";
1564 /* Mimic pcap_open_live() for pipe captures
1566 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1567 * open it, and read the header.
1569 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1570 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1572 cap_pipe_open_live(char *pipename,
1573 capture_src *pcap_src,
1575 char *errmsg, size_t errmsgl,
1576 char *secondary_errmsg, size_t secondary_errmsgl)
1579 ws_statb64 pipe_stat;
1580 struct sockaddr_un sa;
1584 char* extcap_pipe_name;
1586 gboolean extcap_pipe = FALSE;
1588 int fd = -1, sel_ret;
1591 pcap_src->cap_pipe_fd = -1;
1593 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1596 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1599 * XXX - this blocks until a pcap per-file header has been written to
1600 * the pipe, so it could block indefinitely.
1602 if (strcmp(pipename, "-") == 0) {
1604 fd = 0; /* read from stdin */
1606 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1608 } else if (!strncmp(pipename, "TCP@", 4)) {
1609 if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1614 if ( g_strrstr(pipename, EXTCAP_PIPE_PREFIX) != NULL )
1617 if (ws_stat64(pipename, &pipe_stat) < 0) {
1618 if (errno == ENOENT || errno == ENOTDIR)
1619 pcap_src->cap_pipe_err = PIPNEXIST;
1621 g_snprintf(errmsg, (gulong)errmsgl,
1622 "The capture session could not be initiated "
1623 "due to error getting information on pipe/socket: %s.", g_strerror(errno));
1624 pcap_src->cap_pipe_err = PIPERR;
1628 if (S_ISFIFO(pipe_stat.st_mode)) {
1629 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1631 g_snprintf(errmsg, (gulong)errmsgl,
1632 "The capture session could not be initiated "
1633 "due to error on pipe open: %s.", g_strerror(errno));
1634 pcap_src->cap_pipe_err = PIPERR;
1637 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1638 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1640 g_snprintf(errmsg, (gulong)errmsgl,
1641 "The capture session could not be initiated "
1642 "due to error on socket create: %s.", g_strerror(errno));
1643 pcap_src->cap_pipe_err = PIPERR;
1646 sa.sun_family = AF_UNIX;
1648 * The Single UNIX Specification says:
1650 * The size of sun_path has intentionally been left undefined.
1651 * This is because different implementations use different sizes.
1652 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1653 * of 104. Since most implementations originate from BSD versions,
1654 * the size is typically in the range 92 to 108.
1656 * Applications should not assume a particular length for sun_path
1657 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1661 * The <sys/un.h> header shall define the sockaddr_un structure,
1662 * which shall include at least the following members:
1664 * sa_family_t sun_family Address family.
1665 * char sun_path[] Socket pathname.
1667 * so we assume that it's an array, with a specified size,
1668 * and that the size reflects the maximum path length.
1670 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1671 /* Path name too long */
1672 g_snprintf(errmsg, (gulong)errmsgl,
1673 "The capture session coud not be initiated "
1674 "due to error on socket connect: Path name too long.");
1675 pcap_src->cap_pipe_err = PIPERR;
1679 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1681 g_snprintf(errmsg, (gulong)errmsgl,
1682 "The capture session coud not be initiated "
1683 "due to error on socket connect: %s.", g_strerror(errno));
1684 pcap_src->cap_pipe_err = PIPERR;
1689 if (S_ISCHR(pipe_stat.st_mode)) {
1691 * Assume the user specified an interface on a system where
1692 * interfaces are in /dev. Pretend we haven't seen it.
1694 pcap_src->cap_pipe_err = PIPNEXIST;
1696 g_snprintf(errmsg, (gulong)errmsgl,
1697 "The capture session could not be initiated because\n"
1698 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1699 pcap_src->cap_pipe_err = PIPERR;
1705 #define PIPE_STR "\\pipe\\"
1706 /* Under Windows, named pipes _must_ have the form
1707 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1709 pncopy = g_strdup(pipename);
1710 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1711 pos = strchr(pncopy + 3, '\\');
1712 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1719 g_snprintf(errmsg, (gulong)errmsgl,
1720 "The capture session could not be initiated because\n"
1721 "\"%s\" is neither an interface nor a pipe.", pipename);
1722 pcap_src->cap_pipe_err = PIPNEXIST;
1725 extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
1726 extcap_pipe = strstr(pipename, extcap_pipe_name) ? TRUE : FALSE;
1727 g_free(extcap_pipe_name);
1729 /* Wait for the pipe to appear */
1732 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1734 pcap_src->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1735 OPEN_EXISTING, 0, NULL);
1737 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE)
1740 if (GetLastError() != ERROR_PIPE_BUSY) {
1741 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1742 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1743 g_snprintf(errmsg, (gulong)errmsgl,
1744 "The capture session on \"%s\" could not be started "
1745 "due to error on pipe open: %s (error %lu).",
1746 pipename, utf_16to8(err_str), GetLastError());
1748 pcap_src->cap_pipe_err = PIPERR;
1752 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1753 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1754 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1755 g_snprintf(errmsg, (gulong)errmsgl,
1756 "The capture session on \"%s\" timed out during "
1757 "pipe open: %s (error %lu).",
1758 pipename, utf_16to8(err_str), GetLastError());
1760 pcap_src->cap_pipe_err = PIPERR;
1767 pcap_src->from_cap_pipe = TRUE;
1770 * We start with a 2KB buffer for packet data, which should be
1771 * large enough for most regular network packets. We increase it,
1772 * up to the maximum size we allow, as necessary.
1774 pcap_src->cap_pipe_databuf = (char*)g_malloc(2048);
1775 pcap_src->cap_pipe_databuf_size = 2048;
1778 if (pcap_src->from_cap_socket)
1781 /* read the pcap header */
1783 while (bytes_read < sizeof magic) {
1784 sel_ret = cap_pipe_select(fd);
1786 g_snprintf(errmsg, (gulong)errmsgl,
1787 "Unexpected error from select: %s.",
1790 } else if (sel_ret > 0) {
1791 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1792 sizeof magic-bytes_read,
1793 pcap_src->from_cap_socket);
1794 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1795 if (extcap_pipe && b <= 0)
1800 g_snprintf(errmsg, (gulong)errmsgl,
1801 "End of file on pipe magic during open.");
1803 g_snprintf(errmsg, (gulong)errmsgl,
1804 "Error on pipe magic during open: %s.",
1814 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
1816 pcap_src->cap_pipe_buf = (char *) &magic;
1817 pcap_src->cap_pipe_bytes_read = 0;
1818 pcap_src->cap_pipe_bytes_to_read = sizeof(magic);
1819 /* We don't have to worry about cap_pipe_read_mtx here */
1820 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1821 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1822 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1823 if (pcap_src->cap_pipe_bytes_read <= 0 && extcap_pipe)
1826 if (pcap_src->cap_pipe_bytes_read <= 0) {
1827 if (pcap_src->cap_pipe_bytes_read == 0)
1828 g_snprintf(errmsg, (gulong)errmsgl,
1829 "End of file on pipe magic during open.");
1831 g_snprintf(errmsg, (gulong)errmsgl,
1832 "Error on pipe magic during open: %s.",
1841 case PCAP_NSEC_MAGIC:
1842 /* Host that wrote it has our byte order, and was running
1843 a program using either standard or ss990417 libpcap. */
1844 pcap_src->cap_pipe_info.pcap.byte_swapped = FALSE;
1845 pcap_src->cap_pipe_modified = FALSE;
1846 pcap_src->ts_nsec = magic == PCAP_NSEC_MAGIC;
1848 case PCAP_MODIFIED_MAGIC:
1849 /* Host that wrote it has our byte order, but was running
1850 a program using either ss990915 or ss991029 libpcap. */
1851 pcap_src->cap_pipe_info.pcap.byte_swapped = FALSE;
1852 pcap_src->cap_pipe_modified = TRUE;
1854 case PCAP_SWAPPED_MAGIC:
1855 case PCAP_SWAPPED_NSEC_MAGIC:
1856 /* Host that wrote it has a byte order opposite to ours,
1857 and was running a program using either standard or
1858 ss990417 libpcap. */
1859 pcap_src->cap_pipe_info.pcap.byte_swapped = TRUE;
1860 pcap_src->cap_pipe_modified = FALSE;
1861 pcap_src->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
1863 case PCAP_SWAPPED_MODIFIED_MAGIC:
1864 /* Host that wrote it out has a byte order opposite to
1865 ours, and was running a program using either ss990915
1866 or ss991029 libpcap. */
1867 pcap_src->cap_pipe_info.pcap.byte_swapped = TRUE;
1868 pcap_src->cap_pipe_modified = TRUE;
1870 case BLOCK_TYPE_SHB:
1871 /* This isn't pcap, it's pcapng. */
1872 pcap_src->from_pcapng = TRUE;
1873 pcap_src->cap_pipe_dispatch = pcapng_pipe_dispatch;
1874 pcap_src->cap_pipe_info.pcapng.src_iface_to_global = g_array_new(FALSE, FALSE, sizeof(guint32));
1875 global_capture_opts.use_pcapng = TRUE; /* we can only output in pcapng format */
1876 pcapng_pipe_open_live(fd, pcap_src, errmsg, errmsgl);
1879 /* Not a pcap type we know about, or not pcap at all. */
1880 g_snprintf(errmsg, (gulong)errmsgl,
1881 "Data written to the pipe is neither in a supported pcap format nor in pcapng format.");
1882 g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl, "%s",
1887 pcap_pipe_open_live(fd, pcap_src, (struct pcap_hdr *) hdr, errmsg, errmsgl,
1888 secondary_errmsg, secondary_errmsgl);
1892 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1893 pcap_src->cap_pipe_err = PIPERR;
1894 cap_pipe_close(fd, pcap_src->from_cap_socket);
1895 pcap_src->cap_pipe_fd = -1;
1897 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1902 pcap_pipe_open_live(int fd,
1903 capture_src *pcap_src,
1904 struct pcap_hdr *hdr,
1905 char *errmsg, size_t errmsgl,
1906 char *secondary_errmsg, size_t secondary_errmsgl)
1912 if (pcap_src->from_cap_socket)
1915 /* Read the rest of the header */
1917 while (bytes_read < sizeof(struct pcap_hdr)) {
1918 sel_ret = cap_pipe_select(fd);
1920 g_snprintf(errmsg, (gulong)errmsgl,
1921 "Unexpected error from select: %s.",
1924 } else if (sel_ret > 0) {
1925 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
1926 sizeof(struct pcap_hdr) - bytes_read,
1927 pcap_src->from_cap_socket);
1930 g_snprintf(errmsg, (gulong)errmsgl,
1931 "End of file on pipe header during open.");
1933 g_snprintf(errmsg, (gulong)errmsgl,
1934 "Error on pipe header during open: %s.",
1936 g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl,
1946 pcap_src->cap_pipe_buf = (char *) hdr;
1947 pcap_src->cap_pipe_bytes_read = 0;
1948 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1949 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1950 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1951 if (pcap_src->cap_pipe_bytes_read <= 0) {
1952 if (pcap_src->cap_pipe_bytes_read == 0)
1953 g_snprintf(errmsg, (gulong)errmsgl,
1954 "End of file on pipe header during open.");
1956 g_snprintf(errmsg, (gulong)errmsgl,
1957 "Error on pipe header header during open: %s.",
1959 g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl, "%s",
1966 if (pcap_src->cap_pipe_info.pcap.byte_swapped) {
1967 /* Byte-swap the header fields about which we care. */
1968 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
1969 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
1970 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
1971 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
1973 pcap_src->linktype = hdr->network;
1975 if (pcap_src->linktype == DLT_DBUS) {
1977 * The maximum D-Bus message size is 128MB, so allow packets up
1980 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_DBUS;
1983 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
1985 if (hdr->version_major < 2) {
1986 g_snprintf(errmsg, (gulong)errmsgl,
1987 "The old pcap format version %d.%d is not supported.",
1988 hdr->version_major, hdr->version_minor);
1989 g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl, "%s",
1994 pcap_src->cap_pipe_fd = fd;
1998 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcap_pipe_open_live: error %s", errmsg);
1999 pcap_src->cap_pipe_err = PIPERR;
2000 cap_pipe_close(fd, pcap_src->from_cap_socket);
2001 pcap_src->cap_pipe_fd = -1;
2003 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2007 /* Read the pcapng section header block */
2009 pcapng_read_shb(capture_src *pcap_src,
2013 struct pcapng_section_header_block_s shb;
2016 if (pcap_src->from_cap_socket)
2019 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s) + sizeof(struct pcapng_section_header_block_s);
2020 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2026 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + sizeof(struct pcapng_block_header_s);
2027 pcap_src->cap_pipe_bytes_read = 0;
2028 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_section_header_block_s);
2029 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2030 g_async_queue_pop(pcap_src->cap_pipe_done_q);
2031 if (pcap_src->cap_pipe_bytes_read <= 0) {
2032 if (pcap_src->cap_pipe_bytes_read == 0)
2033 g_snprintf(errmsg, (gulong)errmsgl,
2034 "End of file on pipe section header during open.");
2036 g_snprintf(errmsg, (gulong)errmsgl,
2037 "Error on pipe section header during open: %s.",
2041 /* Continuing with STATE_EXPECT_DATA requires reading into cap_pipe_databuf at offset cap_pipe_bytes_read */
2042 pcap_src->cap_pipe_bytes_read = sizeof(struct pcapng_block_header_s) + sizeof(struct pcapng_section_header_block_s);
2045 memcpy(&shb, pcap_src->cap_pipe_databuf + sizeof(struct pcapng_block_header_s), sizeof(struct pcapng_section_header_block_s));
2049 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng SHB MAGIC");
2051 case PCAPNG_SWAPPED_MAGIC:
2052 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng SHB SWAPPED MAGIC");
2054 * pcapng sources can contain all sorts of block types. Rather than add a bunch of
2055 * complexity to this code (which is often privileged), punt and tell the user to
2056 * swap bytes elsewhere.
2058 #if G_BYTE_ORDER == G_BIG_ENDIAN
2059 #define OUR_ENDIAN "big"
2060 #define IFACE_ENDIAN "little"
2062 #define OUR_ENDIAN "little"
2063 #define IFACE_ENDIAN "big"
2065 g_snprintf(errmsg, (gulong)errmsgl,
2066 "Interface %u is " IFACE_ENDIAN " endian but we're " OUR_ENDIAN " endian.",
2067 pcap_src->interface_id);
2070 /* Not a pcapng type we know about, or not pcapng at all. */
2071 g_snprintf(errmsg, (gulong)errmsgl,
2072 "Unrecognized pcapng format or not pcapng data.");
2076 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
2078 /* Setup state to capture any options following the section header block */
2079 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2085 * Save IDB blocks for playback whenever we change output files.
2086 * Rewrite EPB and ISB interface IDs.
2089 pcapng_adjust_block(capture_src *pcap_src, const struct pcapng_block_header_s *bh, u_char *pd)
2091 switch(bh->block_type) {
2092 case BLOCK_TYPE_SHB:
2094 if (global_ld.pcapng_passthrough) {
2096 * We have a single pcapng input. We pass the SHB through when
2097 * writing a single output file and for the first ring buffer
2098 * file. We need to save it for the second and subsequent ring
2101 g_free(global_ld.saved_shb);
2102 global_ld.saved_shb = (guint8 *) g_memdup(pd, bh->block_total_length);
2105 * We're dealing with one section at a time, so we can (and must)
2106 * get rid of our old IDBs.
2108 for (unsigned i = 0; i < global_ld.saved_idbs->len; i++) {
2109 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, i);
2110 g_free(idb_source->idb);
2112 g_array_set_size(global_ld.saved_idbs, 0);
2115 * We have a new SHB from this capture source. We need to keep
2116 * global_ld.saved_idbs intact, so we mark IDBs we previously
2117 * collected from this source as deleted.
2119 for (unsigned i = 0; i < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len; i++) {
2120 guint32 iface_id = g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, guint32, i);
2121 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, iface_id);
2122 g_assert(idb_source->interface_id == pcap_src->interface_id);
2123 g_free(idb_source->idb);
2124 memset(idb_source, 0, sizeof(saved_idb_t));
2125 idb_source->deleted = TRUE;
2126 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: deleted pcapng IDB %u", G_STRFUNC, iface_id);
2129 g_array_set_size(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, 0);
2132 case BLOCK_TYPE_IDB:
2135 * Always gather IDBs. We can remove them or mark them as deleted
2136 * when we get a new SHB.
2138 saved_idb_t idb_source = { 0 };
2139 idb_source.interface_id = pcap_src->interface_id;
2140 idb_source.idb_len = bh->block_total_length;
2141 idb_source.idb = (guint8 *) g_memdup(pd, idb_source.idb_len);
2142 g_array_append_val(global_ld.saved_idbs, idb_source);
2143 guint32 iface_id = global_ld.saved_idbs->len - 1;
2144 g_array_append_val(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, iface_id);
2145 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: mapped pcapng IDB %u -> %u from source %u",
2146 G_STRFUNC, pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len - 1, iface_id, pcap_src->interface_id);
2149 case BLOCK_TYPE_EPB:
2150 case BLOCK_TYPE_ISB:
2152 if (global_ld.pcapng_passthrough) {
2153 /* Our input and output interface IDs are the same. */
2156 /* The interface ID is the first 32-bit field after the BH for both EPBs and ISBs. */
2158 memcpy(&iface_id, pd + sizeof(struct pcapng_block_header_s), 4);
2159 if (iface_id < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len) {
2160 memcpy(pd + sizeof(struct pcapng_block_header_s),
2161 &g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, guint32, iface_id), 4);
2163 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: pcapng EPB or ISB interface id %u > max %u", G_STRFUNC, iface_id, pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len);
2176 pcapng_pipe_open_live(int fd,
2177 capture_src *pcap_src,
2181 guint32 type = BLOCK_TYPE_SHB;
2182 struct pcapng_block_header_s *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2184 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_open_live: fd %d", fd);
2186 if (pcap_src->from_cap_socket)
2189 memcpy(pcap_src->cap_pipe_databuf, &type, sizeof(guint32));
2190 /* read the rest of the pcapng general block header */
2191 pcap_src->cap_pipe_bytes_read = sizeof(guint32);
2192 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s);
2193 pcap_src->cap_pipe_fd = fd;
2194 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2197 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(struct pcapng_block_header_s));
2201 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
2203 bh->block_type = type;
2204 pcap_src->cap_pipe_buf = (char *) &bh->block_total_length;
2205 pcap_src->cap_pipe_bytes_read = 0;
2206 pcap_src->cap_pipe_bytes_to_read = sizeof(bh->block_total_length);
2207 /* We don't have to worry about cap_pipe_read_mtx here */
2208 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2209 g_async_queue_pop(pcap_src->cap_pipe_done_q);
2210 if (pcap_src->cap_pipe_bytes_read <= 0) {
2211 if (pcap_src->cap_pipe_bytes_read == 0)
2212 g_snprintf(errmsg, (gulong)errmsgl,
2213 "End of file on pipe block_total_length during open.");
2215 g_snprintf(errmsg, (gulong)errmsgl,
2216 "Error on pipe block_total_length during open: %s.",
2220 pcap_src->cap_pipe_bytes_read = sizeof(struct pcapng_block_header_s);
2221 memcpy(pcap_src->cap_pipe_databuf, bh, sizeof(struct pcapng_block_header_s));
2222 pcap_src->cap_pipe_fd = fd;
2225 if (pcapng_read_shb(pcap_src, errmsg, errmsgl)) {
2232 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_open_live: error %s", errmsg);
2233 pcap_src->cap_pipe_err = PIPERR;
2234 cap_pipe_close(fd, pcap_src->from_cap_socket);
2235 pcap_src->cap_pipe_fd = -1;
2237 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2241 /* We read one record from the pipe, take care of byte order in the record
2242 * header, write the record to the capture file, and update capture statistics. */
2244 pcap_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2246 struct pcap_pkthdr phdr;
2247 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2255 pcap_pipe_info_t *pcap_info = &pcap_src->cap_pipe_info.pcap;
2257 #ifdef LOG_CAPTURE_VERBOSE
2258 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcap_pipe_dispatch");
2261 switch (pcap_src->cap_pipe_state) {
2263 case STATE_EXPECT_REC_HDR:
2265 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2268 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2269 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_modified ?
2270 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2271 pcap_src->cap_pipe_bytes_read = 0;
2274 pcap_src->cap_pipe_buf = (char *) &pcap_info->rechdr;
2275 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2276 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2281 case STATE_READ_REC_HDR:
2283 if (pcap_src->from_cap_socket)
2286 b = cap_pipe_read(pcap_src->cap_pipe_fd, ((char *)&pcap_info->rechdr)+pcap_src->cap_pipe_bytes_read,
2287 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read, pcap_src->from_cap_socket);
2290 result = PD_PIPE_EOF;
2292 result = PD_PIPE_ERR;
2295 pcap_src->cap_pipe_bytes_read += b;
2299 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2300 if (pcap_src->cap_pipe_err == PIPEOF) {
2301 result = PD_PIPE_EOF;
2303 } else if (pcap_src->cap_pipe_err == PIPERR) {
2304 result = PD_PIPE_ERR;
2312 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2314 result = PD_REC_HDR_READ;
2317 case STATE_EXPECT_DATA:
2319 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2322 pcap_src->cap_pipe_state = STATE_READ_DATA;
2323 pcap_src->cap_pipe_bytes_to_read = pcap_info->rechdr.hdr.incl_len;
2324 pcap_src->cap_pipe_bytes_read = 0;
2327 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2328 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2329 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2334 case STATE_READ_DATA:
2336 if (pcap_src->from_cap_socket)
2339 b = cap_pipe_read(pcap_src->cap_pipe_fd,
2340 pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read,
2341 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read,
2342 pcap_src->from_cap_socket);
2345 result = PD_PIPE_EOF;
2347 result = PD_PIPE_ERR;
2350 pcap_src->cap_pipe_bytes_read += b;
2355 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2356 if (pcap_src->cap_pipe_err == PIPEOF) {
2357 result = PD_PIPE_EOF;
2359 } else if (pcap_src->cap_pipe_err == PIPERR) {
2360 result = PD_PIPE_ERR;
2368 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2370 result = PD_DATA_READ;
2374 g_snprintf(errmsg, (gulong)errmsgl,
2375 "pcap_pipe_dispatch: invalid state");
2378 } /* switch (pcap_src->cap_pipe_state) */
2381 * We've now read as much data as we were expecting, so process it.
2385 case PD_REC_HDR_READ:
2386 /* We've read the header. Take care of byte order. */
2387 cap_pipe_adjust_pcap_header(pcap_src->cap_pipe_info.pcap.byte_swapped, &pcap_info->hdr,
2388 &pcap_info->rechdr.hdr);
2389 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_max_pkt_size) {
2391 * The record contains more data than the advertised/allowed in the
2392 * pcap header, do not try to read more data (do not change to
2393 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2394 * instead stop with an error.
2396 g_snprintf(errmsg, (gulong)errmsgl, "Frame %u too long (%d bytes)",
2397 ld->packets_captured+1, pcap_info->rechdr.hdr.incl_len);
2401 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_databuf_size) {
2403 * Grow the buffer to the packet size, rounded up to a power of
2406 new_bufsize = pcap_info->rechdr.hdr.incl_len;
2408 * http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2411 new_bufsize |= new_bufsize >> 1;
2412 new_bufsize |= new_bufsize >> 2;
2413 new_bufsize |= new_bufsize >> 4;
2414 new_bufsize |= new_bufsize >> 8;
2415 new_bufsize |= new_bufsize >> 16;
2417 pcap_src->cap_pipe_databuf = (char*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2418 pcap_src->cap_pipe_databuf_size = new_bufsize;
2422 * The record has some data following the header, try to read it next
2425 if (pcap_info->rechdr.hdr.incl_len) {
2426 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2431 * No data following the record header? Then no more data needs to be
2432 * read and we will fallthrough and emit an empty packet.
2436 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2437 phdr.ts.tv_sec = pcap_info->rechdr.hdr.ts_sec;
2438 phdr.ts.tv_usec = pcap_info->rechdr.hdr.ts_usec;
2439 phdr.caplen = pcap_info->rechdr.hdr.incl_len;
2440 phdr.len = pcap_info->rechdr.hdr.orig_len;
2443 capture_loop_queue_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2445 capture_loop_write_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2447 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2451 pcap_src->cap_pipe_err = PIPEOF;
2456 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2457 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2458 g_snprintf(errmsg, (gulong)errmsgl,
2459 "Error reading from pipe: %s (error %lu)",
2460 utf_16to8(err_str), GetLastError());
2463 g_snprintf(errmsg, (gulong)errmsgl, "Error reading from pipe: %s",
2471 pcap_src->cap_pipe_err = PIPERR;
2472 /* Return here rather than inside the switch to prevent GCC warning */
2477 pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2479 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2486 struct pcapng_block_header_s *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2488 #ifdef LOG_CAPTURE_VERBOSE
2489 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch");
2492 switch (pcap_src->cap_pipe_state) {
2494 case STATE_EXPECT_REC_HDR:
2495 #ifdef LOG_CAPTURE_VERBOSE
2496 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_EXPECT_REC_HDR");
2499 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2502 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2503 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s);
2504 pcap_src->cap_pipe_bytes_read = 0;
2507 if (!pcap_src->from_cap_socket) {
2508 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2509 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2511 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2516 case STATE_READ_REC_HDR:
2517 #ifdef LOG_CAPTURE_VERBOSE
2518 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_READ_REC_HDR");
2521 if (pcap_src->from_cap_socket) {
2523 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2528 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2529 if (pcap_src->cap_pipe_err == PIPEOF) {
2530 result = PD_PIPE_EOF;
2532 } else if (pcap_src->cap_pipe_err == PIPERR) {
2533 result = PD_PIPE_ERR;
2541 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2544 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(struct pcapng_block_header_s));
2545 result = PD_REC_HDR_READ;
2548 case STATE_EXPECT_DATA:
2549 #ifdef LOG_CAPTURE_VERBOSE
2550 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_EXPECT_DATA");
2553 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2555 pcap_src->cap_pipe_state = STATE_READ_DATA;
2556 pcap_src->cap_pipe_bytes_to_read = bh->block_total_length;
2559 if (!pcap_src->from_cap_socket) {
2560 pcap_src->cap_pipe_bytes_to_read -= pcap_src->cap_pipe_bytes_read;
2561 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + pcap_src->cap_pipe_bytes_read;
2562 pcap_src->cap_pipe_bytes_read = 0;
2563 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2565 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2570 case STATE_READ_DATA:
2571 #ifdef LOG_CAPTURE_VERBOSE
2572 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_READ_DATA");
2575 if (pcap_src->from_cap_socket) {
2577 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2583 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2584 if (pcap_src->cap_pipe_err == PIPEOF) {
2585 result = PD_PIPE_EOF;
2587 } else if (pcap_src->cap_pipe_err == PIPERR) {
2588 result = PD_PIPE_ERR;
2596 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2599 result = PD_DATA_READ;
2603 g_snprintf(errmsg, (gulong)errmsgl,
2604 "pcapng_pipe_dispatch: invalid state");
2607 } /* switch (pcap_src->cap_pipe_state) */
2610 * We've now read as much data as we were expecting, so process it.
2614 case PD_REC_HDR_READ:
2615 if (bh->block_type == BLOCK_TYPE_SHB) {
2616 /* we need to read ahead to get the endianess before getting the block type and length */
2617 pcapng_read_shb(pcap_src, errmsg, errmsgl);
2621 if (bh->block_total_length > pcap_src->cap_pipe_max_pkt_size) {
2623 * The record contains more data than the advertised/allowed in the
2624 * pcapng header, do not try to read more data (do not change to
2625 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2626 * instead stop with an error.
2628 g_snprintf(errmsg, (gulong)errmsgl, "Frame %u too long (%d bytes)",
2629 ld->packets_captured+1, bh->block_total_length);
2633 if (bh->block_total_length > pcap_src->cap_pipe_databuf_size) {
2635 * Grow the buffer to the packet size, rounded up to a power of
2638 new_bufsize = bh->block_total_length;
2640 * http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2643 new_bufsize |= new_bufsize >> 1;
2644 new_bufsize |= new_bufsize >> 2;
2645 new_bufsize |= new_bufsize >> 4;
2646 new_bufsize |= new_bufsize >> 8;
2647 new_bufsize |= new_bufsize >> 16;
2649 pcap_src->cap_pipe_databuf = (guchar*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2650 pcap_src->cap_pipe_databuf_size = new_bufsize;
2653 /* The record always has at least the block total length following the header */
2654 if (bh->block_total_length < sizeof(struct pcapng_block_header_s)+sizeof(guint32)) {
2655 g_snprintf(errmsg, (gulong)errmsgl,
2656 "malformed pcapng block_total_length < minimum");
2657 pcap_src->cap_pipe_err = PIPEOF;
2660 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2665 capture_loop_queue_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
2667 capture_loop_write_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
2669 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2673 pcap_src->cap_pipe_err = PIPEOF;
2678 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2679 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2680 g_snprintf(errmsg, (gulong)errmsgl,
2681 "Error reading from pipe: %s (error %lu)",
2682 utf_16to8(err_str), GetLastError());
2685 g_snprintf(errmsg, (gulong)errmsgl, "Error reading from pipe: %s",
2693 pcap_src->cap_pipe_err = PIPERR;
2694 /* Return here rather than inside the switch to prevent GCC warning */
2698 /** Open the capture input file (pcap or capture pipe).
2699 * Returns TRUE if it succeeds, FALSE otherwise. */
2701 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2702 char *errmsg, size_t errmsg_len,
2703 char *secondary_errmsg, size_t secondary_errmsg_len)
2705 cap_device_open_err open_err;
2706 gchar open_err_str[PCAP_ERRBUF_SIZE];
2707 gchar *sync_msg_str;
2708 interface_options *interface_opts;
2709 capture_src *pcap_src;
2713 WORD wVersionRequested;
2717 /* XXX - opening Winsock on tshark? */
2719 /* Initialize Windows Socket if we are in a Win32 OS
2720 This needs to be done before querying the interface for network/netmask */
2722 /* XXX - do we really require 1.1 or earlier?
2723 Are there any versions that support only 2.0 or higher? */
2724 wVersionRequested = MAKEWORD(1, 1);
2725 err = WSAStartup(wVersionRequested, &wsaData);
2729 case WSASYSNOTREADY:
2730 g_snprintf(errmsg, (gulong) errmsg_len,
2731 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2734 case WSAVERNOTSUPPORTED:
2735 g_snprintf(errmsg, (gulong) errmsg_len,
2736 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2737 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2740 case WSAEINPROGRESS:
2741 g_snprintf(errmsg, (gulong) errmsg_len,
2742 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2746 g_snprintf(errmsg, (gulong) errmsg_len,
2747 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2751 g_snprintf(errmsg, (gulong) errmsg_len,
2752 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2756 g_snprintf(errmsg, (gulong) errmsg_len,
2757 "Couldn't initialize Windows Sockets: error %d", err);
2760 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2764 if ((use_threads == FALSE) &&
2765 (capture_opts->ifaces->len > 1)) {
2766 g_snprintf(errmsg, (gulong) errmsg_len,
2767 "Using threads is required for capturing on multiple interfaces.");
2771 int pcapng_src_count = 0;
2772 for (i = 0; i < capture_opts->ifaces->len; i++) {
2773 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
2774 pcap_src = (capture_src *)g_malloc0(sizeof (capture_src));
2775 if (pcap_src == NULL) {
2776 g_snprintf(errmsg, (gulong) errmsg_len,
2777 "Could not allocate memory.");
2782 * Add our pcapng interface entry. This will be deleted further
2783 * down if pcapng_passthrough == TRUE.
2785 saved_idb_t idb_source = { 0 };
2786 idb_source.interface_id = i;
2787 g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
2788 g_array_append_val(global_ld.saved_idbs, idb_source);
2789 g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
2790 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: saved capture_opts IDB %u",
2793 #ifdef MUST_DO_SELECT
2794 pcap_src->pcap_fd = -1;
2796 pcap_src->interface_id = i;
2797 pcap_src->linktype = -1;
2799 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2801 pcap_src->cap_pipe_fd = -1;
2802 pcap_src->cap_pipe_dispatch = pcap_pipe_dispatch;
2803 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2804 pcap_src->cap_pipe_err = PIPOK;
2806 pcap_src->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2807 g_mutex_init(pcap_src->cap_pipe_read_mtx);
2808 pcap_src->cap_pipe_pending_q = g_async_queue_new();
2809 pcap_src->cap_pipe_done_q = g_async_queue_new();
2811 g_array_append_val(ld->pcaps, pcap_src);
2813 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts->name);
2814 pcap_src->pcap_h = open_capture_device(capture_opts, interface_opts,
2815 CAP_READ_TIMEOUT, &open_err, &open_err_str);
2817 if (pcap_src->pcap_h != NULL) {
2818 /* we've opened "iface" as a network device */
2820 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2821 /* Find out if we're getting nanosecond-precision time stamps */
2822 pcap_src->ts_nsec = have_high_resolution_timestamp(pcap_src->pcap_h);
2825 #if defined(HAVE_PCAP_SETSAMPLING)
2826 if (interface_opts->sampling_method != CAPTURE_SAMP_NONE) {
2827 struct pcap_samp *samp;
2829 if ((samp = pcap_setsampling(pcap_src->pcap_h)) != NULL) {
2830 switch (interface_opts->sampling_method) {
2831 case CAPTURE_SAMP_BY_COUNT:
2832 samp->method = PCAP_SAMP_1_EVERY_N;
2835 case CAPTURE_SAMP_BY_TIMER:
2836 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2840 sync_msg_str = g_strdup_printf(
2841 "Unknown sampling method %d specified,\n"
2842 "continue without packet sampling",
2843 interface_opts->sampling_method);
2844 report_capture_error("Couldn't set the capture "
2845 "sampling", sync_msg_str);
2846 g_free(sync_msg_str);
2848 samp->value = interface_opts->sampling_param;
2850 report_capture_error("Couldn't set the capture sampling",
2851 "Cannot get packet sampling data structure");
2856 /* setting the data link type only works on real interfaces */
2857 if (!set_pcap_datalink(pcap_src->pcap_h, interface_opts->linktype,
2858 interface_opts->name,
2860 secondary_errmsg, secondary_errmsg_len)) {
2863 pcap_src->linktype = get_pcap_datalink(pcap_src->pcap_h, interface_opts->name);
2865 /* We couldn't open "iface" as a network device. */
2866 /* Try to open it as a pipe */
2867 gboolean pipe_err = FALSE;
2868 cap_pipe_open_live(interface_opts->name, pcap_src,
2869 &pcap_src->cap_pipe_info.pcap.hdr,
2871 secondary_errmsg, secondary_errmsg_len);
2874 if (pcap_src->from_cap_socket) {
2876 if (pcap_src->cap_pipe_fd == -1) {
2881 if (pcap_src->cap_pipe_h == INVALID_HANDLE_VALUE) {
2888 if (pcap_src->cap_pipe_err == PIPNEXIST) {
2890 * We tried opening as an interface, and that failed,
2891 * so we tried to open it as a pipe, but the pipe
2892 * doesn't exist. Report the error message for
2895 get_capture_device_open_failure_messages(open_err,
2897 interface_opts->name,
2901 secondary_errmsg_len);
2904 * Else pipe (or file) does exist and cap_pipe_open_live() has
2909 /* cap_pipe_open_live() succeeded; don't want
2910 error message from pcap_open_live() */
2911 open_err_str[0] = '\0';
2915 /* XXX - will this work for tshark? */
2916 #ifdef MUST_DO_SELECT
2917 if (!pcap_src->from_cap_pipe) {
2918 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2919 pcap_src->pcap_fd = pcap_get_selectable_fd(pcap_src->pcap_h);
2921 pcap_src->pcap_fd = pcap_fileno(pcap_src->pcap_h);
2926 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2927 returned a warning; print it, but keep capturing. */
2928 if (open_err_str[0] != '\0') {
2929 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2930 report_capture_error(sync_msg_str, "");
2931 g_free(sync_msg_str);
2933 if (pcap_src->from_pcapng) {
2937 if (capture_opts->ifaces->len == 1 && pcapng_src_count == 1) {
2938 ld->pcapng_passthrough = TRUE;
2939 g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
2940 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: Clearing %u interfaces for passthrough",
2941 G_STRFUNC, global_ld.saved_idbs->len);
2942 g_array_set_size(global_ld.saved_idbs, 0);
2943 g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
2946 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2947 /* to remove any suid privileges. */
2948 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2949 /* (euid/egid have already previously been set to ruid/rgid. */
2950 /* (See comment in main() for details) */
2952 relinquish_special_privs_perm();
2954 relinquish_all_capabilities();
2959 /* close the capture input file (pcap or capture pipe) */
2960 static void capture_loop_close_input(loop_data *ld)
2963 capture_src *pcap_src;
2965 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2967 for (i = 0; i < ld->pcaps->len; i++) {
2968 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2969 /* Pipe, or capture device? */
2970 if (pcap_src->from_cap_pipe) {
2971 /* Pipe. If open, close the capture pipe "input file". */
2972 if (pcap_src->cap_pipe_fd >= 0) {
2973 cap_pipe_close(pcap_src->cap_pipe_fd, pcap_src->from_cap_socket);
2974 pcap_src->cap_pipe_fd = -1;
2977 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE) {
2978 CloseHandle(pcap_src->cap_pipe_h);
2979 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2982 if (pcap_src->cap_pipe_databuf != NULL) {
2983 /* Free the buffer. */
2984 g_free(pcap_src->cap_pipe_databuf);
2985 pcap_src->cap_pipe_databuf = NULL;
2987 if (pcap_src->from_pcapng) {
2988 g_array_free(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, TRUE);
2989 pcap_src->cap_pipe_info.pcapng.src_iface_to_global = NULL;
2992 /* Capture device. If open, close the pcap_t. */
2993 if (pcap_src->pcap_h != NULL) {
2994 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_src->pcap_h);
2995 pcap_close(pcap_src->pcap_h);
2996 pcap_src->pcap_h = NULL;
3004 /* Shut down windows sockets */
3010 /* init the capture filter */
3011 static initfilter_status_t
3012 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
3013 const gchar * name, const gchar * cfilter)
3015 struct bpf_program fcode;
3017 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
3019 /* capture filters only work on real interfaces */
3020 if (cfilter && !from_cap_pipe) {
3021 /* A capture filter was specified; set it up. */
3022 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
3023 /* Treat this specially - our caller might try to compile this
3024 as a display filter and, if that succeeds, warn the user that
3025 the display and capture filter syntaxes are different. */
3026 return INITFILTER_BAD_FILTER;
3028 if (pcap_setfilter(pcap_h, &fcode) < 0) {
3029 #ifdef HAVE_PCAP_FREECODE
3030 pcap_freecode(&fcode);
3032 return INITFILTER_OTHER_ERROR;
3034 #ifdef HAVE_PCAP_FREECODE
3035 pcap_freecode(&fcode);
3039 return INITFILTER_NO_ERROR;
3043 * Write the dumpcap pcapng SHB and IDBs if needed.
3044 * Called from capture_loop_init_output and do_file_switch_or_stop.
3047 capture_loop_init_pcapng_output(capture_options *capture_opts, loop_data *ld)
3049 g_rw_lock_reader_lock (&ld->saved_shb_idb_lock);
3051 if (ld->pcapng_passthrough && !ld->saved_shb) {
3052 /* We have a single pcapng capture interface and this is the first or only output file. */
3053 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: skipping dumpcap SHB and IDBs in favor of source", G_STRFUNC);
3054 g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3058 gboolean successful = TRUE;
3060 GString *os_info_str = g_string_new("");
3062 get_os_version_info(os_info_str);
3064 if (ld->saved_shb) {
3065 /* We have a single pcapng capture interface and multiple output files. */
3067 struct pcapng_block_header_s bh;
3069 memcpy(&bh, ld->saved_shb, sizeof(struct pcapng_block_header_s));
3071 successful = pcapng_write_block(ld->pdh, ld->saved_shb, bh.block_total_length, &ld->bytes_written, &err);
3073 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: wrote saved passthrough SHB %d", G_STRFUNC, successful);
3075 GString *cpu_info_str = g_string_new("");
3076 get_cpu_info(cpu_info_str);
3078 successful = pcapng_write_section_header_block(ld->pdh,
3079 (const char *)capture_opts->capture_comment, /* Comment */
3080 cpu_info_str->str, /* HW */
3081 os_info_str->str, /* OS */
3082 get_appname_and_version(),
3083 -1, /* section_length */
3086 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: wrote dumpcap SHB %d", G_STRFUNC, successful);
3087 g_string_free(cpu_info_str, TRUE);
3090 for (unsigned i = 0; successful && (i < ld->saved_idbs->len); i++) {
3091 saved_idb_t idb_source = g_array_index(ld->saved_idbs, saved_idb_t, i);
3092 if (idb_source.deleted) {
3094 * Our interface is out of scope. Suppose we're writing multiple
3095 * files and a source switches sections. We currently write dummy
3098 * File 1: IDB0, IDB1, IDB2
3099 * [ The source of IDBs 1 and 2 writes an SHB with two new IDBs ]
3100 * [ We switch output files ]
3101 * File 2: IDB0, dummy IDB, dummy IDB, IDB3, IDB4
3103 * It might make more sense to write the original data so that
3104 * so that our IDB lists are more consistent across files.
3106 successful = pcapng_write_interface_description_block(global_ld.pdh,
3107 "Interface went out of scope", /* OPT_COMMENT 1 */
3108 "dummy", /* IDB_NAME 2 */
3109 "Dumpcap dummy interface", /* IDB_DESCRIPTION 3 */
3110 NULL, /* IDB_FILTER 11 */
3111 os_info_str->str, /* IDB_OS 12 */
3114 &(global_ld.bytes_written),
3115 0, /* IDB_IF_SPEED 8 */
3116 6, /* IDB_TSRESOL 9 */
3118 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: skipping deleted pcapng IDB %u", G_STRFUNC, i);
3119 } else if (idb_source.idb && idb_source.idb_len) {
3120 successful = pcapng_write_block(global_ld.pdh, idb_source.idb, idb_source.idb_len, &ld->bytes_written, &err);
3121 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: wrote pcapng IDB %d", G_STRFUNC, successful);
3122 } else if (idb_source.interface_id < capture_opts->ifaces->len) {
3123 unsigned if_id = idb_source.interface_id;
3124 interface_options *interface_opts = &g_array_index(capture_opts->ifaces, interface_options, if_id);
3125 capture_src *pcap_src = g_array_index(ld->pcaps, capture_src *, if_id);
3126 if (pcap_src->from_cap_pipe) {
3127 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3129 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3131 successful = pcapng_write_interface_description_block(global_ld.pdh,
3132 NULL, /* OPT_COMMENT 1 */
3133 interface_opts->name, /* IDB_NAME 2 */
3134 interface_opts->descr, /* IDB_DESCRIPTION 3 */
3135 interface_opts->cfilter, /* IDB_FILTER 11 */
3136 os_info_str->str, /* IDB_OS 12 */
3139 &(global_ld.bytes_written),
3140 0, /* IDB_IF_SPEED 8 */
3141 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3143 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: wrote capture_opts IDB %d: %d", G_STRFUNC, if_id, successful);
3146 g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3148 g_string_free(os_info_str, TRUE);
3153 /* set up to write to the already-opened capture output file/files */
3155 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
3158 gboolean successful;
3160 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
3162 if ((capture_opts->use_pcapng == FALSE) &&
3163 (capture_opts->ifaces->len > 1)) {
3164 g_snprintf(errmsg, errmsg_len,
3165 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
3169 /* Set up to write to the capture file. */
3170 if (capture_opts->multi_files_on) {
3171 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
3173 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
3174 if (ld->pdh == NULL) {
3179 if (capture_opts->use_pcapng) {
3180 successful = capture_loop_init_pcapng_output(capture_opts, ld);
3182 capture_src *pcap_src;
3183 pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
3184 if (pcap_src->from_cap_pipe) {
3185 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3187 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3189 successful = libpcap_write_file_header(ld->pdh, pcap_src->linktype, pcap_src->snaplen,
3190 pcap_src->ts_nsec, &ld->bytes_written, &err);
3198 if (ld->pdh == NULL) {
3199 /* We couldn't set up to write to the capture file. */
3200 /* XXX - use cf_open_error_message from tshark instead? */
3205 g_snprintf(errmsg, errmsg_len,
3206 "The file to which the capture would be"
3207 " saved (\"%s\") could not be opened: Error %d.",
3208 capture_opts->save_file, err);
3210 g_snprintf(errmsg, errmsg_len,
3211 "The file to which the capture would be"
3212 " saved (\"%s\") could not be opened: %s.",
3213 capture_opts->save_file, g_strerror(err));
3225 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
3229 capture_src *pcap_src;
3230 guint64 end_time = create_timestamp();
3232 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
3234 if (capture_opts->multi_files_on) {
3235 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
3237 if (capture_opts->use_pcapng) {
3238 for (i = 0; i < global_ld.pcaps->len; i++) {
3239 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3240 if (!pcap_src->from_cap_pipe) {
3241 guint64 isb_ifrecv, isb_ifdrop;
3242 struct pcap_stat stats;
3244 if (pcap_stats(pcap_src->pcap_h, &stats) >= 0) {
3245 isb_ifrecv = pcap_src->received;
3246 isb_ifdrop = stats.ps_drop + pcap_src->dropped + pcap_src->flushed;
3248 isb_ifrecv = G_MAXUINT64;
3249 isb_ifdrop = G_MAXUINT64;
3251 pcapng_write_interface_statistics_block(ld->pdh,
3254 "Counters provided by dumpcap",
3263 if (fclose(ld->pdh) == EOF) {
3264 if (err_close != NULL) {
3274 /* dispatch incoming packets (pcap or capture pipe)
3276 * Waits for incoming packets to be available, and calls pcap_dispatch()
3277 * to cause them to be processed.
3279 * Returns the number of packets which were processed.
3281 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3282 * packet-batching behaviour does not cause packets to get held back
3286 capture_loop_dispatch(loop_data *ld,
3287 char *errmsg, int errmsg_len, capture_src *pcap_src)
3290 gint packet_count_before;
3293 packet_count_before = ld->packets_captured;
3294 if (pcap_src->from_cap_pipe) {
3295 /* dispatch from capture pipe */
3296 #ifdef LOG_CAPTURE_VERBOSE
3297 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3300 if (pcap_src->from_cap_socket) {
3302 sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
3304 if (sel_ret < 0 && errno != EINTR) {
3305 g_snprintf(errmsg, errmsg_len,
3306 "Unexpected error from select: %s", g_strerror(errno));
3307 report_capture_error(errmsg, please_report);
3313 /* Windows does not have select() for pipes. */
3314 /* Proceed with _dispatch() which waits for cap_pipe_done_q
3315 * notification from cap_thread_read() when ReadFile() on
3316 * the pipe has read enough bytes. */
3322 * "select()" says we can read from the pipe without blocking
3324 inpkts = pcap_src->cap_pipe_dispatch(ld, pcap_src, errmsg, errmsg_len);
3326 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: src %u pipe reached EOF or err, rcv: %u drop: %u flush: %u",
3327 G_STRFUNC, pcap_src->interface_id, pcap_src->received, pcap_src->dropped, pcap_src->flushed);
3328 g_assert(pcap_src->cap_pipe_err != PIPOK);
3334 /* dispatch from pcap */
3335 #ifdef MUST_DO_SELECT
3337 * If we have "pcap_get_selectable_fd()", we use it to get the
3338 * descriptor on which to select; if that's -1, it means there
3339 * is no descriptor on which you can do a "select()" (perhaps
3340 * because you're capturing on a special device, and that device's
3341 * driver unfortunately doesn't support "select()", in which case
3342 * we don't do the select - which means it might not be possible
3343 * to stop a capture until a packet arrives. If that's unacceptable,
3344 * plead with whoever supplies the software for that device to add
3345 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3346 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3347 * later, so it can use pcap_breakloop().
3349 #ifdef LOG_CAPTURE_VERBOSE
3350 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3352 if (pcap_src->pcap_fd != -1) {
3353 sel_ret = cap_pipe_select(pcap_src->pcap_fd);
3356 * "select()" says we can read from it without blocking; go for
3359 * We don't have pcap_breakloop(), so we only process one packet
3360 * per pcap_dispatch() call, to allow a signal to stop the
3361 * processing immediately, rather than processing all packets
3362 * in a batch before quitting.
3365 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3367 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3371 /* Error, rather than pcap_breakloop(). */
3372 pcap_src->pcap_err = TRUE;
3374 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3377 if (sel_ret < 0 && errno != EINTR) {
3378 g_snprintf(errmsg, errmsg_len,
3379 "Unexpected error from select: %s", g_strerror(errno));
3380 report_capture_error(errmsg, please_report);
3386 #endif /* MUST_DO_SELECT */
3388 /* dispatch from pcap without select */
3390 #ifdef LOG_CAPTURE_VERBOSE
3391 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3395 * On Windows, we don't support asynchronously telling a process to
3396 * stop capturing; instead, we check for an indication on a pipe
3397 * after processing packets. We therefore process only one packet
3398 * at a time, so that we can check the pipe after every packet.
3401 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3403 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3407 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3409 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3414 /* Error, rather than pcap_breakloop(). */
3415 pcap_src->pcap_err = TRUE;
3417 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3419 #else /* pcap_next_ex */
3420 #ifdef LOG_CAPTURE_VERBOSE
3421 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3423 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3426 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3427 * see https://wiki.wireshark.org/CaptureSetup/WinPcapRemote
3428 * This should be fixed in the WinPcap 4.0 alpha release.
3430 * For reference, an example remote interface:
3431 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3434 /* emulate dispatch from pcap */
3437 struct pcap_pkthdr *pkt_header;
3442 (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
3444 capture_loop_queue_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3446 capture_loop_write_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3451 pcap_src->pcap_err = TRUE;
3455 #endif /* pcap_next_ex */
3459 #ifdef LOG_CAPTURE_VERBOSE
3460 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3463 return ld->packets_captured - packet_count_before;
3467 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3468 * want to grab only the characters between the '{' and '}' delimiters.
3470 * Returns a GString that must be freed with g_string_free(). */
3472 isolate_uuid(const char *iface)
3477 ptr = strchr(iface, '{');
3479 return g_string_new(iface);
3480 gstr = g_string_new(ptr + 1);
3482 ptr = strchr(gstr->str, '}');
3486 gstr = g_string_truncate(gstr, ptr - gstr->str);
3491 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3492 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3494 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3495 char *errmsg, int errmsg_len)
3498 gchar *capfile_name;
3499 gchar *prefix, *suffix;
3500 gboolean is_tempfile;
3502 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3503 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3505 if (capture_opts->save_file != NULL) {
3506 /* We return to the caller while the capture is in progress.
3507 * Therefore we need to take a copy of save_file in
3508 * case the caller destroys it after we return.
3510 capfile_name = g_strdup(capture_opts->save_file);
3512 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3513 if (capture_opts->multi_files_on) {
3514 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3515 g_snprintf(errmsg, errmsg_len,
3516 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3517 g_free(capfile_name);
3520 if (strcmp(capfile_name, "-") == 0) {
3521 /* write to stdout */
3524 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3525 _setmode(1, O_BINARY);
3528 /* Try to open the specified FIFO for use as a capture buffer.
3529 Do *not* create it if it doesn't exist. There's nothing
3530 to truncate. If we need to read it, We Have A Problem. */
3531 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY, 0);
3533 } /* if (...output_to_pipe ... */
3536 if (capture_opts->multi_files_on) {
3537 /* ringbuffer is enabled */
3538 *save_file_fd = ringbuf_init(capfile_name,
3539 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3540 capture_opts->group_read_access);
3542 /* we need the ringbuf name */
3543 if (*save_file_fd != -1) {
3544 g_free(capfile_name);
3545 capfile_name = g_strdup(ringbuf_current_filename());
3548 /* Try to open/create the specified file for use as a capture buffer. */
3549 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY|O_TRUNC|O_CREAT,
3550 (capture_opts->group_read_access) ? 0640 : 0600);
3553 is_tempfile = FALSE;
3555 /* Choose a random name for the temporary capture buffer */
3556 if (global_capture_opts.ifaces->len > 1) {
3558 * More than one interface; just use the number of interfaces
3559 * to generate the temporary file name prefix.
3561 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3564 * One interface; use its description, if it has one, to generate
3565 * the temporary file name, otherwise use its name.
3568 const interface_options *interface_opts;
3570 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
3573 * Do we have a description?
3575 if (interface_opts->descr) {
3579 * Strip off any stuff we shouldn't use in the file name,
3580 * by getting the last component of what would be a file
3583 basename = g_path_get_basename(interface_opts->descr);
3586 * No - use the name.
3588 * Strip off any stuff we shouldn't use in the file name,
3589 * by getting the last component of what would be a file
3592 basename = g_path_get_basename(interface_opts->name);
3595 * This is Windows, where we might have an ugly GUID-based
3598 * If it's an ugly GUID-based name, use the generic portion
3599 * of the interface GUID to form the basis of the filename.
3601 if (strncmp("NPF_{", basename, 5) == 0) {
3603 * We have a GUID-based name; extract the GUID digits
3604 * as the basis of the filename.
3607 iface = isolate_uuid(basename);
3609 basename = g_strdup(iface->str);
3610 g_string_free(iface, TRUE);
3614 /* generate the temp file name prefix */
3615 prefix = g_strconcat("wireshark_", basename, NULL);
3619 /* Generate the appropriate suffix. */
3620 if (capture_opts->use_pcapng) {
3625 *save_file_fd = create_tempfile(&tmpname, prefix, suffix);
3627 capfile_name = g_strdup(tmpname);
3631 /* did we fail to open the output file? */
3632 if (*save_file_fd == -1) {
3634 g_snprintf(errmsg, errmsg_len,
3635 "The temporary file to which the capture would be saved (\"%s\") "
3636 "could not be opened: %s.", capfile_name, g_strerror(errno));
3638 if (capture_opts->multi_files_on) {
3639 ringbuf_error_cleanup();
3642 g_snprintf(errmsg, errmsg_len,
3643 "The file to which the capture would be saved (\"%s\") "
3644 "could not be opened: %s.", capfile_name,
3647 g_free(capfile_name);
3651 if (capture_opts->save_file != NULL) {
3652 g_free(capture_opts->save_file);
3654 capture_opts->save_file = capfile_name;
3655 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3656 "g_free(capfile_name)". */
3661 static time_t get_next_time_interval(int interval_s) {
3662 time_t next_time = time(NULL);
3663 next_time -= next_time % interval_s;
3664 next_time += interval_s;
3668 /* Do the work of handling either the file size or file duration capture
3669 conditions being reached, and switching files or stopping. */
3671 do_file_switch_or_stop(capture_options *capture_opts)
3673 gboolean successful;
3675 if (capture_opts->multi_files_on) {
3676 if (capture_opts->has_autostop_files &&
3677 ++global_ld.file_count >= capture_opts->autostop_files) {
3678 /* no files left: stop here */
3679 global_ld.go = FALSE;
3683 /* Switch to the next ringbuffer file */
3684 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3685 &global_ld.save_file_fd, &global_ld.err)) {
3687 /* File switch succeeded: reset the conditions */
3688 global_ld.bytes_written = 0;
3689 global_ld.packets_written = 0;
3690 if (capture_opts->use_pcapng) {
3691 successful = capture_loop_init_pcapng_output(capture_opts, &global_ld);
3693 capture_src *pcap_src;
3694 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3695 successful = libpcap_write_file_header(global_ld.pdh, pcap_src->linktype, pcap_src->snaplen,
3696 pcap_src->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3700 fclose(global_ld.pdh);
3701 global_ld.pdh = NULL;
3702 global_ld.go = FALSE;
3705 if (global_ld.file_duration_timer) {
3706 g_timer_reset(global_ld.file_duration_timer);
3708 if (global_ld.next_interval_time) {
3709 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
3711 fflush(global_ld.pdh);
3713 report_packet_count(global_ld.inpkts_to_sync_pipe);
3714 global_ld.inpkts_to_sync_pipe = 0;
3715 report_new_capture_file(capture_opts->save_file);
3717 /* File switch failed: stop here */
3718 global_ld.go = FALSE;
3722 /* single file, stop now */
3723 global_ld.go = FALSE;
3730 pcap_read_handler(void* arg)
3732 capture_src *pcap_src = (capture_src *)arg;
3733 char errmsg[MSG_MAX_LENGTH+1];
3735 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3736 pcap_src->interface_id);
3738 /* If this is a pipe input it might finish early. */
3739 while (global_ld.go && pcap_src->cap_pipe_err == PIPOK) {
3740 /* dispatch incoming packets */
3741 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_src);
3744 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3745 pcap_src->interface_id);
3746 g_thread_exit(NULL);
3750 /* Try to pop an item off the packet queue and if it exists, write it */
3752 capture_loop_dequeue_packet(void) {
3753 pcap_queue_element *queue_element;
3755 g_async_queue_lock(pcap_queue);
3756 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3757 if (queue_element) {
3758 if (queue_element->pcap_src->from_pcapng) {
3759 pcap_queue_bytes -= queue_element->u.bh.block_total_length;
3761 pcap_queue_bytes -= queue_element->u.phdr.caplen;
3763 pcap_queue_packets -= 1;
3765 g_async_queue_unlock(pcap_queue);
3766 if (queue_element) {
3767 if (queue_element->pcap_src->from_pcapng) {
3768 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3769 "Dequeued a block of type 0x%08x of length %d captured on interface %d.",
3770 queue_element->u.bh.block_type, queue_element->u.bh.block_total_length,
3771 queue_element->pcap_src->interface_id);
3773 capture_loop_write_pcapng_cb(queue_element->pcap_src,
3774 &queue_element->u.bh,
3777 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3778 "Dequeued a packet of length %d captured on interface %d.",
3779 queue_element->u.phdr.caplen, queue_element->pcap_src->interface_id);
3781 capture_loop_write_packet_cb((u_char *) queue_element->pcap_src,
3782 &queue_element->u.phdr,
3785 g_free(queue_element->pd);
3786 g_free(queue_element);
3792 /* Do the low-level work of a capture.
3793 Returns TRUE if it succeeds, FALSE otherwise. */
3795 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3798 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3800 struct timeval upd_time, cur_time;
3804 GTimer *autostop_duration_timer = NULL;
3807 gboolean cfilter_error = FALSE;
3808 char errmsg[MSG_MAX_LENGTH+1];
3809 char secondary_errmsg[MSG_MAX_LENGTH+1];
3810 capture_src *pcap_src;
3811 interface_options *interface_opts;
3812 guint i, error_index = 0;
3815 *secondary_errmsg = '\0';
3817 /* init the loop data */
3818 global_ld.go = TRUE;
3819 global_ld.packets_captured = 0;
3821 global_ld.report_packet_count = FALSE;
3823 global_ld.inpkts_to_sync_pipe = 0;
3824 global_ld.err = 0; /* no error seen yet */
3825 global_ld.pdh = NULL;
3826 global_ld.save_file_fd = -1;
3827 global_ld.file_count = 0;
3828 global_ld.file_duration_timer = NULL;
3829 global_ld.next_interval_time = 0;
3830 global_ld.interval_s = 0;
3832 /* We haven't yet gotten the capture statistics. */
3833 *stats_known = FALSE;
3835 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3836 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3838 /* open the "input file" from network interface or capture pipe */
3839 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3840 secondary_errmsg, sizeof(secondary_errmsg))) {
3843 for (i = 0; i < capture_opts->ifaces->len; i++) {
3844 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3845 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
3846 /* init the input filter from the network interface (capture pipe will do nothing) */
3848 * When remote capturing WinPCap crashes when the capture filter
3849 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3852 switch (capture_loop_init_filter(pcap_src->pcap_h, pcap_src->from_cap_pipe,
3853 interface_opts->name,
3854 interface_opts->cfilter?interface_opts->cfilter:"")) {
3856 case INITFILTER_NO_ERROR:
3859 case INITFILTER_BAD_FILTER:
3860 cfilter_error = TRUE;
3862 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
3865 case INITFILTER_OTHER_ERROR:
3866 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3867 pcap_geterr(pcap_src->pcap_h));
3868 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3873 /* If we're supposed to write to a capture file, open it for output
3874 (temporary/specified name/ringbuffer) */
3875 if (capture_opts->saving_to_file) {
3876 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3877 errmsg, sizeof(errmsg))) {
3881 /* set up to write to the already-opened capture output file/files */
3882 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3887 /* XXX - capture SIGTERM and close the capture, in case we're on a
3888 Linux 2.0[.x] system and you have to explicitly close the capture
3889 stream in order to turn promiscuous mode off? We need to do that
3890 in other places as well - and I don't think that works all the
3891 time in any case, due to libpcap bugs. */
3893 /* Well, we should be able to start capturing.
3895 Sync out the capture file, so the header makes it to the file system,
3896 and send a "capture started successfully and capture file created"
3897 message to our parent so that they'll open the capture file and
3898 update its windows to indicate that we have a live capture in
3900 fflush(global_ld.pdh);
3901 report_new_capture_file(capture_opts->save_file);
3904 if (capture_opts->has_file_interval) {
3905 global_ld.interval_s = capture_opts->file_interval;
3906 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
3908 /* create stop conditions */
3909 if (capture_opts->has_autostop_filesize) {
3910 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3911 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3914 if (capture_opts->has_autostop_duration) {
3915 autostop_duration_timer = g_timer_new();
3918 if (capture_opts->multi_files_on) {
3919 if (capture_opts->has_file_duration) {
3920 global_ld.file_duration_timer = g_timer_new();
3924 /* init the time values */
3926 upd_time = GetTickCount();
3928 gettimeofday(&upd_time, NULL);
3930 start_time = create_timestamp();
3931 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3932 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3934 /* WOW, everything is prepared! */
3935 /* please fasten your seat belts, we will enter now the actual capture loop */
3937 pcap_queue = g_async_queue_new();
3938 pcap_queue_bytes = 0;
3939 pcap_queue_packets = 0;
3940 for (i = 0; i < global_ld.pcaps->len; i++) {
3941 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3942 /* XXX - Add an interface name here? */
3943 pcap_src->tid = g_thread_new("Capture read", pcap_read_handler, pcap_src);
3946 while (global_ld.go) {
3947 /* dispatch incoming packets */
3949 gboolean dequeued = capture_loop_dequeue_packet();
3957 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3958 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3959 sizeof(errmsg), pcap_src);
3962 /* Stop capturing if all of our sources are pipes and none of them are open. */
3963 gboolean open_interfaces = FALSE;
3964 for (i = 0; i < global_ld.pcaps->len; i++) {
3965 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3966 if (pcap_src->cap_pipe_err == PIPOK) {
3967 /* True for both non-pipes and open pipes. */
3968 open_interfaces = TRUE;
3971 if (!open_interfaces) {
3972 global_ld.go = FALSE;
3976 /* Were we asked to print packet counts by the SIGINFO handler? */
3977 if (global_ld.report_packet_count) {
3978 fprintf(stderr, "%u packet%s captured\n", global_ld.packets_captured,
3979 plurality(global_ld.packets_captured, "", "s"));
3980 global_ld.report_packet_count = FALSE;
3985 /* any news from our parent (signal pipe)? -> just stop the capture */
3986 if (!signal_pipe_check_running()) {
3987 global_ld.go = FALSE;
3992 global_ld.inpkts_to_sync_pipe += inpkts;
3994 if (capture_opts->output_to_pipe) {
3995 fflush(global_ld.pdh);
3999 /* Only update once every 500ms so as not to overload slow displays.
4000 * This also prevents too much context-switching between the dumpcap
4001 * and wireshark processes.
4003 #define DUMPCAP_UPD_TIME 500
4006 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
4007 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) /* wrap just causes an extra update */
4009 gettimeofday(&cur_time, NULL);
4010 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
4011 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000))
4015 upd_time = cur_time;
4018 if (pcap_stats(pch, stats) >= 0) {
4019 *stats_known = TRUE;
4022 /* Let the parent process know. */
4023 if (global_ld.inpkts_to_sync_pipe) {
4025 fflush(global_ld.pdh);
4027 /* Send our parent a message saying we've written out
4028 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
4030 report_packet_count(global_ld.inpkts_to_sync_pipe);
4032 global_ld.inpkts_to_sync_pipe = 0;
4035 /* check capture duration condition */
4036 if (autostop_duration_timer != NULL && g_timer_elapsed(autostop_duration_timer, NULL) >= capture_opts->autostop_duration) {
4037 /* The maximum capture time has elapsed; stop the capture. */
4038 global_ld.go = FALSE;
4042 /* check capture file duration condition */
4043 if (global_ld.file_duration_timer != NULL && g_timer_elapsed(global_ld.file_duration_timer, NULL) >= capture_opts->file_duration) {
4044 /* duration limit reached, do we have another file? */
4045 if (!do_file_switch_or_stop(capture_opts))
4047 } /* cnd_file_duration */
4049 /* check capture file interval condition */
4050 if (global_ld.interval_s && time(NULL) >= global_ld.next_interval_time) {
4051 /* end of interval reached, do we have another file? */
4052 if (!do_file_switch_or_stop(capture_opts))
4054 } /* cnd_file_interval */
4058 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
4061 for (i = 0; i < global_ld.pcaps->len; i++) {
4062 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4063 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
4064 pcap_src->interface_id);
4065 g_thread_join(pcap_src->tid);
4066 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
4067 pcap_src->interface_id);
4070 gboolean dequeued = capture_loop_dequeue_packet();
4074 global_ld.inpkts_to_sync_pipe += 1;
4075 if (capture_opts->output_to_pipe) {
4076 fflush(global_ld.pdh);
4082 /* delete stop conditions */
4083 if (global_ld.file_duration_timer != NULL)
4084 g_timer_destroy(global_ld.file_duration_timer);
4085 if (autostop_duration_timer != NULL)
4086 g_timer_destroy(autostop_duration_timer);
4088 /* did we have a pcap (input) error? */
4089 for (i = 0; i < capture_opts->ifaces->len; i++) {
4090 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4091 if (pcap_src->pcap_err) {
4092 /* On Linux, if an interface goes down while you're capturing on it,
4093 you'll get a "recvfrom: Network is down" or
4094 "The interface went down" error (ENETDOWN).
4095 (At least you will if g_strerror() doesn't show a local translation
4098 On FreeBSD, DragonFly BSD, and macOS, if a network adapter
4099 disappears while you're capturing on it, you'll get a
4100 "read: Device not configured" error (ENXIO). (See previous
4101 parenthetical note.)
4103 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
4105 These should *not* be reported to the Wireshark developers. */
4108 cap_err_str = pcap_geterr(pcap_src->pcap_h);
4109 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
4110 strcmp(cap_err_str, "The interface went down") == 0 ||
4111 strcmp(cap_err_str, "read: Device not configured") == 0 ||
4112 strcmp(cap_err_str, "read: I/O error") == 0 ||
4113 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
4114 report_capture_error("The network adapter on which the capture was being done "
4115 "is no longer running; the capture has stopped.",
4118 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
4120 report_capture_error(errmsg, please_report);
4123 } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
4124 report_capture_error(errmsg, "");
4128 /* did we have an output error while capturing? */
4129 if (global_ld.err == 0) {
4132 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4133 sizeof(secondary_errmsg),
4134 capture_opts->save_file, global_ld.err, FALSE);
4135 report_capture_error(errmsg, secondary_errmsg);
4139 if (capture_opts->saving_to_file) {
4140 /* close the output file */
4141 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
4145 /* there might be packets not yet notified to the parent */
4146 /* (do this after closing the file, so all packets are already flushed) */
4147 if (global_ld.inpkts_to_sync_pipe) {
4149 report_packet_count(global_ld.inpkts_to_sync_pipe);
4150 global_ld.inpkts_to_sync_pipe = 0;
4153 /* If we've displayed a message about a write error, there's no point
4154 in displaying another message about an error on close. */
4155 if (!close_ok && write_ok) {
4156 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4157 sizeof(secondary_errmsg),
4158 capture_opts->save_file, err_close, TRUE);
4159 report_capture_error(errmsg, secondary_errmsg);
4163 * XXX We exhibit different behaviour between normal mode and sync mode
4164 * when the pipe is stdin and not already at EOF. If we're a child, the
4165 * parent's stdin isn't closed, so if the user starts another capture,
4166 * cap_pipe_open_live() will very likely not see the expected magic bytes and
4167 * will say "Unrecognized libpcap format". On the other hand, in normal
4168 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
4171 report_capture_count(TRUE);
4173 /* get packet drop statistics from pcap */
4174 for (i = 0; i < capture_opts->ifaces->len; i++) {
4176 guint32 pcap_dropped = 0;
4178 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4179 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4180 received = pcap_src->received;
4181 if (pcap_src->pcap_h != NULL) {
4182 g_assert(!pcap_src->from_cap_pipe);
4183 /* Get the capture statistics, so we know how many packets were dropped. */
4185 * Older versions of libpcap didn't set ps_ifdrop on some
4186 * platforms; initialize it to 0 to handle that.
4188 stats->ps_ifdrop = 0;
4189 if (pcap_stats(pcap_src->pcap_h, stats) >= 0) {
4190 *stats_known = TRUE;
4191 /* Let the parent process know. */
4192 pcap_dropped += stats->ps_drop;
4194 g_snprintf(errmsg, sizeof(errmsg),
4195 "Can't get packet-drop statistics: %s",
4196 pcap_geterr(pcap_src->pcap_h));
4197 report_capture_error(errmsg, please_report);
4200 report_packet_drops(received, pcap_dropped, pcap_src->dropped, pcap_src->flushed, stats->ps_ifdrop, interface_opts->display_name);
4203 /* close the input file (pcap or capture pipe) */
4204 capture_loop_close_input(&global_ld);
4206 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
4208 /* ok, if the write and the close were successful. */
4209 return write_ok && close_ok;
4212 if (capture_opts->multi_files_on) {
4213 /* cleanup ringbuffer */
4214 ringbuf_error_cleanup();
4216 /* We can't use the save file, and we have no FILE * for the stream
4217 to close in order to close it, so close the FD directly. */
4218 if (global_ld.save_file_fd != -1) {
4219 ws_close(global_ld.save_file_fd);
4222 /* We couldn't even start the capture, so get rid of the capture
4224 if (capture_opts->save_file != NULL) {
4225 ws_unlink(capture_opts->save_file);
4226 g_free(capture_opts->save_file);
4229 capture_opts->save_file = NULL;
4231 report_cfilter_error(capture_opts, error_index, errmsg);
4233 report_capture_error(errmsg, secondary_errmsg);
4235 /* close the input file (pcap or cap_pipe) */
4236 capture_loop_close_input(&global_ld);
4238 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
4245 capture_loop_stop(void)
4247 #ifdef HAVE_PCAP_BREAKLOOP
4249 capture_src *pcap_src;
4251 for (i = 0; i < global_ld.pcaps->len; i++) {
4252 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4253 if (pcap_src->pcap_h != NULL)
4254 pcap_breakloop(pcap_src->pcap_h);
4257 global_ld.go = FALSE;
4262 capture_loop_get_errmsg(char *errmsg, size_t errmsglen, char *secondary_errmsg,
4263 size_t secondary_errmsglen, const char *fname,
4264 int err, gboolean is_close)
4266 static const char find_space[] =
4267 "You will need to free up space on that file system"
4268 " or put the capture file on a different file system.";
4273 g_snprintf(errmsg, (gulong)errmsglen,
4274 "Not all the packets could be written to the file"
4275 " to which the capture was being saved\n"
4276 "(\"%s\") because there is no space left on the file system\n"
4277 "on which that file resides.",
4279 g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen, "%s",
4285 g_snprintf(errmsg, (gulong)errmsglen,
4286 "Not all the packets could be written to the file"
4287 " to which the capture was being saved\n"
4288 "(\"%s\") because you are too close to, or over,"
4289 " your disk quota\n"
4290 "on the file system on which that file resides.",
4292 g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen, "%s",
4299 g_snprintf(errmsg, (gulong)errmsglen,
4300 "The file to which the capture was being saved\n"
4301 "(\"%s\") could not be closed: %s.",
4302 fname, g_strerror(err));
4304 g_snprintf(errmsg, (gulong)errmsglen,
4305 "An error occurred while writing to the file"
4306 " to which the capture was being saved\n"
4308 fname, g_strerror(err));
4310 g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen,
4311 "%s", please_report);
4317 * We wrote one packet. Update some statistics and check if we've met any
4318 * autostop or ring buffer conditions.
4321 capture_loop_wrote_one_packet(capture_src *pcap_src) {
4322 global_ld.packets_captured++;
4323 global_ld.packets_written++;
4324 pcap_src->received++;
4326 /* check -c NUM / -a packets:NUM */
4327 if (global_capture_opts.has_autostop_packets && global_ld.packets_captured >= global_capture_opts.autostop_packets) {
4328 fflush(global_ld.pdh);
4329 global_ld.go = FALSE;
4332 /* check -b packets:NUM */
4333 if (global_capture_opts.has_file_packets && global_ld.packets_written >= global_capture_opts.file_packets) {
4334 do_file_switch_or_stop(&global_capture_opts);
4337 /* check -a filesize:NUM */
4338 if (global_capture_opts.has_autostop_filesize &&
4339 global_capture_opts.autostop_filesize > 0 &&
4340 global_ld.bytes_written / 1000 >= global_capture_opts.autostop_filesize) {
4341 /* Capture size limit reached, do we have another file? */
4342 do_file_switch_or_stop(&global_capture_opts);
4347 /* one pcapng block was captured, process it */
4349 capture_loop_write_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, u_char *pd)
4354 * This should never be called if we're not writing pcapng.
4356 g_assert(global_capture_opts.use_pcapng);
4358 /* We may be called multiple times from pcap_dispatch(); if we've set
4359 the "stop capturing" flag, ignore this packet, as we're not
4360 supposed to be saving any more packets. */
4361 if (!global_ld.go) {
4362 pcap_src->flushed++;
4366 if (!pcapng_adjust_block(pcap_src, bh, pd)) {
4367 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "%s failed to adjust pcapng block.", G_STRFUNC);
4368 g_assert_not_reached();
4372 if (bh->block_type == BLOCK_TYPE_SHB && !global_ld.pcapng_passthrough) {
4374 * capture_loop_init_pcapng_output should've handled this. We need
4375 * to write ISBs when they're initially read so we shouldn't skip
4381 if (global_ld.pdh) {
4382 gboolean successful;
4384 /* We're supposed to write the packet to a file; do so.
4385 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4386 "ld->err" to the error. */
4387 successful = pcapng_write_block(global_ld.pdh,
4389 bh->block_total_length,
4390 &global_ld.bytes_written, &err);
4392 fflush(global_ld.pdh);
4394 global_ld.go = FALSE;
4395 global_ld.err = err;
4396 pcap_src->dropped++;
4397 } else if (bh->block_type == BLOCK_TYPE_EPB || bh->block_type == BLOCK_TYPE_SPB || bh->block_type == BLOCK_TYPE_SYSTEMD_JOURNAL) {
4398 /* count packet only if we actually have an EPB or SPB */
4399 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4400 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4401 "Wrote a pcapng block type %u of length %d captured on interface %u.",
4402 bh->block_type, bh->block_total_length, pcap_src->interface_id);
4404 capture_loop_wrote_one_packet(pcap_src);
4409 /* one pcap packet was captured, process it */
4411 capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4414 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4416 guint ts_mul = pcap_src->ts_nsec ? 1000000000 : 1000000;
4418 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_write_packet_cb");
4420 /* We may be called multiple times from pcap_dispatch(); if we've set
4421 the "stop capturing" flag, ignore this packet, as we're not
4422 supposed to be saving any more packets. */
4423 if (!global_ld.go) {
4424 pcap_src->flushed++;
4428 if (global_ld.pdh) {
4429 gboolean successful;
4431 /* We're supposed to write the packet to a file; do so.
4432 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4433 "ld->err" to the error. */
4434 if (global_capture_opts.use_pcapng) {
4435 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4437 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4438 phdr->caplen, phdr->len,
4439 pcap_src->interface_id,
4442 &global_ld.bytes_written, &err);
4444 successful = libpcap_write_packet(global_ld.pdh,
4445 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4446 phdr->caplen, phdr->len,
4448 &global_ld.bytes_written, &err);
4451 global_ld.go = FALSE;
4452 global_ld.err = err;
4453 pcap_src->dropped++;
4455 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4456 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4457 "Wrote a pcap packet of length %d captured on interface %u.",
4458 phdr->caplen, pcap_src->interface_id);
4460 capture_loop_wrote_one_packet(pcap_src);
4465 /* one packet was captured, queue it */
4467 capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4470 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4471 pcap_queue_element *queue_element;
4472 gboolean limit_reached;
4474 /* We may be called multiple times from pcap_dispatch(); if we've set
4475 the "stop capturing" flag, ignore this packet, as we're not
4476 supposed to be saving any more packets. */
4477 if (!global_ld.go) {
4478 pcap_src->flushed++;
4482 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4483 if (queue_element == NULL) {
4484 pcap_src->dropped++;
4487 queue_element->pcap_src = pcap_src;
4488 queue_element->u.phdr = *phdr;
4489 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4490 if (queue_element->pd == NULL) {
4491 pcap_src->dropped++;
4492 g_free(queue_element);
4495 memcpy(queue_element->pd, pd, phdr->caplen);
4496 g_async_queue_lock(pcap_queue);
4497 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4498 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4499 limit_reached = FALSE;
4500 g_async_queue_push_unlocked(pcap_queue, queue_element);
4501 pcap_queue_bytes += phdr->caplen;
4502 pcap_queue_packets += 1;
4504 limit_reached = TRUE;
4506 g_async_queue_unlock(pcap_queue);
4507 if (limit_reached) {
4508 pcap_src->dropped++;
4509 g_free(queue_element->pd);
4510 g_free(queue_element);
4511 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4512 "Dropped a packet of length %d captured on interface %u.",
4513 phdr->caplen, pcap_src->interface_id);
4515 pcap_src->received++;
4516 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4517 "Queued a packet of length %d captured on interface %u.",
4518 phdr->caplen, pcap_src->interface_id);
4520 /* I don't want to hold the mutex over the debug output. So the
4521 output may be wrong */
4522 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4523 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4524 pcap_queue_bytes, pcap_queue_packets);
4527 /* one pcapng block was captured, queue it */
4529 capture_loop_queue_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, u_char *pd)
4531 pcap_queue_element *queue_element;
4532 gboolean limit_reached;
4534 /* We may be called multiple times from pcap_dispatch(); if we've set
4535 the "stop capturing" flag, ignore this packet, as we're not
4536 supposed to be saving any more packets. */
4537 if (!global_ld.go) {
4538 pcap_src->flushed++;
4542 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4543 if (queue_element == NULL) {
4544 pcap_src->dropped++;
4547 queue_element->pcap_src = pcap_src;
4548 queue_element->u.bh = *bh;
4549 queue_element->pd = (u_char *)g_malloc(bh->block_total_length);
4550 if (queue_element->pd == NULL) {
4551 pcap_src->dropped++;
4552 g_free(queue_element);
4555 memcpy(queue_element->pd, pd, bh->block_total_length);
4556 g_async_queue_lock(pcap_queue);
4557 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4558 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4559 limit_reached = FALSE;
4560 g_async_queue_push_unlocked(pcap_queue, queue_element);
4561 pcap_queue_bytes += bh->block_total_length;
4562 pcap_queue_packets += 1;
4564 limit_reached = TRUE;
4566 g_async_queue_unlock(pcap_queue);
4567 if (limit_reached) {
4568 pcap_src->dropped++;
4569 g_free(queue_element->pd);
4570 g_free(queue_element);
4571 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4572 "Dropped a packet of length %d captured on interface %u.",
4573 bh->block_total_length, pcap_src->interface_id);
4575 pcap_src->received++;
4576 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4577 "Queued a block of type 0x%08x of length %d captured on interface %u.",
4578 bh->block_type, bh->block_total_length, pcap_src->interface_id);
4580 /* I don't want to hold the mutex over the debug output. So the
4581 output may be wrong */
4582 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4583 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4584 pcap_queue_bytes, pcap_queue_packets);
4588 set_80211_channel(const char *iface, const char *opt)
4592 guint32 center_freq1 = 0;
4593 guint32 center_freq2 = 0;
4596 gchar **options = NULL;
4598 options = g_strsplit_set(opt, ",", 4);
4599 for (args = 0; options[args]; args++);
4602 freq = get_nonzero_guint32(options[0], "802.11 channel frequency");
4604 if (args >= 1 && options[1]) {
4605 type = ws80211_str_to_chan_type(options[1]);
4607 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
4613 if (args >= 2 && options[2])
4614 center_freq1 = get_nonzero_guint32(options[2], "VHT center frequency");
4616 if (args >= 3 && options[3])
4617 center_freq2 = get_nonzero_guint32(options[3], "VHT center frequency 2");
4619 ret = ws80211_init();
4621 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4625 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
4628 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4634 pipe_write_block(2, SP_SUCCESS, NULL);
4637 g_strfreev(options);
4642 get_dumpcap_compiled_info(GString *str)
4644 /* Capture libraries */
4645 g_string_append(str, ", ");
4646 get_compiled_caplibs_version(str);
4650 get_dumpcap_runtime_info(GString *str)
4652 /* Capture libraries */
4653 g_string_append(str, ", ");
4654 get_runtime_caplibs_version(str);
4657 /* And now our feature presentation... [ fade to music ] */
4659 main(int argc, char *argv[])
4662 static const struct option long_options[] = {
4663 {"help", no_argument, NULL, 'h'},
4664 {"version", no_argument, NULL, 'v'},
4665 LONGOPT_CAPTURE_COMMON
4669 gboolean arg_error = FALSE;
4675 struct sigaction action, oldaction;
4678 gboolean start_capture = TRUE;
4679 gboolean stats_known;
4680 struct pcap_stat stats;
4681 GLogLevelFlags log_flags;
4682 gboolean list_interfaces = FALSE;
4683 int caps_queries = 0;
4684 #ifdef HAVE_BPF_IMAGE
4685 gboolean print_bpf_code = FALSE;
4687 gboolean set_chan = FALSE;
4688 gchar *set_chan_arg = NULL;
4689 gboolean machine_readable = FALSE;
4690 gboolean print_statistics = FALSE;
4691 int status, run_once_args = 0;
4694 #if defined(__APPLE__) && defined(__LP64__)
4695 struct utsname osinfo;
4699 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
4701 /* Initialize the version information. */
4702 ws_init_version_info("Dumpcap (Wireshark)", NULL, get_dumpcap_compiled_info,
4703 get_dumpcap_runtime_info);
4706 create_app_running_mutex();
4709 * Initialize our DLL search path. MUST be called before LoadLibrary
4712 ws_init_dll_search_path();
4715 #ifdef HAVE_BPF_IMAGE
4716 #define OPTSTRING_d "d"
4718 #define OPTSTRING_d ""
4721 #ifdef HAVE_PCAP_REMOTE
4722 #define OPTSTRING_r "r"
4723 #define OPTSTRING_u "u"
4725 #define OPTSTRING_r ""
4726 #define OPTSTRING_u ""
4729 #ifdef HAVE_PCAP_SETSAMPLING
4730 #define OPTSTRING_m "m:"
4732 #define OPTSTRING_m ""
4735 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
4737 #ifdef DEBUG_CHILD_DUMPCAP
4738 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4739 fprintf (stderr, "Unable to open debug log file .\n");
4744 #if defined(__APPLE__) && defined(__LP64__)
4746 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4747 * a bug workaround - timeouts less than 1 second don't work with libpcap
4748 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4749 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4750 * The problem is extremely unlikely to be reintroduced in a future
4753 if (uname(&osinfo) == 0) {
4755 * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
4756 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4757 * number of 10.0.0, not 10.1.0 - go figure).
4759 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4760 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4761 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4762 need_timeout_workaround = TRUE;
4767 * Determine if dumpcap is being requested to run in a special
4768 * capture_child mode by going thru the command line args to see if
4769 * a -Z is present. (-Z is a hidden option).
4771 * The primary result of running in capture_child mode is that
4772 * all messages sent out on stderr are in a special type/len/string
4773 * format to allow message processing by type. These messages include
4774 * error messages if dumpcap fails to start the operation it was
4775 * requested to do, as well as various "status" messages which are sent
4776 * when an actual capture is in progress, and a "success" message sent
4777 * if dumpcap was requested to perform an operation other than a
4780 * Capture_child mode would normally be requested by a parent process
4781 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4782 * to which dumpcap stderr has been redirected. It might also have
4783 * another pipe to obtain dumpcap stdout output; for operations other
4784 * than a capture, that information is formatted specially for easier
4785 * parsing by the parent process.
4787 * Capture_child mode needs to be determined immediately upon
4788 * startup so that any messages generated by dumpcap in this mode
4789 * (eg: during initialization) will be formatted properly.
4792 for (i=1; i<argc; i++) {
4793 if (strcmp("-Z", argv[i]) == 0) {
4794 capture_child = TRUE;
4795 machine_readable = TRUE; /* request machine-readable output */
4797 /* set output pipe to binary mode, to avoid ugly text conversions */
4798 _setmode(2, O_BINARY);
4803 /* The default_log_handler will use stdout, which makes trouble in */
4804 /* capture child mode, as it uses stdout for its sync_pipe. */
4805 /* So: the filtering is done in the console_log_handler and not here.*/
4806 /* We set the log handlers right up front to make sure that any log */
4807 /* messages when running as child will be sent back to the parent */
4808 /* with the correct format. */
4813 G_LOG_LEVEL_CRITICAL|
4814 G_LOG_LEVEL_WARNING|
4815 G_LOG_LEVEL_MESSAGE|
4819 G_LOG_FLAG_RECURSION);
4821 g_log_set_handler(NULL,
4823 console_log_handler, NULL /* user_data */);
4824 g_log_set_handler(LOG_DOMAIN_MAIN,
4826 console_log_handler, NULL /* user_data */);
4827 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4829 console_log_handler, NULL /* user_data */);
4830 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4832 console_log_handler, NULL /* user_data */);
4834 /* Initialize the pcaps list and IDBs */
4835 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(capture_src *));
4836 global_ld.pcapng_passthrough = FALSE;
4837 global_ld.saved_shb = NULL;
4838 global_ld.saved_idbs = g_array_new(FALSE, TRUE, sizeof(saved_idb_t));
4841 /* Load wpcap if possible. Do this before collecting the run-time version information */
4844 /* ... and also load the packet.dll from wpcap */
4845 /* XXX - currently not required, may change later. */
4846 /*wpcap_packet_load();*/
4848 /* Start windows sockets */
4849 result = WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4852 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_ERROR,
4853 "ERROR: WSAStartup failed with error: %d", result);
4857 /* Set handler for Ctrl+C key */
4858 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4860 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4861 and exit. Do the same with SIGPIPE, in case, for example,
4862 we're writing to our standard output and it's a pipe.
4863 Do the same with SIGHUP if it's not being ignored (if we're
4864 being run under nohup, it might be ignored, in which case we
4865 should leave it ignored).
4867 XXX - apparently, Coverity complained that part of action
4868 wasn't initialized. Perhaps it's running on Linux, where
4869 struct sigaction has an ignored "sa_restorer" element and
4870 where "sa_handler" and "sa_sigaction" might not be two
4871 members of a union. */
4872 memset(&action, 0, sizeof(action));
4873 action.sa_handler = capture_cleanup_handler;
4875 * Arrange that system calls not get restarted, because when
4876 * our signal handler returns we don't want to restart
4877 * a call that was waiting for packets to arrive.
4879 action.sa_flags = 0;
4880 sigemptyset(&action.sa_mask);
4881 sigaction(SIGTERM, &action, NULL);
4882 sigaction(SIGINT, &action, NULL);
4883 sigaction(SIGPIPE, &action, NULL);
4884 sigaction(SIGHUP, NULL, &oldaction);
4885 if (oldaction.sa_handler == SIG_DFL)
4886 sigaction(SIGHUP, &action, NULL);
4889 /* Catch SIGINFO and, if we get it and we're capturing in
4890 quiet mode, report the number of packets we've captured. */
4891 action.sa_handler = report_counts_siginfo;
4892 action.sa_flags = SA_RESTART;
4893 sigemptyset(&action.sa_mask);
4894 sigaction(SIGINFO, &action, NULL);
4895 #endif /* SIGINFO */
4898 /* ----------------------------------------------------------------- */
4899 /* Privilege and capability handling */
4901 /* 1. Running not as root or suid root; no special capabilities. */
4904 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4907 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4909 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4910 /* capabilities; Drop all other capabilities; */
4911 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4912 /* else: after pcap_open_live() in capture_loop_open_input() */
4913 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4914 /* (Note: this means that the process, although logged in */
4915 /* as root, does not have various permissions such as the */
4916 /* ability to bypass file access permissions). */
4917 /* XXX: Should we just leave capabilities alone in this case */
4918 /* so that user gets expected effect that root can do */
4921 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4923 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4924 /* else: after pcap_open_live() in capture_loop_open_input() */
4925 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4926 /* pcap_open_live). */
4928 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4930 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4931 /* capabilities; Drop all other capabilities; */
4932 /* Drop suid privileges (euid=ruid); */
4933 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4934 /* else: after pcap_open_live() in capture_loop_open_input() */
4935 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4937 /* XXX: For some Linux versions/distros with capabilities */
4938 /* a 'normal' process with any capabilities cannot be */
4939 /* 'killed' (signaled) from another (same uid) non-privileged */
4941 /* For example: If (non-suid) Wireshark forks a */
4942 /* child suid dumpcap which acts as described here (case 5), */
4943 /* Wireshark will be unable to kill (signal) the child */
4944 /* dumpcap process until the capabilities have been dropped */
4945 /* (after pcap_open_live()). */
4946 /* This behaviour will apparently be changed in the kernel */
4947 /* to allow the kill (signal) in this case. */
4948 /* See the following for details: */
4949 /* https://www.mail-archive.com/ [wrapped] */
4950 /* linux-security-module@vger.kernel.org/msg02913.html */
4952 /* It is therefore conceivable that if dumpcap somehow hangs */
4953 /* in pcap_open_live or before that wireshark will not */
4954 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4955 /* In this case, exiting wireshark will kill the child */
4956 /* dumpcap process. */
4958 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4959 /* capabilities; Using libcap. Note: capset cmd (which see) */
4960 /* used to assign capabilities to file. */
4962 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4963 /* else: after pcap_open_live() in capture_loop_open_input() */
4964 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4966 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4967 /* longer required (similar to capture). */
4969 /* ----------------------------------------------------------------- */
4971 init_process_policies();
4974 /* If 'started with special privileges' (and using libcap) */
4975 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4976 /* Set euid/egid = ruid/rgid to remove suid privileges */
4977 relinquish_privs_except_capture();
4980 /* Set the initial values in the capture options. This might be overwritten
4981 by the command line parameters. */
4982 capture_opts_init(&global_capture_opts);
4983 /* We always save to a file - if no file was specified, we save to a
4985 global_capture_opts.saving_to_file = TRUE;
4986 global_capture_opts.has_ring_num_files = TRUE;
4988 /* Pass on capture_child mode for capture_opts */
4989 global_capture_opts.capture_child = capture_child;
4991 /* Now get our args */
4992 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4994 case 'h': /* Print help and exit */
4995 show_help_header("Capture network packets and dump them into a pcapng or pcap file.");
4996 print_usage(stdout);
4999 case 'v': /* Show version and exit */
5003 /*** capture option specific ***/
5004 case 'a': /* autostop criteria */
5005 case 'b': /* Ringbuffer option */
5006 case 'c': /* Capture x packets */
5007 case 'f': /* capture filter */
5008 case 'g': /* enable group read access on file(s) */
5009 case 'i': /* Use interface x */
5010 case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
5011 case 'n': /* Use pcapng format */
5012 case 'p': /* Don't capture in promiscuous mode */
5013 case 'P': /* Use pcap format */
5014 case 's': /* Set the snapshot (capture) length */
5015 case 'w': /* Write to capture file x */
5016 case 'y': /* Set the pcap data link type */
5017 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
5018 #ifdef HAVE_PCAP_REMOTE
5019 case 'u': /* Use UDP for data transfer */
5020 case 'r': /* Capture own RPCAP traffic too */
5021 case 'A': /* Authentication */
5023 #ifdef HAVE_PCAP_SETSAMPLING
5024 case 'm': /* Sampling */
5026 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
5027 case 'B': /* Buffer size */
5029 #ifdef HAVE_PCAP_CREATE
5030 case 'I': /* Monitor mode */
5032 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
5037 /*** hidden option: Wireshark child mode (using binary output messages) ***/
5039 capture_child = TRUE;
5041 /* set output pipe to binary mode, to avoid ugly text conversions */
5042 _setmode(2, O_BINARY);
5044 * optarg = the control ID, aka the PPID, currently used for the
5047 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
5048 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
5049 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
5050 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
5052 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
5053 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5054 "Signal pipe: Unable to open %s. Dead parent?",
5062 case 'q': /* Quiet */
5068 /*** all non capture option specific ***/
5069 case 'D': /* Print a list of capture devices and exit */
5070 if (!list_interfaces) {
5071 list_interfaces = TRUE;
5075 case 'L': /* Print list of link-layer types and exit */
5076 if (!(caps_queries & CAPS_QUERY_LINK_TYPES)) {
5077 caps_queries |= CAPS_QUERY_LINK_TYPES;
5081 case LONGOPT_LIST_TSTAMP_TYPES:
5082 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
5084 #ifdef HAVE_BPF_IMAGE
5085 case 'd': /* Print BPF code for capture filter and exit */
5086 if (!print_bpf_code) {
5087 print_bpf_code = TRUE;
5092 case 'S': /* Print interface statistics once a second */
5093 if (!print_statistics) {
5094 print_statistics = TRUE;
5098 case 'k': /* Set wireless channel */
5101 set_chan_arg = optarg;
5104 cmdarg_err("Only one -k flag may be specified");
5108 case 'M': /* For -D, -L, and -S, print machine-readable output */
5109 machine_readable = TRUE;
5112 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
5115 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
5118 cmdarg_err("Invalid Option: %s", argv[optind-1]);
5120 case '?': /* Bad flag - print usage message */
5129 /* user specified file name as regular command-line argument */
5130 /* XXX - use it as the capture file name (or something else)? */
5136 * Extra command line arguments were specified; complain.
5137 * XXX - interpret as capture filter, as tcpdump and tshark do?
5139 cmdarg_err("Invalid argument: %s", argv[0]);
5144 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
5147 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
5148 /* Use some default if the user hasn't specified some */
5149 /* XXX: Are these defaults good enough? */
5150 pcap_queue_byte_limit = 1000 * 1000;
5151 pcap_queue_packet_limit = 1000;
5154 print_usage(stderr);
5158 if (run_once_args > 1) {
5159 #ifdef HAVE_BPF_IMAGE
5160 cmdarg_err("Only one of -D, -L, -d, -k or -S may be supplied.");
5162 cmdarg_err("Only one of -D, -L, -k or -S may be supplied.");
5165 } else if (run_once_args == 1) {
5166 /* We're supposed to print some information, rather than
5167 to capture traffic; did they specify a ring buffer option? */
5168 if (global_capture_opts.multi_files_on) {
5169 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
5173 /* We're supposed to capture traffic; */
5175 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
5176 if (global_capture_opts.ifaces->len > 1) {
5178 global_capture_opts.use_pcapng = TRUE;
5181 if (global_capture_opts.capture_comment &&
5182 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
5183 /* XXX - for ringbuffer, should we apply the comment to each file? */
5184 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
5188 /* Was the ring buffer option specified and, if so, does it make sense? */
5189 if (global_capture_opts.multi_files_on) {
5190 /* Ring buffer works only under certain conditions:
5191 a) ring buffer does not work with temporary files;
5192 b) it makes no sense to enable the ring buffer if the maximum
5193 file size is set to "infinite". */
5194 if (global_capture_opts.save_file == NULL) {
5195 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
5196 global_capture_opts.multi_files_on = FALSE;
5198 if (!global_capture_opts.has_autostop_filesize &&
5199 !global_capture_opts.has_file_duration &&
5200 !global_capture_opts.has_file_interval &&
5201 !global_capture_opts.has_file_packets) {
5202 cmdarg_err("Ring buffer requested, but no maximum capture file size, duration "
5203 "interval, or packets were specified.");
5205 /* XXX - this must be redesigned as the conditions changed */
5206 global_capture_opts.multi_files_on = FALSE;
5209 if (global_capture_opts.has_file_duration && global_capture_opts.has_file_interval) {
5210 cmdarg_err("Ring buffer file duration and interval can't be used at the same time.");
5217 * "-D" requires no interface to be selected; it's supposed to list
5220 if (list_interfaces) {
5221 /* Get the list of interfaces */
5226 if_list = capture_interface_list(&err, &err_str, NULL);
5227 if (if_list == NULL) {
5230 * If we're being run by another program, just give them
5231 * an empty list of interfaces, don't report this as
5232 * an error; that lets them decide whether to report
5233 * this as an error or not.
5235 if (!machine_readable) {
5236 cmdarg_err("There are no interfaces on which a capture can be done");
5240 cmdarg_err("%s", err_str);
5246 if (machine_readable) /* tab-separated values to stdout */
5247 print_machine_readable_interfaces(if_list);
5249 capture_opts_print_interfaces(if_list);
5250 free_interface_list(if_list);
5255 * "-S" requires no interface to be selected; it gives statistics
5256 * for all interfaces.
5258 if (print_statistics) {
5259 status = print_statistics_loop(machine_readable);
5264 interface_options *interface_opts;
5266 if (global_capture_opts.ifaces->len != 1) {
5267 cmdarg_err("Need one interface");
5271 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
5272 status = set_80211_channel(interface_opts->name, set_chan_arg);
5277 * "-L", "-d", and capturing act on a particular interface, so we have to
5278 * have an interface; if none was specified, pick a default.
5280 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
5282 /* cmdarg_err() already called .... */
5287 /* Get the list of link-layer and/or timestamp types for the capture device. */
5288 if_capabilities_t *caps;
5289 cap_device_open_err err;
5293 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
5294 int if_caps_queries = caps_queries;
5295 interface_options *interface_opts;
5297 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, ii);
5299 caps = get_if_capabilities(interface_opts, &err, &err_str);
5301 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
5302 "%s", interface_opts->name, err_str,
5303 get_pcap_failure_secondary_error_message(err, err_str));
5307 if ((if_caps_queries & CAPS_QUERY_LINK_TYPES) && caps->data_link_types == NULL) {
5308 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts->name);
5310 } /* No timestamp types is no big deal. So we will just ignore it */
5312 if (interface_opts->monitor_mode)
5313 if_caps_queries |= CAPS_MONITOR_MODE;
5315 if (machine_readable) /* tab-separated values to stdout */
5316 /* XXX: We need to change the format and adapt consumers */
5317 print_machine_readable_if_capabilities(caps, if_caps_queries);
5319 /* XXX: We might want to print also the interface name */
5320 capture_opts_print_if_capabilities(caps, interface_opts->name, if_caps_queries);
5321 free_if_capabilities(caps);
5326 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
5327 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5328 interface_options *interface_opts;
5330 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5331 if (interface_opts->timestamp_type) {
5332 interface_opts->timestamp_type_id = pcap_tstamp_type_name_to_val(interface_opts->timestamp_type);
5333 if (interface_opts->timestamp_type_id < 0) {
5334 cmdarg_err("Invalid argument to option: --time-stamp-type=%s", interface_opts->timestamp_type);
5341 /* We're supposed to do a capture, or print the BPF code for a filter. */
5343 /* Let the user know what interfaces were chosen. */
5344 if (capture_child) {
5345 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5346 interface_options *interface_opts;
5348 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5349 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
5350 interface_opts->name);
5353 str = g_string_new("");
5355 if (global_capture_opts.ifaces->len < 2)
5357 if (global_capture_opts.ifaces->len < 4)
5360 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5361 interface_options *interface_opts;
5363 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5365 if (global_capture_opts.ifaces->len > 2) {
5366 g_string_append_printf(str, ",");
5368 g_string_append_printf(str, " ");
5369 if (j == global_capture_opts.ifaces->len - 1) {
5370 g_string_append_printf(str, "and ");
5373 g_string_append_printf(str, "'%s'", interface_opts->display_name);
5376 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
5378 fprintf(stderr, "Capturing on %s\n", str->str);
5379 g_string_free(str, TRUE);
5382 /* Process the snapshot length, as that affects the generated BPF code. */
5383 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
5385 #ifdef HAVE_BPF_IMAGE
5386 if (print_bpf_code) {
5387 show_filter_code(&global_capture_opts);
5392 /* We're supposed to do a capture. Process the ring buffer arguments. */
5393 capture_opts_trim_ring_num_files(&global_capture_opts);
5395 /* flush stderr prior to starting the main capture loop */
5398 /* Now start the capture. */
5399 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
5403 /* capture failed */
5406 return 0; /* never here, make compiler happy */
5410 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
5411 const char *message, gpointer user_data _U_)
5418 /* ignore log message, if log_level isn't interesting */
5419 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5420 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
5425 switch(log_level & G_LOG_LEVEL_MASK) {
5426 case G_LOG_LEVEL_ERROR:
5429 case G_LOG_LEVEL_CRITICAL:
5432 case G_LOG_LEVEL_WARNING:
5435 case G_LOG_LEVEL_MESSAGE:
5438 case G_LOG_LEVEL_INFO:
5441 case G_LOG_LEVEL_DEBUG:
5445 fprintf(stderr, "unknown log_level %d\n", log_level);
5447 g_assert_not_reached();
5450 /* Generate the output message */
5451 if (log_level & G_LOG_LEVEL_MESSAGE) {
5452 /* normal user messages without additional infos */
5453 msg = g_strdup_printf("%s\n", message);
5455 /* create a "timestamp" */
5457 today = localtime(&curr);
5459 /* info/debug messages with additional infos */
5461 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
5462 today->tm_hour, today->tm_min, today->tm_sec,
5463 log_domain != NULL ? log_domain : "",
5466 msg = g_strdup_printf("Time not representable %8s %s %s\n",
5467 log_domain != NULL ? log_domain : "",
5471 /* DEBUG & INFO msgs (if we're debugging today) */
5472 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
5473 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5474 #ifdef DEBUG_DUMPCAP
5475 fprintf(stderr, "%s", msg);
5478 #ifdef DEBUG_CHILD_DUMPCAP
5479 fprintf(debug_log, "%s", msg);
5487 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
5488 /* to parent especially formatted if dumpcap running as child. */
5489 if (capture_child) {
5490 sync_pipe_errmsg_to_parent(2, msg, "");
5492 fprintf(stderr, "%s", msg);
5499 /****************************************************************************************************************/
5500 /* indication report routines */
5504 report_packet_count(unsigned int packet_count)
5506 char count_str[SP_DECISIZE+1+1];
5507 static unsigned int count = 0;
5509 if (capture_child) {
5510 g_snprintf(count_str, sizeof(count_str), "%u", packet_count);
5511 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", count_str);
5512 pipe_write_block(2, SP_PACKET_COUNT, count_str);
5514 count += packet_count;
5515 fprintf(stderr, "\rPackets: %u ", count);
5516 /* stderr could be line buffered */
5522 report_new_capture_file(const char *filename)
5524 if (capture_child) {
5525 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
5526 pipe_write_block(2, SP_FILE, filename);
5530 * Prevent a SIGINFO handler from writing to the standard error
5531 * while we're doing so; instead, have it just set a flag telling
5532 * us to print that information when we're done.
5535 #endif /* SIGINFO */
5536 fprintf(stderr, "File: %s\n", filename);
5537 /* stderr could be line buffered */
5542 * Allow SIGINFO handlers to write.
5547 * If a SIGINFO handler asked us to write out capture counts, do so.
5550 report_counts_for_siginfo();
5551 #endif /* SIGINFO */
5556 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5558 interface_options *interface_opts;
5559 char tmp[MSG_MAX_LENGTH+1+6];
5561 if (i < capture_opts->ifaces->len) {
5562 if (capture_child) {
5563 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5564 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5565 pipe_write_block(2, SP_BAD_FILTER, tmp);
5568 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5569 * the error message below.
5571 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
5573 "Invalid capture filter \"%s\" for interface '%s'.\n"
5575 "That string isn't a valid capture filter (%s).\n"
5576 "See the User's Guide for a description of the capture filter syntax.",
5577 interface_opts->cfilter, interface_opts->name, errmsg);
5583 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5585 if (capture_child) {
5586 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5587 "Primary Error: %s", error_msg);
5588 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5589 "Secondary Error: %s", secondary_error_msg);
5590 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5592 cmdarg_err("%s", error_msg);
5593 if (secondary_error_msg[0] != '\0')
5594 cmdarg_err_cont("%s", secondary_error_msg);
5599 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
5601 guint32 total_drops = pcap_drops + drops + flushed;
5603 if (capture_child) {
5604 char* tmp = g_strdup_printf("%u:%s", total_drops, name);
5606 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5607 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5608 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
5609 pipe_write_block(2, SP_DROPS, tmp);
5613 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5614 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
5615 received ? 100.0 * received / (received + total_drops) : 0.0);
5616 /* stderr could be line buffered */
5622 /************************************************************************************************/
5623 /* signal_pipe handling */
5628 signal_pipe_check_running(void)
5630 /* any news from our parent? -> just stop the capture */
5634 /* if we are running standalone, no check required */
5635 if (!capture_child) {
5639 if (!sig_pipe_name || !sig_pipe_handle) {
5640 /* This shouldn't happen */
5641 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5642 "Signal pipe: No name or handle");
5647 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5648 * at this point. Should we check to see if the parent is still alive,
5649 * e.g. by using OpenProcess?
5652 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5654 if (!result || avail > 0) {
5655 /* peek failed or some bytes really available */
5656 /* (if not piping from stdin this would fail) */
5657 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5658 "Signal pipe: Stop capture: %s", sig_pipe_name);
5659 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5660 "Signal pipe: %s (%p) result: %u avail: %lu", sig_pipe_name,
5661 sig_pipe_handle, result, avail);
5664 /* pipe ok and no bytes available */
5671 * Editor modelines - https://www.wireshark.org/tools/modelines.html
5676 * indent-tabs-mode: nil
5679 * vi: set shiftwidth=4 tabstop=8 expandtab:
5680 * :indentSize=4:tabSize=8:noTabs=true: