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_NETINET_IN_H
21 #include <netinet/in.h>
28 #if defined(__APPLE__) && defined(__LP64__)
29 #include <sys/utsname.h>
35 #include <ui/cmdarg_err.h>
36 #include <wsutil/strtoi.h>
38 #include <version_info.h>
40 #include <wsutil/socket.h>
42 #ifndef HAVE_GETOPT_LONG
43 #include "wsutil/wsgetopt.h"
47 # include <sys/prctl.h>
48 # include <sys/capability.h>
51 #include "ringbuffer.h"
53 #include "caputils/capture_ifinfo.h"
54 #include "caputils/capture-pcap-util.h"
55 #include "caputils/capture-pcap-util-int.h"
57 #include "caputils/capture-wpcap.h"
60 #include "writecap/pcapio.h"
66 #include <ui/clopts_common.h>
67 #include <wsutil/privileges.h>
69 #include "sync_pipe.h"
71 #include "capture_opts.h"
72 #include <capchild/capture_session.h>
73 #include <capchild/capture_sync.h>
75 #include "wsutil/tempfile.h"
77 #include "wsutil/file_util.h"
78 #include "wsutil/cpu_info.h"
79 #include "wsutil/os_version_info.h"
80 #include "wsutil/str_util.h"
81 #include "wsutil/inet_addr.h"
82 #include "wsutil/time_util.h"
83 #include "wsutil/please_report_bug.h"
85 #include "caputils/ws80211_utils.h"
90 * Get information about libpcap format from "wiretap/libpcap.h".
91 * Get information about pcapng format from "wiretap/pcapng_module.h".
92 * XXX - can we just use pcap_open_offline() to read the pipe?
94 #include "wiretap/libpcap.h"
95 #include "wiretap/pcapng_module.h"
96 #include "wiretap/pcapng.h"
98 /**#define DEBUG_DUMPCAP**/
99 /**#define DEBUG_CHILD_DUMPCAP**/
102 #include "wsutil/win32-utils.h"
104 #include <conio.h> /* _getch() */
108 #ifdef DEBUG_CHILD_DUMPCAP
109 FILE *debug_log; /* for logging debug messages to */
110 /* a file if DEBUG_CHILD_DUMPCAP */
114 static GAsyncQueue *pcap_queue;
115 static gint64 pcap_queue_bytes;
116 static gint64 pcap_queue_packets;
117 static gint64 pcap_queue_byte_limit = 0;
118 static gint64 pcap_queue_packet_limit = 0;
120 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
122 static gchar *sig_pipe_name = NULL;
123 static HANDLE sig_pipe_handle = NULL;
124 static gboolean signal_pipe_check_running(void);
128 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
129 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
132 /** Stop a low-level capture (stops the capture child). */
133 static void capture_loop_stop(void);
134 /** Close a pipe, or socket if \a from_socket is TRUE */
135 static void cap_pipe_close(int pipe_fd, gboolean from_socket);
137 #if !defined (__linux__)
138 #ifndef HAVE_PCAP_BREAKLOOP
140 * We don't have pcap_breakloop(), which is the only way to ensure that
141 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
142 * won't, if the call to read the next packet or batch of packets is
143 * is interrupted by a signal on UN*X, just go back and try again to
146 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
147 * the signal handler, set a flag to stop capturing; however, without
148 * a guarantee of that sort, we can't guarantee that we'll stop capturing
149 * if the read will be retried and won't time out if no packets arrive.
151 * Therefore, on at least some platforms, we work around the lack of
152 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
153 * to wait for packets to arrive, so that we're probably going to be
154 * blocked in the select() when the signal arrives, and can just bail
155 * out of the loop at that point.
157 * However, we don't want to do that on BSD (because "select()" doesn't work
158 * correctly on BPF devices on at least some releases of some flavors of
159 * BSD), and we don't want to do it on Windows (because "select()" is
160 * something for sockets, not for arbitrary handles). (Note that "Windows"
161 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
162 * using Npcap, not a UNIX libpcap.)
164 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
165 * on BSD times out even if no packets have arrived, so we'll eventually
166 * exit pcap_dispatch() with an indication that no packets have arrived,
167 * and will break out of the capture loop at that point.
169 * On Windows, we can't send a SIGINT to stop capturing, so none of this
170 * applies in any case.
172 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
173 * want to include it if it's not present on this platform, however.
175 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
176 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
178 # define MUST_DO_SELECT
179 # endif /* avoid select */
180 #endif /* HAVE_PCAP_BREAKLOOP */
182 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
183 * in pcap_dispatch(); on the other hand, select() works just fine there.
184 * Hence we use a select for that come what may.
186 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
187 * internally, and, with TPACKET_V3, once that's supported, it'll
188 * support timeouts, at least as I understand the way the code works.
190 #define MUST_DO_SELECT
193 /** init the capture filter */
196 INITFILTER_BAD_FILTER,
197 INITFILTER_OTHER_ERROR
198 } initfilter_status_t;
201 STATE_EXPECT_REC_HDR,
214 typedef struct _pcap_pipe_info {
215 gboolean byte_swapped; /**< TRUE if data in the pipe is byte swapped. */
216 struct pcap_hdr hdr; /**< Pcap header when capturing from a pipe */
217 struct pcaprec_modified_hdr rechdr; /**< Pcap record header when capturing from a pipe */
220 typedef struct _pcapng_pipe_info {
221 pcapng_block_header_t bh; /**< Pcapng general block header when capturing from a pipe */
222 GArray *src_iface_to_global; /**< Int array mapping local IDB numbers to global_ld.interface_data */
223 } pcapng_pipe_info_t;
225 struct _loop_data; /* forward declaration so we can use it in the cap_pipe_dispatch function pointer */
228 * A source of packets from which we're capturing.
230 typedef struct _capture_src {
235 #ifdef MUST_DO_SELECT
236 int pcap_fd; /**< pcap file descriptor */
243 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
244 /**< capture pipe (unix only "input file") */
245 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
246 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
247 gboolean from_pcapng; /**< TRUE if we're capturing from pcapng format */
249 pcap_pipe_info_t pcap; /**< Pcap info when capturing from a pipe */
250 pcapng_pipe_info_t pcapng; /**< Pcapng info when capturing from a pipe */
253 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
255 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
256 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
257 char * cap_pipe_databuf; /**< Pointer to the data buffer we've allocated */
258 size_t cap_pipe_databuf_size; /**< Current size of the data buffer */
259 guint cap_pipe_max_pkt_size; /**< Maximum packet size allowed */
261 char * cap_pipe_buf; /**< Pointer to the buffer we read into */
262 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
263 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
265 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
266 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
268 int (*cap_pipe_dispatch)(struct _loop_data *, struct _capture_src *, char *, size_t);
269 cap_pipe_state_t cap_pipe_state;
270 cap_pipe_err_t cap_pipe_err;
273 GMutex *cap_pipe_read_mtx;
274 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
278 typedef struct _saved_idb {
280 guint interface_id; /* capture_src->interface_id for the associated SHB */
281 guint8 *idb; /* If non-NULL, IDB read from capture_src. This is an interface specified on the command line otherwise. */
286 * Global capture loop state.
288 typedef struct _loop_data {
290 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
291 int err; /**< if non-zero, error seen while capturing */
292 gint packets_captured; /**< Number of packets we have already captured */
293 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
295 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
297 GArray *pcaps; /**< Array of capture_src's on which we're capturing */
298 gboolean pcapng_passthrough; /**< We have one source and it's pcapng. Pass its SHB and IDBs through. */
299 guint8 *saved_shb; /**< SHB to write when we have one pcapng input */
300 GArray *saved_idbs; /**< Array of saved_idb_t, written when we have a new section or output file. */
301 GRWLock saved_shb_idb_lock; /**< Saved IDB RW mutex */
305 char *io_buffer; /**< Our IO buffer if we increase the size from the standard size */
306 guint64 bytes_written; /**< Bytes written for the current file. */
307 /* autostop conditions */
308 int packets_written; /**< Packets written for the current file. */
310 /* ring buffer conditions */
311 GTimer *file_duration_timer;
312 time_t next_interval_time;
316 typedef struct _pcap_queue_element {
317 capture_src *pcap_src;
319 struct pcap_pkthdr phdr;
320 pcapng_block_header_t bh;
323 } pcap_queue_element;
326 * This needs to be static, so that the SIGINT handler can clear the "go"
327 * flag and for saved_shb_idb_lock.
329 static loop_data global_ld;
332 * Timeout, in milliseconds, for reads from the stream of captured packets
333 * from a capture device.
335 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
336 * 64-bit applications, with sub-second timeouts not to work. The bug is
337 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
339 #if defined(__APPLE__) && defined(__LP64__)
340 static gboolean need_timeout_workaround;
342 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
344 #define CAP_READ_TIMEOUT 250
348 * Timeout, in microseconds, for reads from the stream of captured packets
349 * from a pipe. Pipes don't have the same problem that BPF devices do
350 * in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
351 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
352 * of the offending versions of Snow Leopard.
354 * On Windows this value is converted to milliseconds and passed to
355 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
356 * will return immediately.
359 #define PIPE_READ_TIMEOUT 100000
361 #define PIPE_READ_TIMEOUT 250000
364 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
367 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
368 const char *message, gpointer user_data _U_);
370 /* capture related options */
371 static capture_options global_capture_opts;
372 static gboolean quiet = FALSE;
373 static gboolean use_threads = FALSE;
374 static guint64 start_time;
376 static void capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
378 static void capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
380 static void capture_loop_write_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd);
381 static void capture_loop_queue_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd);
382 static void capture_loop_get_errmsg(char *errmsg, size_t errmsglen,
383 char *secondary_errmsg,
384 size_t secondary_errmsglen,
385 const char *fname, int err,
388 static void WS_NORETURN exit_main(int err);
390 static void report_new_capture_file(const char *filename);
391 static void report_packet_count(unsigned int packet_count);
392 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
393 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
394 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
396 #define MSG_MAX_LENGTH 4096
399 print_usage(FILE *output)
401 fprintf(output, "\nUsage: dumpcap [options] ...\n");
402 fprintf(output, "\n");
403 fprintf(output, "Capture interface:\n");
404 fprintf(output, " -i <interface>, --interface <interface>\n");
405 fprintf(output, " name or idx of interface (def: first non-loopback),\n"
406 " or for remote capturing, use one of these formats:\n"
407 " rpcap://<host>/<interface>\n"
408 " TCP@<host>:<port>\n");
409 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
410 fprintf(output, " -s <snaplen>, --snapshot-length <snaplen>\n");
411 #ifdef HAVE_PCAP_CREATE
412 fprintf(output, " packet snapshot length (def: appropriate maximum)\n");
414 fprintf(output, " packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
416 fprintf(output, " -p, --no-promiscuous-mode\n");
417 fprintf(output, " don't capture in promiscuous mode\n");
418 #ifdef HAVE_PCAP_CREATE
419 fprintf(output, " -I, --monitor-mode capture in monitor mode, if available\n");
421 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
422 fprintf(output, " -B <buffer size>, --buffer-size <buffer size>\n");
423 fprintf(output, " size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
425 fprintf(output, " -y <link type>, --linktype <link type>\n");
426 fprintf(output, " link layer type (def: first appropriate)\n");
427 fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
428 fprintf(output, " -D, --list-interfaces print list of interfaces and exit\n");
429 fprintf(output, " -L, --list-data-link-types\n");
430 fprintf(output, " print list of link-layer types of iface and exit\n");
431 fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
432 #ifdef HAVE_BPF_IMAGE
433 fprintf(output, " -d print generated BPF code for capture filter\n");
435 fprintf(output, " -k <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
436 fprintf(output, " set channel on wifi interface\n");
437 fprintf(output, " -S print statistics for each interface once per second\n");
438 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
439 fprintf(output, "\n");
440 #ifdef HAVE_PCAP_REMOTE
441 fprintf(output, "RPCAP options:\n");
442 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
443 fprintf(output, " -u use UDP for RPCAP data transfer\n");
444 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
445 #ifdef HAVE_PCAP_SETSAMPLING
446 fprintf(output, " -m <sampling type> use packet sampling\n");
447 fprintf(output, " count:NUM - capture one packet of every NUM\n");
448 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
451 fprintf(output, "Stop conditions:\n");
452 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
453 fprintf(output, " -a <autostop cond.> ..., --autostop <autostop cond.> ...\n");
454 fprintf(output, " duration:NUM - stop after NUM seconds\n");
455 fprintf(output, " filesize:NUM - stop this file after NUM kB\n");
456 fprintf(output, " files:NUM - stop after NUM files\n");
457 fprintf(output, " packets:NUM - stop after NUM packets\n");
458 /*fprintf(output, "\n");*/
459 fprintf(output, "Output (files):\n");
460 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
461 fprintf(output, " -g enable group read access on the output file(s)\n");
462 fprintf(output, " -b <ringbuffer opt.> ..., --ring-buffer <ringbuffer opt.>\n");
463 fprintf(output, " duration:NUM - switch to next file after NUM secs\n");
464 fprintf(output, " filesize:NUM - switch to next file after NUM kB\n");
465 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
466 fprintf(output, " packets:NUM - ringbuffer: replace after NUM packets\n");
467 fprintf(output, " interval:NUM - switch to next file when the time is\n");
468 fprintf(output, " an exact multiple of NUM secs\n");
469 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
470 fprintf(output, " -P use libpcap format instead of pcapng\n");
471 fprintf(output, " --capture-comment <comment>\n");
472 fprintf(output, " add a capture comment to the output file\n");
473 fprintf(output, " (only for pcapng)\n");
474 fprintf(output, "\n");
475 fprintf(output, "Miscellaneous:\n");
476 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
477 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
478 fprintf(output, " within dumpcap\n");
479 fprintf(output, " -t use a separate thread per interface\n");
480 fprintf(output, " -q don't report packet capture counts\n");
481 fprintf(output, " -v, --version print version information and exit\n");
482 fprintf(output, " -h, --help display this help and exit\n");
483 fprintf(output, "\n");
485 fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
486 fprintf(output, "You might want to enable it by executing:\n");
487 fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
488 fprintf(output, "Note that this can make your system less secure!\n");
489 fprintf(output, "\n");
491 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
492 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
493 fprintf(output, "\n");
494 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
498 * Report an error in command-line arguments.
499 * If we're a capture child, send a message back to the parent, otherwise
503 dumpcap_cmdarg_err(const char *fmt, va_list ap)
507 /* Generate a 'special format' message back to parent */
508 msg = g_strdup_vprintf(fmt, ap);
509 sync_pipe_errmsg_to_parent(2, msg, "");
512 fprintf(stderr, "dumpcap: ");
513 vfprintf(stderr, fmt, ap);
514 fprintf(stderr, "\n");
519 * Report additional information for an error in command-line arguments.
520 * If we're a capture child, send a message back to the parent, otherwise
524 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
528 msg = g_strdup_vprintf(fmt, ap);
529 sync_pipe_errmsg_to_parent(2, msg, "");
532 vfprintf(stderr, fmt, ap);
533 fprintf(stderr, "\n");
539 #if 0 /* Set to enable capability debugging */
540 /* see 'man cap_to_text()' for explanation of output */
541 /* '=' means 'all= ' ie: no capabilities */
542 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
544 print_caps(const char *pfx) {
545 cap_t caps = cap_get_proc();
546 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
547 "%s: EUID: %d Capabilities: %s", pfx,
548 geteuid(), cap_to_text(caps, NULL));
552 print_caps(const char *pfx _U_) {
557 relinquish_all_capabilities(void)
559 /* Drop any and all capabilities this process may have. */
560 /* Allowed whether or not process has any privileges. */
561 cap_t caps = cap_init(); /* all capabilities initialized to off */
562 print_caps("Pre-clear");
563 if (cap_set_proc(caps)) {
564 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
566 print_caps("Post-clear");
572 * Platform-dependent suggestions for fixing permissions.
574 #if defined(__linux__)
575 #define PLATFORM_PERMISSIONS_SUGGESTION \
577 "On Debian and Debian derivatives such as Ubuntu, if you have " \
578 "installed Wireshark from a package, try running" \
580 " sudo dpkg-reconfigure wireshark-common" \
582 "selecting \"<Yes>\" in response to the question" \
584 " Should non-superusers be able to capture packets?" \
586 "adding yourself to the \"wireshark\" group by running" \
588 " sudo usermod -a -G wireshark {your username}" \
590 "and then logging out and logging back in again."
591 #elif defined(__APPLE__)
592 #define PLATFORM_PERMISSIONS_SUGGESTION \
594 "If you installed Wireshark using the package from wireshark.org, "\
595 "Try re-installing it and checking the box for the \"Set capture " \
596 "permissions on startup\" item."
598 #define PLATFORM_PERMISSIONS_SUGGESTION
602 get_pcap_failure_secondary_error_message(cap_device_open_err open_err,
604 const char *open_err_str
606 const char* open_err_str _U_
612 * On Windows, first make sure they *have* Npcap installed.
616 "In order to capture packets, Npcap or WinPcap must be installed. See\n"
618 " https://nmap.org/npcap/\n"
620 "for a downloadable version of Npcap and for instructions on how to\n"
626 * Now deal with ancient versions of libpcap that, on HP-UX, don't
627 * correctly figure out how to open a device given the device name.
630 /* HP-UX-specific suggestion. */
631 static const char ppamsg[] = "can't find PPA for ";
633 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0) {
635 "You are running (T)Wireshark with a version of the libpcap library\n"
636 "that doesn't handle HP-UX network devices well; this means that\n"
637 "(T)Wireshark may not be able to capture packets.\n"
639 "To fix this, you should install libpcap 0.6.2, or a later version\n"
640 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
641 "packaged binary form from the Software Porting And Archive Centre\n"
642 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
643 "at the URL lists a number of mirror sites.";
648 * OK, now just return a largely platform-independent error that might
649 * have platform-specific suggestions at the end (for example, suggestions
650 * for how to get permission to capture).
652 if (open_err == CAP_DEVICE_OPEN_ERR_GENERIC) {
654 * We don't know what kind of error it is, so throw all the
655 * suggestions at the user.
658 "Please check to make sure you have sufficient permissions, and that you have "
659 "the proper interface or pipe specified."
660 PLATFORM_PERMISSIONS_SUGGESTION;
661 } else if (open_err == CAP_DEVICE_OPEN_ERR_PERMISSIONS) {
663 * This is a permissions error, so no need to specify any other
667 "Please check to make sure you have sufficient permissions."
668 PLATFORM_PERMISSIONS_SUGGESTION;
671 * This is not a permissons error, so no need to suggest
672 * checking permissions.
675 "Please check that you have the proper interface or pipe specified.";
680 get_capture_device_open_failure_messages(cap_device_open_err open_err,
681 const char *open_err_str,
683 char *errmsg, size_t errmsg_len,
684 char *secondary_errmsg,
685 size_t secondary_errmsg_len)
687 g_snprintf(errmsg, (gulong) errmsg_len,
688 "The capture session could not be initiated on interface '%s' (%s).",
689 iface, open_err_str);
690 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, "%s",
691 get_pcap_failure_secondary_error_message(open_err, open_err_str));
695 compile_capture_filter(const char *iface, pcap_t *pcap_h,
696 struct bpf_program *fcode, const char *cfilter)
698 bpf_u_int32 netnum, netmask;
699 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
701 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
703 * Well, we can't get the netmask for this interface; it's used
704 * only for filters that check for broadcast IP addresses, so
705 * we just punt and use 0. It might be nice to warn the user,
706 * but that's a pain in a GUI application, as it'd involve popping
707 * up a message box, and it's not clear how often this would make
708 * a difference (only filters that check for IP broadcast addresses
712 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
717 * Sigh. Older versions of libpcap don't properly declare the
718 * third argument to pcap_compile() as a const pointer. Cast
722 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
728 #ifdef HAVE_BPF_IMAGE
730 show_filter_code(capture_options *capture_opts)
732 interface_options *interface_opts;
734 cap_device_open_err open_err;
735 gchar open_err_str[PCAP_ERRBUF_SIZE];
736 char errmsg[MSG_MAX_LENGTH+1];
737 char secondary_errmsg[MSG_MAX_LENGTH+1];
738 struct bpf_program fcode;
739 struct bpf_insn *insn;
743 for (j = 0; j < capture_opts->ifaces->len; j++) {
744 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, j);
745 pcap_h = open_capture_device(capture_opts, interface_opts,
746 CAP_READ_TIMEOUT, &open_err, &open_err_str);
747 if (pcap_h == NULL) {
748 /* Open failed; get messages */
749 get_capture_device_open_failure_messages(open_err, open_err_str,
750 interface_opts->name,
751 errmsg, sizeof errmsg,
753 sizeof secondary_errmsg);
754 /* And report them */
755 report_capture_error(errmsg, secondary_errmsg);
759 /* Set the link-layer type. */
760 if (!set_pcap_datalink(pcap_h, interface_opts->linktype, interface_opts->name,
761 errmsg, sizeof errmsg,
762 secondary_errmsg, sizeof secondary_errmsg)) {
764 report_capture_error(errmsg, secondary_errmsg);
768 /* OK, try to compile the capture filter. */
769 if (!compile_capture_filter(interface_opts->name, pcap_h, &fcode,
770 interface_opts->cfilter)) {
771 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_h));
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)
1139 ws_cleanup_sockets();
1142 /* can be helpful for debugging */
1143 #ifdef DEBUG_DUMPCAP
1144 printf("Press any key\n");
1150 if (ringbuf_is_initialized()) {
1151 /* save_file is managed by ringbuffer, be sure to release the memory and
1152 * avoid capture_opts_cleanup from double-freeing 'save_file'. */
1154 global_capture_opts.save_file = NULL;
1157 capture_opts_cleanup(&global_capture_opts);
1163 * If we were linked with libcap (not related to libpcap), make sure we have
1164 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1165 * (See comment in main() for details)
1168 relinquish_privs_except_capture(void)
1170 /* If 'started_with_special_privs' (ie: suid) then enable for
1171 * ourself the NET_ADMIN and NET_RAW capabilities and then
1172 * drop our suid privileges.
1174 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1175 * stuff we don't need (and shouldn't have).
1176 * CAP_NET_RAW: Packet capture (raw sockets).
1179 if (started_with_special_privs()) {
1180 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1181 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1183 cap_t caps = cap_init(); /* all capabilities initialized to off */
1185 print_caps("Pre drop, pre set");
1187 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1188 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1191 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1192 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1194 if (cap_set_proc(caps)) {
1195 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1197 print_caps("Pre drop, post set");
1199 relinquish_special_privs_perm();
1201 print_caps("Post drop, pre set");
1202 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1203 if (cap_set_proc(caps)) {
1204 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1206 print_caps("Post drop, post set");
1212 #endif /* HAVE_LIBCAP */
1214 /* Take care of byte order in the libpcap headers read from pipes.
1215 * (function taken from wiretap/libpcap.c) */
1217 cap_pipe_adjust_pcap_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1220 /* Byte-swap the record header fields. */
1221 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1222 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1223 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1224 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1227 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1228 swapped, in order to match the BPF header layout.
1230 Unfortunately, some files were, according to a comment in the "libpcap"
1231 source, written with version 2.3 in their headers but without the
1232 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1233 would make no sense - we assume that we need to swap them. */
1234 if (hdr->version_major == 2 &&
1235 (hdr->version_minor < 3 ||
1236 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1239 temp = rechdr->orig_len;
1240 rechdr->orig_len = rechdr->incl_len;
1241 rechdr->incl_len = temp;
1245 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1249 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1253 return recv(pipe_fd, buf, (int)sz, 0);
1258 return ws_read(pipe_fd, buf, sz);
1264 * Thread function that reads from a pipe and pushes the data
1265 * to the main application thread.
1268 * XXX Right now we use async queues for basic signaling. The main thread
1269 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1270 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1271 * Iff the read is successful cap_pipe_read pushes an item onto
1272 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1273 * the queues themselves (yet).
1275 * We might want to move some of the cap_pipe_dispatch logic here so that
1276 * we can let cap_thread_read run independently, queuing up multiple reads
1277 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1279 static void *cap_thread_read(void *arg)
1281 capture_src *pcap_src;
1284 DWORD last_err, bytes_read;
1289 pcap_src = (capture_src *)arg;
1290 while (pcap_src->cap_pipe_err == PIPOK) {
1291 g_async_queue_pop(pcap_src->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1292 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1294 while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1295 if ((pcap_src->from_cap_socket)
1302 b = cap_pipe_read(pcap_src->cap_pipe_fd, pcap_src->cap_pipe_buf+bytes_read,
1303 pcap_src->cap_pipe_bytes_to_read - bytes_read, pcap_src->from_cap_socket);
1306 pcap_src->cap_pipe_err = PIPEOF;
1310 pcap_src->cap_pipe_err = PIPERR;
1321 /* If we try to use read() on a named pipe on Windows with partial
1322 * data it appears to return EOF.
1325 res = ReadFile(pcap_src->cap_pipe_h, pcap_src->cap_pipe_buf+bytes_read,
1326 pcap_src->cap_pipe_bytes_to_read - bytes_read,
1331 last_err = GetLastError();
1332 if (last_err == ERROR_MORE_DATA) {
1334 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1335 pcap_src->cap_pipe_err = PIPEOF;
1339 pcap_src->cap_pipe_err = PIPERR;
1342 } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1343 pcap_src->cap_pipe_err = PIPEOF;
1350 pcap_src->cap_pipe_bytes_read = bytes_read;
1351 if (pcap_src->cap_pipe_bytes_read >= pcap_src->cap_pipe_bytes_to_read) {
1352 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1354 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1356 /* Post to queue if we didn't read enough data as the main thread waits for the message */
1357 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1358 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1359 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1361 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1366 /* Provide select() functionality for a single file descriptor
1367 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1369 * Returns the same values as select.
1372 cap_pipe_select(int pipe_fd)
1375 struct timeval timeout;
1378 FD_SET(pipe_fd, &rfds);
1380 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1381 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1383 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1386 #define DEF_TCP_PORT 19000
1389 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, size_t errmsgl)
1391 struct sockaddr_storage sa;
1394 /* Skip the initial "TCP@" in the pipename. */
1395 if (ws_socket_ptoa(&sa, pipename + 4, DEF_TCP_PORT) < 0) {
1396 g_snprintf(errmsg, (gulong)errmsgl,
1397 "The capture session could not be initiated because"
1398 "\"%s\" is not a valid socket specification", pipename);
1399 pcap_src->cap_pipe_err = PIPERR;
1403 if ((fd = (int)socket(sa.ss_family, SOCK_STREAM, 0)) < 0 ||
1404 connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
1405 g_snprintf(errmsg, (gulong)errmsgl,
1406 "The capture session could not be initiated due to the socket error: \n"
1408 " %s", win32strerror(WSAGetLastError()));
1410 " %d: %s", errno, g_strerror(errno));
1412 pcap_src->cap_pipe_err = PIPERR;
1415 cap_pipe_close(fd, TRUE);
1419 pcap_src->from_cap_socket = TRUE;
1423 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1427 cap_pipe_close(int pipe_fd, gboolean from_socket)
1431 closesocket(pipe_fd);
1434 (void) from_socket; /* Mark unused, similar to Q_UNUSED */
1439 /** Read bytes from a capture source, which is assumed to be a pipe.
1441 * Returns -1, or the number of bytes read similar to read(2).
1442 * Sets pcap_src->cap_pipe_err on error or EOF.
1445 cap_pipe_read_data_bytes(capture_src *pcap_src, char *errmsg, size_t errmsgl)
1448 int fd = pcap_src->cap_pipe_fd;
1450 DWORD sz, bytes_read = 0;
1452 ssize_t sz, bytes_read = 0;
1456 #ifdef LOG_CAPTURE_VERBOSE
1457 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_read_data_bytes read %lu of %lu",
1458 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1460 sz = pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read;
1461 while (bytes_read < sz) {
1463 g_snprintf(errmsg, (gulong)errmsgl, "Invalid file descriptor.");
1464 pcap_src->cap_pipe_err = PIPNEXIST;
1468 sel_ret = cap_pipe_select(fd);
1470 g_snprintf(errmsg, (gulong)errmsgl,
1471 "Unexpected error from select: %s.", g_strerror(errno));
1472 pcap_src->cap_pipe_err = PIPERR;
1474 } else if (sel_ret > 0) {
1475 b = cap_pipe_read(fd, pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read+bytes_read,
1476 sz-bytes_read, pcap_src->from_cap_socket);
1479 g_snprintf(errmsg, (gulong)errmsgl,
1480 "End of file on pipe during cap_pipe_read.");
1481 pcap_src->cap_pipe_err = PIPEOF;
1484 DWORD lastError = WSAGetLastError();
1486 g_snprintf(errmsg, (gulong)errmsgl,
1487 "Error on pipe data during cap_pipe_read: %s.",
1488 win32strerror(lastError));
1490 g_snprintf(errmsg, (gulong)errmsgl,
1491 "Error on pipe data during cap_pipe_read: %s.",
1494 pcap_src->cap_pipe_err = PIPERR;
1501 pcap_src->cap_pipe_bytes_read += bytes_read;
1502 #ifdef LOG_CAPTURE_VERBOSE
1503 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_read_data_bytes read %lu of %lu",
1504 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1509 /* Some forward declarations for breaking up cap_pipe_open_live for pcap and pcapng formats */
1510 static void pcap_pipe_open_live(int fd, capture_src *pcap_src,
1511 struct pcap_hdr *hdr,
1512 char *errmsg, size_t errmsgl,
1513 char *secondary_errmsg, size_t secondary_errmsgl);
1514 static void pcapng_pipe_open_live(int fd, capture_src *pcap_src,
1515 char *errmsg, size_t errmsgl);
1516 static int pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src,
1517 char *errmsg, size_t errmsgl);
1519 /* For problems that are probably Not Our Fault. */
1520 static char not_our_bug[] =
1521 "Please report this to the developers of the program writing to the pipe.";
1523 /* Mimic pcap_open_live() for pipe captures
1525 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1526 * open it, and read the header.
1528 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1529 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1531 cap_pipe_open_live(char *pipename,
1532 capture_src *pcap_src,
1534 char *errmsg, size_t errmsgl,
1535 char *secondary_errmsg, size_t secondary_errmsgl)
1538 ws_statb64 pipe_stat;
1539 struct sockaddr_un sa;
1542 guintptr extcap_pipe_handle;
1544 gboolean extcap_pipe = FALSE;
1546 int fd = -1, sel_ret;
1549 pcap_src->cap_pipe_fd = -1;
1551 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1554 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1557 * XXX - this blocks until a pcap per-file header has been written to
1558 * the pipe, so it could block indefinitely.
1560 if (strcmp(pipename, "-") == 0) {
1562 fd = 0; /* read from stdin */
1564 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1566 } else if (!strncmp(pipename, "TCP@", 4)) {
1567 if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1572 if ( g_strrstr(pipename, EXTCAP_PIPE_PREFIX) != NULL )
1575 if (ws_stat64(pipename, &pipe_stat) < 0) {
1576 if (errno == ENOENT || errno == ENOTDIR)
1577 pcap_src->cap_pipe_err = PIPNEXIST;
1579 g_snprintf(errmsg, (gulong)errmsgl,
1580 "The capture session could not be initiated "
1581 "due to error getting information on pipe/socket: %s.", g_strerror(errno));
1582 pcap_src->cap_pipe_err = PIPERR;
1586 if (S_ISFIFO(pipe_stat.st_mode)) {
1587 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1589 g_snprintf(errmsg, (gulong)errmsgl,
1590 "The capture session could not be initiated "
1591 "due to error on pipe open: %s.", g_strerror(errno));
1592 pcap_src->cap_pipe_err = PIPERR;
1595 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1596 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1598 g_snprintf(errmsg, (gulong)errmsgl,
1599 "The capture session could not be initiated "
1600 "due to error on socket create: %s.", g_strerror(errno));
1601 pcap_src->cap_pipe_err = PIPERR;
1604 sa.sun_family = AF_UNIX;
1606 * The Single UNIX Specification says:
1608 * The size of sun_path has intentionally been left undefined.
1609 * This is because different implementations use different sizes.
1610 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1611 * of 104. Since most implementations originate from BSD versions,
1612 * the size is typically in the range 92 to 108.
1614 * Applications should not assume a particular length for sun_path
1615 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1619 * The <sys/un.h> header shall define the sockaddr_un structure,
1620 * which shall include at least the following members:
1622 * sa_family_t sun_family Address family.
1623 * char sun_path[] Socket pathname.
1625 * so we assume that it's an array, with a specified size,
1626 * and that the size reflects the maximum path length.
1628 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1629 /* Path name too long */
1630 g_snprintf(errmsg, (gulong)errmsgl,
1631 "The capture session coud not be initiated "
1632 "due to error on socket connect: Path name too long.");
1633 pcap_src->cap_pipe_err = PIPERR;
1637 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1639 g_snprintf(errmsg, (gulong)errmsgl,
1640 "The capture session coud not be initiated "
1641 "due to error on socket connect: %s.", g_strerror(errno));
1642 pcap_src->cap_pipe_err = PIPERR;
1647 if (S_ISCHR(pipe_stat.st_mode)) {
1649 * Assume the user specified an interface on a system where
1650 * interfaces are in /dev. Pretend we haven't seen it.
1652 pcap_src->cap_pipe_err = PIPNEXIST;
1654 g_snprintf(errmsg, (gulong)errmsgl,
1655 "The capture session could not be initiated because\n"
1656 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1657 pcap_src->cap_pipe_err = PIPERR;
1663 if (sscanf(pipename, EXTCAP_PIPE_PREFIX "%" G_GUINTPTR_FORMAT, &extcap_pipe_handle) == 1)
1665 /* The client is already connected to extcap pipe.
1666 * We have inherited the handle from parent process.
1669 pcap_src->cap_pipe_h = (HANDLE)extcap_pipe_handle;
1673 #define PIPE_STR "\\pipe\\"
1674 /* Under Windows, named pipes _must_ have the form
1675 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1677 pncopy = g_strdup(pipename);
1678 if ((pos = strstr(pncopy, "\\\\")) == pncopy) {
1679 pos = strchr(pncopy + 3, '\\');
1680 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1687 g_snprintf(errmsg, (gulong)errmsgl,
1688 "The capture session could not be initiated because\n"
1689 "\"%s\" is neither an interface nor a pipe.", pipename);
1690 pcap_src->cap_pipe_err = PIPNEXIST;
1695 /* Wait for the pipe to appear */
1697 pcap_src->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1698 OPEN_EXISTING, 0, NULL);
1700 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE)
1703 if (GetLastError() != ERROR_PIPE_BUSY) {
1704 g_snprintf(errmsg, (gulong)errmsgl,
1705 "The capture session on \"%s\" could not be started "
1706 "due to error on pipe open: %s.",
1707 pipename, win32strerror(GetLastError()));
1708 pcap_src->cap_pipe_err = PIPERR;
1712 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1713 g_snprintf(errmsg, (gulong)errmsgl,
1714 "The capture session on \"%s\" timed out during "
1716 pipename, win32strerror(GetLastError()));
1717 pcap_src->cap_pipe_err = PIPERR;
1725 pcap_src->from_cap_pipe = TRUE;
1728 * We start with a 2KB buffer for packet data, which should be
1729 * large enough for most regular network packets. We increase it,
1730 * up to the maximum size we allow, as necessary.
1732 pcap_src->cap_pipe_databuf = (char*)g_malloc(2048);
1733 pcap_src->cap_pipe_databuf_size = 2048;
1736 if (pcap_src->from_cap_socket)
1739 /* read the pcap header */
1741 while (bytes_read < sizeof magic) {
1742 sel_ret = cap_pipe_select(fd);
1744 g_snprintf(errmsg, (gulong)errmsgl,
1745 "Unexpected error from select: %s.",
1748 } else if (sel_ret > 0) {
1749 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1750 sizeof magic-bytes_read,
1751 pcap_src->from_cap_socket);
1752 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1753 if (extcap_pipe && b <= 0)
1758 g_snprintf(errmsg, (gulong)errmsgl,
1759 "End of file on pipe magic during open.");
1761 g_snprintf(errmsg, (gulong)errmsgl,
1762 "Error on pipe magic during open: %s.",
1772 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
1774 pcap_src->cap_pipe_buf = (char *) &magic;
1775 pcap_src->cap_pipe_bytes_read = 0;
1776 pcap_src->cap_pipe_bytes_to_read = sizeof(magic);
1777 /* We don't have to worry about cap_pipe_read_mtx here */
1778 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1779 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1780 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1781 if (pcap_src->cap_pipe_bytes_read <= 0 && extcap_pipe)
1784 if (pcap_src->cap_pipe_bytes_read <= 0) {
1785 if (pcap_src->cap_pipe_bytes_read == 0)
1786 g_snprintf(errmsg, (gulong)errmsgl,
1787 "End of file on pipe magic during open.");
1789 g_snprintf(errmsg, (gulong)errmsgl,
1790 "Error on pipe magic during open: %s.",
1799 case PCAP_NSEC_MAGIC:
1800 /* Host that wrote it has our byte order, and was running
1801 a program using either standard or ss990417 libpcap. */
1802 pcap_src->cap_pipe_info.pcap.byte_swapped = FALSE;
1803 pcap_src->cap_pipe_modified = FALSE;
1804 pcap_src->ts_nsec = magic == PCAP_NSEC_MAGIC;
1806 case PCAP_MODIFIED_MAGIC:
1807 /* Host that wrote it has our byte order, but was running
1808 a program using either ss990915 or ss991029 libpcap. */
1809 pcap_src->cap_pipe_info.pcap.byte_swapped = FALSE;
1810 pcap_src->cap_pipe_modified = TRUE;
1812 case PCAP_SWAPPED_MAGIC:
1813 case PCAP_SWAPPED_NSEC_MAGIC:
1814 /* Host that wrote it has a byte order opposite to ours,
1815 and was running a program using either standard or
1816 ss990417 libpcap. */
1817 pcap_src->cap_pipe_info.pcap.byte_swapped = TRUE;
1818 pcap_src->cap_pipe_modified = FALSE;
1819 pcap_src->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
1821 case PCAP_SWAPPED_MODIFIED_MAGIC:
1822 /* Host that wrote it out has a byte order opposite to
1823 ours, and was running a program using either ss990915
1824 or ss991029 libpcap. */
1825 pcap_src->cap_pipe_info.pcap.byte_swapped = TRUE;
1826 pcap_src->cap_pipe_modified = TRUE;
1828 case BLOCK_TYPE_SHB:
1829 /* This isn't pcap, it's pcapng. */
1830 pcap_src->from_pcapng = TRUE;
1831 pcap_src->cap_pipe_dispatch = pcapng_pipe_dispatch;
1832 pcap_src->cap_pipe_info.pcapng.src_iface_to_global = g_array_new(FALSE, FALSE, sizeof(guint32));
1833 global_capture_opts.use_pcapng = TRUE; /* we can only output in pcapng format */
1834 pcapng_pipe_open_live(fd, pcap_src, errmsg, errmsgl);
1837 /* Not a pcap type we know about, or not pcap at all. */
1838 g_snprintf(errmsg, (gulong)errmsgl,
1839 "Data written to the pipe is neither in a supported pcap format nor in pcapng format.");
1840 g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl, "%s",
1845 pcap_pipe_open_live(fd, pcap_src, (struct pcap_hdr *) hdr, errmsg, errmsgl,
1846 secondary_errmsg, secondary_errmsgl);
1850 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1851 pcap_src->cap_pipe_err = PIPERR;
1852 cap_pipe_close(fd, pcap_src->from_cap_socket);
1853 pcap_src->cap_pipe_fd = -1;
1855 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1860 pcap_pipe_open_live(int fd,
1861 capture_src *pcap_src,
1862 struct pcap_hdr *hdr,
1863 char *errmsg, size_t errmsgl,
1864 char *secondary_errmsg, size_t secondary_errmsgl)
1870 if (pcap_src->from_cap_socket)
1873 /* Read the rest of the header */
1875 while (bytes_read < sizeof(struct pcap_hdr)) {
1876 sel_ret = cap_pipe_select(fd);
1878 g_snprintf(errmsg, (gulong)errmsgl,
1879 "Unexpected error from select: %s.",
1882 } else if (sel_ret > 0) {
1883 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
1884 sizeof(struct pcap_hdr) - bytes_read,
1885 pcap_src->from_cap_socket);
1888 g_snprintf(errmsg, (gulong)errmsgl,
1889 "End of file on pipe header during open.");
1891 g_snprintf(errmsg, (gulong)errmsgl,
1892 "Error on pipe header during open: %s.",
1894 g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl,
1904 pcap_src->cap_pipe_buf = (char *) hdr;
1905 pcap_src->cap_pipe_bytes_read = 0;
1906 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1907 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1908 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1909 if (pcap_src->cap_pipe_bytes_read <= 0) {
1910 if (pcap_src->cap_pipe_bytes_read == 0)
1911 g_snprintf(errmsg, (gulong)errmsgl,
1912 "End of file on pipe header during open.");
1914 g_snprintf(errmsg, (gulong)errmsgl,
1915 "Error on pipe header header during open: %s.",
1917 g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl, "%s",
1924 if (pcap_src->cap_pipe_info.pcap.byte_swapped) {
1925 /* Byte-swap the header fields about which we care. */
1926 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
1927 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
1928 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
1929 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
1931 pcap_src->linktype = hdr->network;
1932 /* Pick the appropriate maximum packet size for the link type */
1933 switch (pcap_src->linktype) {
1935 case 231: /* DLT_DBUS */
1936 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_DBUS;
1939 case 279: /* DLT_EBHSCR */
1940 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_EBHSCR;
1943 case 249: /* DLT_USBPCAP */
1944 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_USBPCAP;
1948 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
1952 if (hdr->version_major < 2) {
1953 g_snprintf(errmsg, (gulong)errmsgl,
1954 "The old pcap format version %d.%d is not supported.",
1955 hdr->version_major, hdr->version_minor);
1956 g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl, "%s",
1961 pcap_src->cap_pipe_fd = fd;
1965 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcap_pipe_open_live: error %s", errmsg);
1966 pcap_src->cap_pipe_err = PIPERR;
1967 cap_pipe_close(fd, pcap_src->from_cap_socket);
1968 pcap_src->cap_pipe_fd = -1;
1970 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1974 /* Read the pcapng section header block */
1976 pcapng_read_shb(capture_src *pcap_src,
1980 pcapng_section_header_block_t shb;
1983 if (pcap_src->from_cap_socket)
1986 pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t) + sizeof(pcapng_section_header_block_t);
1987 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
1993 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + sizeof(pcapng_block_header_t);
1994 pcap_src->cap_pipe_bytes_read = 0;
1995 pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_section_header_block_t);
1996 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1997 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1998 if (pcap_src->cap_pipe_bytes_read <= 0) {
1999 if (pcap_src->cap_pipe_bytes_read == 0)
2000 g_snprintf(errmsg, (gulong)errmsgl,
2001 "End of file on pipe section header during open.");
2003 g_snprintf(errmsg, (gulong)errmsgl,
2004 "Error on pipe section header during open: %s.",
2008 /* Continuing with STATE_EXPECT_DATA requires reading into cap_pipe_databuf at offset cap_pipe_bytes_read */
2009 pcap_src->cap_pipe_bytes_read = sizeof(pcapng_block_header_t) + sizeof(pcapng_section_header_block_t);
2012 memcpy(&shb, pcap_src->cap_pipe_databuf + sizeof(pcapng_block_header_t), sizeof(pcapng_section_header_block_t));
2016 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng SHB MAGIC");
2018 case PCAPNG_SWAPPED_MAGIC:
2019 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng SHB SWAPPED MAGIC");
2021 * pcapng sources can contain all sorts of block types.
2022 * Rather than add a bunch of complexity to this code (which is
2023 * often privileged), punt and tell the user to swap bytes
2026 * XXX - punting means that the Wireshark test suite must be
2029 * 1) have both little-endian and big-endian versions of
2030 * all pcapng files piped to dumpcap;
2032 * 2) pipe the appropriate file to dumpcap, depending on
2033 * the byte order of the host on which the tests are
2036 * as per comments in bug 15772 and 15754.
2038 * Are we *really* certain that the complexity added would be
2039 * significant enough to make adding it a security risk? And
2040 * why would this code even be running with any elevated
2041 * privileges if you're capturing from a pipe? We should not
2042 * only have given up all additional privileges if we're reading
2043 * from a pipe, we should give them up in such a fashion that
2044 * we can't reclaim them.
2046 #if G_BYTE_ORDER == G_BIG_ENDIAN
2047 #define OUR_ENDIAN "big"
2048 #define IFACE_ENDIAN "little"
2050 #define OUR_ENDIAN "little"
2051 #define IFACE_ENDIAN "big"
2053 g_snprintf(errmsg, (gulong)errmsgl,
2054 "Interface %u is " IFACE_ENDIAN " endian but we're " OUR_ENDIAN " endian.",
2055 pcap_src->interface_id);
2058 /* Not a pcapng type we know about, or not pcapng at all. */
2059 g_snprintf(errmsg, (gulong)errmsgl,
2060 "Unrecognized pcapng format or not pcapng data.");
2064 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
2066 /* Setup state to capture any options following the section header block */
2067 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2073 * Save IDB blocks for playback whenever we change output files.
2074 * Rewrite EPB and ISB interface IDs.
2077 pcapng_adjust_block(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd)
2079 switch(bh->block_type) {
2080 case BLOCK_TYPE_SHB:
2082 if (global_ld.pcapng_passthrough) {
2084 * We have a single pcapng input. We pass the SHB through when
2085 * writing a single output file and for the first ring buffer
2086 * file. We need to save it for the second and subsequent ring
2089 g_free(global_ld.saved_shb);
2090 global_ld.saved_shb = (guint8 *) g_memdup(pd, bh->block_total_length);
2093 * We're dealing with one section at a time, so we can (and must)
2094 * get rid of our old IDBs.
2096 for (unsigned i = 0; i < global_ld.saved_idbs->len; i++) {
2097 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, i);
2098 g_free(idb_source->idb);
2100 g_array_set_size(global_ld.saved_idbs, 0);
2103 * We have a new SHB from this capture source. We need to keep
2104 * global_ld.saved_idbs intact, so we mark IDBs we previously
2105 * collected from this source as deleted.
2107 for (unsigned i = 0; i < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len; i++) {
2108 guint32 iface_id = g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, guint32, i);
2109 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, iface_id);
2110 g_assert(idb_source->interface_id == pcap_src->interface_id);
2111 g_free(idb_source->idb);
2112 memset(idb_source, 0, sizeof(saved_idb_t));
2113 idb_source->deleted = TRUE;
2114 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: deleted pcapng IDB %u", G_STRFUNC, iface_id);
2117 g_array_set_size(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, 0);
2120 case BLOCK_TYPE_IDB:
2123 * Always gather IDBs. We can remove them or mark them as deleted
2124 * when we get a new SHB.
2126 saved_idb_t idb_source = { 0 };
2127 idb_source.interface_id = pcap_src->interface_id;
2128 idb_source.idb_len = bh->block_total_length;
2129 idb_source.idb = (guint8 *) g_memdup(pd, idb_source.idb_len);
2130 g_array_append_val(global_ld.saved_idbs, idb_source);
2131 guint32 iface_id = global_ld.saved_idbs->len - 1;
2132 g_array_append_val(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, iface_id);
2133 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: mapped pcapng IDB %u -> %u from source %u",
2134 G_STRFUNC, pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len - 1, iface_id, pcap_src->interface_id);
2137 case BLOCK_TYPE_EPB:
2138 case BLOCK_TYPE_ISB:
2140 if (global_ld.pcapng_passthrough) {
2141 /* Our input and output interface IDs are the same. */
2144 /* The interface ID is the first 32-bit field after the BH for both EPBs and ISBs. */
2146 memcpy(&iface_id, pd + sizeof(pcapng_block_header_t), 4);
2147 if (iface_id < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len) {
2148 memcpy(pd + sizeof(pcapng_block_header_t),
2149 &g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, guint32, iface_id), 4);
2151 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);
2164 pcapng_pipe_open_live(int fd,
2165 capture_src *pcap_src,
2169 guint32 type = BLOCK_TYPE_SHB;
2170 pcapng_block_header_t *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2172 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_open_live: fd %d", fd);
2174 if (pcap_src->from_cap_socket)
2177 memcpy(pcap_src->cap_pipe_databuf, &type, sizeof(guint32));
2178 /* read the rest of the pcapng general block header */
2179 pcap_src->cap_pipe_bytes_read = sizeof(guint32);
2180 pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t);
2181 pcap_src->cap_pipe_fd = fd;
2182 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2185 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(pcapng_block_header_t));
2189 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
2191 bh->block_type = type;
2192 pcap_src->cap_pipe_buf = (char *) &bh->block_total_length;
2193 pcap_src->cap_pipe_bytes_read = 0;
2194 pcap_src->cap_pipe_bytes_to_read = sizeof(bh->block_total_length);
2195 /* We don't have to worry about cap_pipe_read_mtx here */
2196 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2197 g_async_queue_pop(pcap_src->cap_pipe_done_q);
2198 if (pcap_src->cap_pipe_bytes_read <= 0) {
2199 if (pcap_src->cap_pipe_bytes_read == 0)
2200 g_snprintf(errmsg, (gulong)errmsgl,
2201 "End of file on pipe block_total_length during open.");
2203 g_snprintf(errmsg, (gulong)errmsgl,
2204 "Error on pipe block_total_length during open: %s.",
2208 pcap_src->cap_pipe_bytes_read = sizeof(pcapng_block_header_t);
2209 memcpy(pcap_src->cap_pipe_databuf, bh, sizeof(pcapng_block_header_t));
2210 pcap_src->cap_pipe_fd = fd;
2213 if (pcapng_read_shb(pcap_src, errmsg, errmsgl)) {
2220 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_open_live: error %s", errmsg);
2221 pcap_src->cap_pipe_err = PIPERR;
2222 cap_pipe_close(fd, pcap_src->from_cap_socket);
2223 pcap_src->cap_pipe_fd = -1;
2225 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2229 /* We read one record from the pipe, take care of byte order in the record
2230 * header, write the record to the capture file, and update capture statistics. */
2232 pcap_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2234 struct pcap_pkthdr phdr;
2235 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2242 pcap_pipe_info_t *pcap_info = &pcap_src->cap_pipe_info.pcap;
2244 #ifdef LOG_CAPTURE_VERBOSE
2245 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcap_pipe_dispatch");
2248 switch (pcap_src->cap_pipe_state) {
2250 case STATE_EXPECT_REC_HDR:
2252 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2255 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2256 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_modified ?
2257 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2258 pcap_src->cap_pipe_bytes_read = 0;
2261 pcap_src->cap_pipe_buf = (char *) &pcap_info->rechdr;
2262 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2263 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2268 case STATE_READ_REC_HDR:
2270 if (pcap_src->from_cap_socket)
2273 b = cap_pipe_read(pcap_src->cap_pipe_fd, ((char *)&pcap_info->rechdr)+pcap_src->cap_pipe_bytes_read,
2274 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read, pcap_src->from_cap_socket);
2277 result = PD_PIPE_EOF;
2279 result = PD_PIPE_ERR;
2282 pcap_src->cap_pipe_bytes_read += b;
2286 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2287 if (pcap_src->cap_pipe_err == PIPEOF) {
2288 result = PD_PIPE_EOF;
2290 } else if (pcap_src->cap_pipe_err == PIPERR) {
2291 result = PD_PIPE_ERR;
2299 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2301 result = PD_REC_HDR_READ;
2304 case STATE_EXPECT_DATA:
2306 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2309 pcap_src->cap_pipe_state = STATE_READ_DATA;
2310 pcap_src->cap_pipe_bytes_to_read = pcap_info->rechdr.hdr.incl_len;
2311 pcap_src->cap_pipe_bytes_read = 0;
2314 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2315 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2316 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2321 case STATE_READ_DATA:
2323 if (pcap_src->from_cap_socket)
2326 b = cap_pipe_read(pcap_src->cap_pipe_fd,
2327 pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read,
2328 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read,
2329 pcap_src->from_cap_socket);
2332 result = PD_PIPE_EOF;
2334 result = PD_PIPE_ERR;
2337 pcap_src->cap_pipe_bytes_read += b;
2342 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2343 if (pcap_src->cap_pipe_err == PIPEOF) {
2344 result = PD_PIPE_EOF;
2346 } else if (pcap_src->cap_pipe_err == PIPERR) {
2347 result = PD_PIPE_ERR;
2355 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2357 result = PD_DATA_READ;
2361 g_snprintf(errmsg, (gulong)errmsgl,
2362 "pcap_pipe_dispatch: invalid state");
2365 } /* switch (pcap_src->cap_pipe_state) */
2368 * We've now read as much data as we were expecting, so process it.
2372 case PD_REC_HDR_READ:
2373 /* We've read the header. Take care of byte order. */
2374 cap_pipe_adjust_pcap_header(pcap_src->cap_pipe_info.pcap.byte_swapped, &pcap_info->hdr,
2375 &pcap_info->rechdr.hdr);
2376 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_max_pkt_size) {
2378 * The record contains more data than the advertised/allowed in the
2379 * pcap header, do not try to read more data (do not change to
2380 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2381 * instead stop with an error.
2383 g_snprintf(errmsg, (gulong)errmsgl, "Frame %u too long (%d bytes)",
2384 ld->packets_captured+1, pcap_info->rechdr.hdr.incl_len);
2388 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_databuf_size) {
2390 * Grow the buffer to the packet size, rounded up to a power of
2393 new_bufsize = pcap_info->rechdr.hdr.incl_len;
2395 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2398 new_bufsize |= new_bufsize >> 1;
2399 new_bufsize |= new_bufsize >> 2;
2400 new_bufsize |= new_bufsize >> 4;
2401 new_bufsize |= new_bufsize >> 8;
2402 new_bufsize |= new_bufsize >> 16;
2404 pcap_src->cap_pipe_databuf = (char*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2405 pcap_src->cap_pipe_databuf_size = new_bufsize;
2409 * The record has some data following the header, try to read it next
2412 if (pcap_info->rechdr.hdr.incl_len) {
2413 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2418 * No data following the record header? Then no more data needs to be
2419 * read and we will fallthrough and emit an empty packet.
2423 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2424 phdr.ts.tv_sec = pcap_info->rechdr.hdr.ts_sec;
2425 phdr.ts.tv_usec = pcap_info->rechdr.hdr.ts_usec;
2426 phdr.caplen = pcap_info->rechdr.hdr.incl_len;
2427 phdr.len = pcap_info->rechdr.hdr.orig_len;
2430 capture_loop_queue_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2432 capture_loop_write_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2434 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2438 pcap_src->cap_pipe_err = PIPEOF;
2442 g_snprintf(errmsg, (gulong)errmsgl, "Error reading from pipe: %s",
2444 win32strerror(GetLastError()));
2453 pcap_src->cap_pipe_err = PIPERR;
2454 /* Return here rather than inside the switch to prevent GCC warning */
2459 pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2461 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2467 pcapng_block_header_t *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2469 #ifdef LOG_CAPTURE_VERBOSE
2470 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch");
2473 switch (pcap_src->cap_pipe_state) {
2475 case STATE_EXPECT_REC_HDR:
2476 #ifdef LOG_CAPTURE_VERBOSE
2477 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_EXPECT_REC_HDR");
2480 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2483 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2484 pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t);
2485 pcap_src->cap_pipe_bytes_read = 0;
2488 if (!pcap_src->from_cap_socket) {
2489 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2490 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2492 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2497 case STATE_READ_REC_HDR:
2498 #ifdef LOG_CAPTURE_VERBOSE
2499 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_READ_REC_HDR");
2502 if (pcap_src->from_cap_socket) {
2504 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2509 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2510 if (pcap_src->cap_pipe_err == PIPEOF) {
2511 result = PD_PIPE_EOF;
2513 } else if (pcap_src->cap_pipe_err == PIPERR) {
2514 result = PD_PIPE_ERR;
2522 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2525 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(pcapng_block_header_t));
2526 result = PD_REC_HDR_READ;
2529 case STATE_EXPECT_DATA:
2530 #ifdef LOG_CAPTURE_VERBOSE
2531 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_EXPECT_DATA");
2534 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2536 pcap_src->cap_pipe_state = STATE_READ_DATA;
2537 pcap_src->cap_pipe_bytes_to_read = bh->block_total_length;
2540 if (!pcap_src->from_cap_socket) {
2541 pcap_src->cap_pipe_bytes_to_read -= pcap_src->cap_pipe_bytes_read;
2542 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + pcap_src->cap_pipe_bytes_read;
2543 pcap_src->cap_pipe_bytes_read = 0;
2544 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2546 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2551 case STATE_READ_DATA:
2552 #ifdef LOG_CAPTURE_VERBOSE
2553 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_READ_DATA");
2556 if (pcap_src->from_cap_socket) {
2558 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2564 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2565 if (pcap_src->cap_pipe_err == PIPEOF) {
2566 result = PD_PIPE_EOF;
2568 } else if (pcap_src->cap_pipe_err == PIPERR) {
2569 result = PD_PIPE_ERR;
2577 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2580 result = PD_DATA_READ;
2584 g_snprintf(errmsg, (gulong)errmsgl,
2585 "pcapng_pipe_dispatch: invalid state");
2588 } /* switch (pcap_src->cap_pipe_state) */
2591 * We've now read as much data as we were expecting, so process it.
2595 case PD_REC_HDR_READ:
2596 if (bh->block_type == BLOCK_TYPE_SHB) {
2597 /* we need to read ahead to get the endianess before getting the block type and length */
2598 pcapng_read_shb(pcap_src, errmsg, errmsgl);
2602 if (bh->block_total_length > pcap_src->cap_pipe_max_pkt_size) {
2604 * The record contains more data than the advertised/allowed in the
2605 * pcapng header, do not try to read more data (do not change to
2606 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2607 * instead stop with an error.
2609 g_snprintf(errmsg, (gulong)errmsgl, "Frame %u too long (%d bytes)",
2610 ld->packets_captured+1, bh->block_total_length);
2614 if (bh->block_total_length > pcap_src->cap_pipe_databuf_size) {
2616 * Grow the buffer to the packet size, rounded up to a power of
2619 new_bufsize = bh->block_total_length;
2621 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2624 new_bufsize |= new_bufsize >> 1;
2625 new_bufsize |= new_bufsize >> 2;
2626 new_bufsize |= new_bufsize >> 4;
2627 new_bufsize |= new_bufsize >> 8;
2628 new_bufsize |= new_bufsize >> 16;
2630 pcap_src->cap_pipe_databuf = (guchar*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2631 pcap_src->cap_pipe_databuf_size = new_bufsize;
2634 /* The record always has at least the block total length following the header */
2635 if (bh->block_total_length < sizeof(pcapng_block_header_t)+sizeof(guint32)) {
2636 g_snprintf(errmsg, (gulong)errmsgl,
2637 "malformed pcapng block_total_length < minimum");
2638 pcap_src->cap_pipe_err = PIPEOF;
2641 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2646 capture_loop_queue_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
2648 capture_loop_write_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
2650 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2654 pcap_src->cap_pipe_err = PIPEOF;
2658 g_snprintf(errmsg, (gulong)errmsgl, "Error reading from pipe: %s",
2660 win32strerror(GetLastError()));
2669 pcap_src->cap_pipe_err = PIPERR;
2670 /* Return here rather than inside the switch to prevent GCC warning */
2674 /** Open the capture input file (pcap or capture pipe).
2675 * Returns TRUE if it succeeds, FALSE otherwise. */
2677 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2678 char *errmsg, size_t errmsg_len,
2679 char *secondary_errmsg, size_t secondary_errmsg_len)
2681 cap_device_open_err open_err;
2682 gchar open_err_str[PCAP_ERRBUF_SIZE];
2683 gchar *sync_msg_str;
2684 interface_options *interface_opts;
2685 capture_src *pcap_src;
2688 if ((use_threads == FALSE) &&
2689 (capture_opts->ifaces->len > 1)) {
2690 g_snprintf(errmsg, (gulong) errmsg_len,
2691 "Using threads is required for capturing on multiple interfaces.");
2695 int pcapng_src_count = 0;
2696 for (i = 0; i < capture_opts->ifaces->len; i++) {
2697 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
2698 pcap_src = (capture_src *)g_malloc0(sizeof (capture_src));
2699 if (pcap_src == NULL) {
2700 g_snprintf(errmsg, (gulong) errmsg_len,
2701 "Could not allocate memory.");
2706 * Add our pcapng interface entry. This will be deleted further
2707 * down if pcapng_passthrough == TRUE.
2709 saved_idb_t idb_source = { 0 };
2710 idb_source.interface_id = i;
2711 g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
2712 g_array_append_val(global_ld.saved_idbs, idb_source);
2713 g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
2714 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: saved capture_opts IDB %u",
2717 #ifdef MUST_DO_SELECT
2718 pcap_src->pcap_fd = -1;
2720 pcap_src->interface_id = i;
2721 pcap_src->linktype = -1;
2723 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2725 pcap_src->cap_pipe_fd = -1;
2726 pcap_src->cap_pipe_dispatch = pcap_pipe_dispatch;
2727 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2728 pcap_src->cap_pipe_err = PIPOK;
2730 pcap_src->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2731 g_mutex_init(pcap_src->cap_pipe_read_mtx);
2732 pcap_src->cap_pipe_pending_q = g_async_queue_new();
2733 pcap_src->cap_pipe_done_q = g_async_queue_new();
2735 g_array_append_val(ld->pcaps, pcap_src);
2737 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts->name);
2738 pcap_src->pcap_h = open_capture_device(capture_opts, interface_opts,
2739 CAP_READ_TIMEOUT, &open_err, &open_err_str);
2741 if (pcap_src->pcap_h != NULL) {
2742 /* we've opened "iface" as a network device */
2744 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2745 /* Find out if we're getting nanosecond-precision time stamps */
2746 pcap_src->ts_nsec = have_high_resolution_timestamp(pcap_src->pcap_h);
2749 #if defined(HAVE_PCAP_SETSAMPLING)
2750 if (interface_opts->sampling_method != CAPTURE_SAMP_NONE) {
2751 struct pcap_samp *samp;
2753 if ((samp = pcap_setsampling(pcap_src->pcap_h)) != NULL) {
2754 switch (interface_opts->sampling_method) {
2755 case CAPTURE_SAMP_BY_COUNT:
2756 samp->method = PCAP_SAMP_1_EVERY_N;
2759 case CAPTURE_SAMP_BY_TIMER:
2760 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2764 sync_msg_str = g_strdup_printf(
2765 "Unknown sampling method %d specified,\n"
2766 "continue without packet sampling",
2767 interface_opts->sampling_method);
2768 report_capture_error("Couldn't set the capture "
2769 "sampling", sync_msg_str);
2770 g_free(sync_msg_str);
2772 samp->value = interface_opts->sampling_param;
2774 report_capture_error("Couldn't set the capture sampling",
2775 "Cannot get packet sampling data structure");
2780 /* setting the data link type only works on real interfaces */
2781 if (!set_pcap_datalink(pcap_src->pcap_h, interface_opts->linktype,
2782 interface_opts->name,
2784 secondary_errmsg, secondary_errmsg_len)) {
2787 pcap_src->linktype = get_pcap_datalink(pcap_src->pcap_h, interface_opts->name);
2789 /* We couldn't open "iface" as a network device. */
2790 /* Try to open it as a pipe */
2791 gboolean pipe_err = FALSE;
2792 cap_pipe_open_live(interface_opts->name, pcap_src,
2793 &pcap_src->cap_pipe_info.pcap.hdr,
2795 secondary_errmsg, secondary_errmsg_len);
2798 if (pcap_src->from_cap_socket) {
2800 if (pcap_src->cap_pipe_fd == -1) {
2805 if (pcap_src->cap_pipe_h == INVALID_HANDLE_VALUE) {
2812 if (pcap_src->cap_pipe_err == PIPNEXIST) {
2814 * We tried opening as an interface, and that failed,
2815 * so we tried to open it as a pipe, but the pipe
2816 * doesn't exist. Report the error message for
2819 get_capture_device_open_failure_messages(open_err,
2821 interface_opts->name,
2825 secondary_errmsg_len);
2828 * Else pipe (or file) does exist and cap_pipe_open_live() has
2833 /* cap_pipe_open_live() succeeded; don't want
2834 error message from pcap_open_live() */
2835 open_err_str[0] = '\0';
2839 /* XXX - will this work for tshark? */
2840 #ifdef MUST_DO_SELECT
2841 if (!pcap_src->from_cap_pipe) {
2842 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2843 pcap_src->pcap_fd = pcap_get_selectable_fd(pcap_src->pcap_h);
2845 pcap_src->pcap_fd = pcap_fileno(pcap_src->pcap_h);
2850 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2851 returned a warning; print it, but keep capturing. */
2852 if (open_err_str[0] != '\0') {
2853 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2854 report_capture_error(sync_msg_str, "");
2855 g_free(sync_msg_str);
2857 if (pcap_src->from_pcapng) {
2861 if (capture_opts->ifaces->len == 1 && pcapng_src_count == 1) {
2862 ld->pcapng_passthrough = TRUE;
2863 g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
2864 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: Clearing %u interfaces for passthrough",
2865 G_STRFUNC, global_ld.saved_idbs->len);
2866 g_array_set_size(global_ld.saved_idbs, 0);
2867 g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
2870 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2871 /* to remove any suid privileges. */
2872 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2873 /* (euid/egid have already previously been set to ruid/rgid. */
2874 /* (See comment in main() for details) */
2876 relinquish_special_privs_perm();
2878 relinquish_all_capabilities();
2883 /* close the capture input file (pcap or capture pipe) */
2884 static void capture_loop_close_input(loop_data *ld)
2887 capture_src *pcap_src;
2889 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2891 for (i = 0; i < ld->pcaps->len; i++) {
2892 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2893 /* Pipe, or capture device? */
2894 if (pcap_src->from_cap_pipe) {
2895 /* Pipe. If open, close the capture pipe "input file". */
2896 if (pcap_src->cap_pipe_fd >= 0) {
2897 cap_pipe_close(pcap_src->cap_pipe_fd, pcap_src->from_cap_socket);
2898 pcap_src->cap_pipe_fd = -1;
2901 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE) {
2902 CloseHandle(pcap_src->cap_pipe_h);
2903 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2906 if (pcap_src->cap_pipe_databuf != NULL) {
2907 /* Free the buffer. */
2908 g_free(pcap_src->cap_pipe_databuf);
2909 pcap_src->cap_pipe_databuf = NULL;
2911 if (pcap_src->from_pcapng) {
2912 g_array_free(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, TRUE);
2913 pcap_src->cap_pipe_info.pcapng.src_iface_to_global = NULL;
2916 /* Capture device. If open, close the pcap_t. */
2917 if (pcap_src->pcap_h != NULL) {
2918 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_src->pcap_h);
2919 pcap_close(pcap_src->pcap_h);
2920 pcap_src->pcap_h = NULL;
2929 /* init the capture filter */
2930 static initfilter_status_t
2931 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2932 const gchar * name, const gchar * cfilter)
2934 struct bpf_program fcode;
2936 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2938 /* capture filters only work on real interfaces */
2939 if (cfilter && !from_cap_pipe) {
2940 /* A capture filter was specified; set it up. */
2941 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2942 /* Treat this specially - our caller might try to compile this
2943 as a display filter and, if that succeeds, warn the user that
2944 the display and capture filter syntaxes are different. */
2945 return INITFILTER_BAD_FILTER;
2947 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2948 #ifdef HAVE_PCAP_FREECODE
2949 pcap_freecode(&fcode);
2951 return INITFILTER_OTHER_ERROR;
2953 #ifdef HAVE_PCAP_FREECODE
2954 pcap_freecode(&fcode);
2958 return INITFILTER_NO_ERROR;
2962 * Write the dumpcap pcapng SHB and IDBs if needed.
2963 * Called from capture_loop_init_output and do_file_switch_or_stop.
2966 capture_loop_init_pcapng_output(capture_options *capture_opts, loop_data *ld)
2968 g_rw_lock_reader_lock (&ld->saved_shb_idb_lock);
2970 if (ld->pcapng_passthrough && !ld->saved_shb) {
2971 /* We have a single pcapng capture interface and this is the first or only output file. */
2972 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: skipping dumpcap SHB and IDBs in favor of source", G_STRFUNC);
2973 g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
2977 gboolean successful = TRUE;
2979 GString *os_info_str = g_string_new("");
2981 get_os_version_info(os_info_str);
2983 if (ld->saved_shb) {
2984 /* We have a single pcapng capture interface and multiple output files. */
2986 pcapng_block_header_t bh;
2988 memcpy(&bh, ld->saved_shb, sizeof(pcapng_block_header_t));
2990 successful = pcapng_write_block(ld->pdh, ld->saved_shb, bh.block_total_length, &ld->bytes_written, &err);
2992 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: wrote saved passthrough SHB %d", G_STRFUNC, successful);
2994 GString *cpu_info_str = g_string_new("");
2995 get_cpu_info(cpu_info_str);
2997 successful = pcapng_write_section_header_block(ld->pdh,
2998 (const char *)capture_opts->capture_comment, /* Comment */
2999 cpu_info_str->str, /* HW */
3000 os_info_str->str, /* OS */
3001 get_appname_and_version(),
3002 -1, /* section_length */
3005 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: wrote dumpcap SHB %d", G_STRFUNC, successful);
3006 g_string_free(cpu_info_str, TRUE);
3009 for (unsigned i = 0; successful && (i < ld->saved_idbs->len); i++) {
3010 saved_idb_t idb_source = g_array_index(ld->saved_idbs, saved_idb_t, i);
3011 if (idb_source.deleted) {
3013 * Our interface is out of scope. Suppose we're writing multiple
3014 * files and a source switches sections. We currently write dummy
3017 * File 1: IDB0, IDB1, IDB2
3018 * [ The source of IDBs 1 and 2 writes an SHB with two new IDBs ]
3019 * [ We switch output files ]
3020 * File 2: IDB0, dummy IDB, dummy IDB, IDB3, IDB4
3022 * It might make more sense to write the original data so that
3023 * so that our IDB lists are more consistent across files.
3025 successful = pcapng_write_interface_description_block(global_ld.pdh,
3026 "Interface went out of scope", /* OPT_COMMENT 1 */
3027 "dummy", /* IDB_NAME 2 */
3028 "Dumpcap dummy interface", /* IDB_DESCRIPTION 3 */
3029 NULL, /* IDB_FILTER 11 */
3030 os_info_str->str, /* IDB_OS 12 */
3033 &(global_ld.bytes_written),
3034 0, /* IDB_IF_SPEED 8 */
3035 6, /* IDB_TSRESOL 9 */
3037 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: skipping deleted pcapng IDB %u", G_STRFUNC, i);
3038 } else if (idb_source.idb && idb_source.idb_len) {
3039 successful = pcapng_write_block(global_ld.pdh, idb_source.idb, idb_source.idb_len, &ld->bytes_written, &err);
3040 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: wrote pcapng IDB %d", G_STRFUNC, successful);
3041 } else if (idb_source.interface_id < capture_opts->ifaces->len) {
3042 unsigned if_id = idb_source.interface_id;
3043 interface_options *interface_opts = &g_array_index(capture_opts->ifaces, interface_options, if_id);
3044 capture_src *pcap_src = g_array_index(ld->pcaps, capture_src *, if_id);
3045 if (pcap_src->from_cap_pipe) {
3046 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3048 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3050 successful = pcapng_write_interface_description_block(global_ld.pdh,
3051 NULL, /* OPT_COMMENT 1 */
3052 interface_opts->name, /* IDB_NAME 2 */
3053 interface_opts->descr, /* IDB_DESCRIPTION 3 */
3054 interface_opts->cfilter, /* IDB_FILTER 11 */
3055 os_info_str->str, /* IDB_OS 12 */
3058 &(global_ld.bytes_written),
3059 0, /* IDB_IF_SPEED 8 */
3060 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3062 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: wrote capture_opts IDB %d: %d", G_STRFUNC, if_id, successful);
3065 g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3067 g_string_free(os_info_str, TRUE);
3072 /* set up to write to the already-opened capture output file/files */
3074 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
3077 gboolean successful;
3079 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
3081 if ((capture_opts->use_pcapng == FALSE) &&
3082 (capture_opts->ifaces->len > 1)) {
3083 g_snprintf(errmsg, errmsg_len,
3084 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
3088 /* Set up to write to the capture file. */
3089 if (capture_opts->multi_files_on) {
3090 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
3092 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
3093 if (ld->pdh == NULL) {
3096 size_t buffsize = IO_BUF_SIZE;
3097 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
3100 if (ws_fstat64(ld->save_file_fd, &statb) == 0) {
3101 if (statb.st_blksize > IO_BUF_SIZE) {
3102 buffsize = statb.st_blksize;
3106 /* Increase the size of the IO buffer */
3107 ld->io_buffer = (char *)g_malloc(buffsize);
3108 setvbuf(ld->pdh, ld->io_buffer, _IOFBF, buffsize);
3109 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output: buffsize %zu", buffsize);
3113 if (capture_opts->use_pcapng) {
3114 successful = capture_loop_init_pcapng_output(capture_opts, ld);
3116 capture_src *pcap_src;
3117 pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
3118 if (pcap_src->from_cap_pipe) {
3119 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3121 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3123 successful = libpcap_write_file_header(ld->pdh, pcap_src->linktype, pcap_src->snaplen,
3124 pcap_src->ts_nsec, &ld->bytes_written, &err);
3129 g_free(ld->io_buffer);
3130 ld->io_buffer = NULL;
3134 if (ld->pdh == NULL) {
3135 /* We couldn't set up to write to the capture file. */
3136 /* XXX - use cf_open_error_message from tshark instead? */
3138 g_snprintf(errmsg, errmsg_len,
3139 "The file to which the capture would be"
3140 " saved (\"%s\") could not be opened: Error %d.",
3141 capture_opts->save_file, err);
3143 g_snprintf(errmsg, errmsg_len,
3144 "The file to which the capture would be"
3145 " saved (\"%s\") could not be opened: %s.",
3146 capture_opts->save_file, g_strerror(err));
3155 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
3159 capture_src *pcap_src;
3160 guint64 end_time = create_timestamp();
3163 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
3165 if (capture_opts->multi_files_on) {
3166 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
3168 if (capture_opts->use_pcapng) {
3169 for (i = 0; i < global_ld.pcaps->len; i++) {
3170 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3171 if (!pcap_src->from_cap_pipe) {
3172 guint64 isb_ifrecv, isb_ifdrop;
3173 struct pcap_stat stats;
3175 if (pcap_stats(pcap_src->pcap_h, &stats) >= 0) {
3176 isb_ifrecv = pcap_src->received;
3177 isb_ifdrop = stats.ps_drop + pcap_src->dropped + pcap_src->flushed;
3179 isb_ifrecv = G_MAXUINT64;
3180 isb_ifdrop = G_MAXUINT64;
3182 pcapng_write_interface_statistics_block(ld->pdh,
3185 "Counters provided by dumpcap",
3194 if (fclose(ld->pdh) == EOF) {
3195 if (err_close != NULL) {
3202 g_free(ld->io_buffer);
3203 ld->io_buffer = NULL;
3208 /* dispatch incoming packets (pcap or capture pipe)
3210 * Waits for incoming packets to be available, and calls pcap_dispatch()
3211 * to cause them to be processed.
3213 * Returns the number of packets which were processed.
3215 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3216 * packet-batching behaviour does not cause packets to get held back
3220 capture_loop_dispatch(loop_data *ld,
3221 char *errmsg, int errmsg_len, capture_src *pcap_src)
3224 gint packet_count_before;
3227 packet_count_before = ld->packets_captured;
3228 if (pcap_src->from_cap_pipe) {
3229 /* dispatch from capture pipe */
3230 #ifdef LOG_CAPTURE_VERBOSE
3231 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3234 if (pcap_src->from_cap_socket) {
3236 sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
3238 if (sel_ret < 0 && errno != EINTR) {
3239 g_snprintf(errmsg, errmsg_len,
3240 "Unexpected error from select: %s", g_strerror(errno));
3241 report_capture_error(errmsg, please_report_bug());
3247 /* Windows does not have select() for pipes. */
3248 /* Proceed with _dispatch() which waits for cap_pipe_done_q
3249 * notification from cap_thread_read() when ReadFile() on
3250 * the pipe has read enough bytes. */
3256 * "select()" says we can read from the pipe without blocking
3258 inpkts = pcap_src->cap_pipe_dispatch(ld, pcap_src, errmsg, errmsg_len);
3260 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: src %u pipe reached EOF or err, rcv: %u drop: %u flush: %u",
3261 G_STRFUNC, pcap_src->interface_id, pcap_src->received, pcap_src->dropped, pcap_src->flushed);
3262 g_assert(pcap_src->cap_pipe_err != PIPOK);
3268 /* dispatch from pcap */
3269 #ifdef MUST_DO_SELECT
3271 * If we have "pcap_get_selectable_fd()", we use it to get the
3272 * descriptor on which to select; if that's -1, it means there
3273 * is no descriptor on which you can do a "select()" (perhaps
3274 * because you're capturing on a special device, and that device's
3275 * driver unfortunately doesn't support "select()", in which case
3276 * we don't do the select - which means it might not be possible
3277 * to stop a capture until a packet arrives. If that's unacceptable,
3278 * plead with whoever supplies the software for that device to add
3279 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3280 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3281 * later, so it can use pcap_breakloop().
3283 #ifdef LOG_CAPTURE_VERBOSE
3284 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3286 if (pcap_src->pcap_fd != -1) {
3287 sel_ret = cap_pipe_select(pcap_src->pcap_fd);
3290 * "select()" says we can read from it without blocking; go for
3293 * We don't have pcap_breakloop(), so we only process one packet
3294 * per pcap_dispatch() call, to allow a signal to stop the
3295 * processing immediately, rather than processing all packets
3296 * in a batch before quitting.
3299 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3301 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3305 /* Error, rather than pcap_breakloop(). */
3306 pcap_src->pcap_err = TRUE;
3308 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3311 if (sel_ret < 0 && errno != EINTR) {
3312 g_snprintf(errmsg, errmsg_len,
3313 "Unexpected error from select: %s", g_strerror(errno));
3314 report_capture_error(errmsg, please_report_bug());
3320 #endif /* MUST_DO_SELECT */
3322 /* dispatch from pcap without select */
3324 #ifdef LOG_CAPTURE_VERBOSE
3325 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3329 * On Windows, we don't support asynchronously telling a process to
3330 * stop capturing; instead, we check for an indication on a pipe
3331 * after processing packets. We therefore process only one packet
3332 * at a time, so that we can check the pipe after every packet.
3335 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3337 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3341 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3343 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3348 /* Error, rather than pcap_breakloop(). */
3349 pcap_src->pcap_err = TRUE;
3351 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3353 #else /* pcap_next_ex */
3354 #ifdef LOG_CAPTURE_VERBOSE
3355 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3357 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3360 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3361 * see https://wiki.wireshark.org/CaptureSetup/WinPcapRemote
3362 * This should be fixed in the WinPcap 4.0 alpha release.
3364 * For reference, an example remote interface:
3365 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3368 /* emulate dispatch from pcap */
3371 struct pcap_pkthdr *pkt_header;
3376 (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
3378 capture_loop_queue_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3380 capture_loop_write_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3385 pcap_src->pcap_err = TRUE;
3389 #endif /* pcap_next_ex */
3393 #ifdef LOG_CAPTURE_VERBOSE
3394 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3397 return ld->packets_captured - packet_count_before;
3401 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3402 * want to grab only the characters between the '{' and '}' delimiters.
3404 * Returns a GString that must be freed with g_string_free(). */
3406 isolate_uuid(const char *iface)
3411 ptr = strchr(iface, '{');
3413 return g_string_new(iface);
3414 gstr = g_string_new(ptr + 1);
3416 ptr = strchr(gstr->str, '}');
3420 gstr = g_string_truncate(gstr, ptr - gstr->str);
3425 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3426 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3428 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3429 char *errmsg, int errmsg_len)
3431 gchar *capfile_name;
3432 gchar *prefix, *suffix;
3433 gboolean is_tempfile;
3434 GError *err_tempfile = NULL;
3436 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3437 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3439 if (capture_opts->save_file != NULL) {
3440 /* We return to the caller while the capture is in progress.
3441 * Therefore we need to take a copy of save_file in
3442 * case the caller destroys it after we return.
3444 capfile_name = g_strdup(capture_opts->save_file);
3446 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3447 if (capture_opts->multi_files_on) {
3448 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3449 g_snprintf(errmsg, errmsg_len,
3450 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3451 g_free(capfile_name);
3454 if (strcmp(capfile_name, "-") == 0) {
3455 /* write to stdout */
3458 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3459 _setmode(1, O_BINARY);
3462 /* Try to open the specified FIFO for use as a capture buffer.
3463 Do *not* create it if it doesn't exist. There's nothing
3464 to truncate. If we need to read it, We Have A Problem. */
3465 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY, 0);
3467 } /* if (...output_to_pipe ... */
3470 if (capture_opts->multi_files_on) {
3471 /* ringbuffer is enabled */
3472 *save_file_fd = ringbuf_init(capfile_name,
3473 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3474 capture_opts->group_read_access);
3476 /* capfile_name is unused as the ringbuffer provides its own filename. */
3477 if (*save_file_fd != -1) {
3478 g_free(capfile_name);
3479 capfile_name = NULL;
3482 /* Try to open/create the specified file for use as a capture buffer. */
3483 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY|O_TRUNC|O_CREAT,
3484 (capture_opts->group_read_access) ? 0640 : 0600);
3487 is_tempfile = FALSE;
3489 /* Choose a random name for the temporary capture buffer */
3490 if (global_capture_opts.ifaces->len > 1) {
3492 * More than one interface; just use the number of interfaces
3493 * to generate the temporary file name prefix.
3495 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3498 * One interface; use its description, if it has one, to generate
3499 * the temporary file name, otherwise use its name.
3502 const interface_options *interface_opts;
3504 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
3507 * Do we have a description?
3509 if (interface_opts->descr) {
3513 * Strip off any stuff we shouldn't use in the file name,
3514 * by getting the last component of what would be a file
3517 basename = g_path_get_basename(interface_opts->descr);
3520 * No - use the name.
3522 * Strip off any stuff we shouldn't use in the file name,
3523 * by getting the last component of what would be a file
3526 basename = g_path_get_basename(interface_opts->name);
3529 * This is Windows, where we might have an ugly GUID-based
3532 * If it's an ugly GUID-based name, use the generic portion
3533 * of the interface GUID to form the basis of the filename.
3535 if (strncmp("NPF_{", basename, 5) == 0) {
3537 * We have a GUID-based name; extract the GUID digits
3538 * as the basis of the filename.
3541 iface = isolate_uuid(basename);
3543 basename = g_strdup(iface->str);
3544 g_string_free(iface, TRUE);
3548 /* generate the temp file name prefix */
3549 prefix = g_strconcat("wireshark_", basename, NULL);
3553 /* Generate the appropriate suffix. */
3554 if (capture_opts->use_pcapng) {
3559 *save_file_fd = create_tempfile(&capfile_name, prefix, suffix, &err_tempfile);
3564 /* did we fail to open the output file? */
3565 if (*save_file_fd == -1) {
3567 g_snprintf(errmsg, errmsg_len,
3568 "The temporary file to which the capture would be saved (\"%s\") "
3569 "could not be opened: %s.", capfile_name, err_tempfile->message);
3570 g_error_free(err_tempfile);
3572 if (capture_opts->multi_files_on) {
3573 /* Ensures that the ringbuffer is not used. This ensures that
3574 * !ringbuf_is_initialized() is equivalent to
3575 * capture_opts->save_file not being part of ringbuffer. */
3576 ringbuf_error_cleanup();
3579 g_snprintf(errmsg, errmsg_len,
3580 "The file to which the capture would be saved (\"%s\") "
3581 "could not be opened: %s.", capfile_name,
3584 g_free(capfile_name);
3588 g_free(capture_opts->save_file);
3589 if (!is_tempfile && capture_opts->multi_files_on) {
3590 /* In ringbuffer mode, save_file points to a filename from ringbuffer.c.
3591 * capfile_name was already freed before. */
3592 capture_opts->save_file = (char *)ringbuf_current_filename();
3594 /* capture_opts_cleanup will g_free(capture_opts->save_file). */
3595 capture_opts->save_file = capfile_name;
3601 static time_t get_next_time_interval(int interval_s) {
3602 time_t next_time = time(NULL);
3603 next_time -= next_time % interval_s;
3604 next_time += interval_s;
3608 /* Do the work of handling either the file size or file duration capture
3609 conditions being reached, and switching files or stopping. */
3611 do_file_switch_or_stop(capture_options *capture_opts)
3613 gboolean successful;
3615 if (capture_opts->multi_files_on) {
3616 if (capture_opts->has_autostop_files &&
3617 ++global_ld.file_count >= capture_opts->autostop_files) {
3618 /* no files left: stop here */
3619 global_ld.go = FALSE;
3623 /* Switch to the next ringbuffer file */
3624 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3625 &global_ld.save_file_fd, &global_ld.err)) {
3627 /* File switch succeeded: reset the conditions */
3628 global_ld.bytes_written = 0;
3629 global_ld.packets_written = 0;
3630 if (capture_opts->use_pcapng) {
3631 successful = capture_loop_init_pcapng_output(capture_opts, &global_ld);
3633 capture_src *pcap_src;
3634 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3635 successful = libpcap_write_file_header(global_ld.pdh, pcap_src->linktype, pcap_src->snaplen,
3636 pcap_src->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3640 fclose(global_ld.pdh);
3641 global_ld.pdh = NULL;
3642 global_ld.go = FALSE;
3643 g_free(global_ld.io_buffer);
3644 global_ld.io_buffer = NULL;
3647 if (global_ld.file_duration_timer) {
3648 g_timer_reset(global_ld.file_duration_timer);
3650 if (global_ld.next_interval_time) {
3651 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
3653 fflush(global_ld.pdh);
3655 report_packet_count(global_ld.inpkts_to_sync_pipe);
3656 global_ld.inpkts_to_sync_pipe = 0;
3657 report_new_capture_file(capture_opts->save_file);
3659 /* File switch failed: stop here */
3660 global_ld.go = FALSE;
3664 /* single file, stop now */
3665 global_ld.go = FALSE;
3672 pcap_read_handler(void* arg)
3674 capture_src *pcap_src = (capture_src *)arg;
3675 char errmsg[MSG_MAX_LENGTH+1];
3677 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3678 pcap_src->interface_id);
3680 /* If this is a pipe input it might finish early. */
3681 while (global_ld.go && pcap_src->cap_pipe_err == PIPOK) {
3682 /* dispatch incoming packets */
3683 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_src);
3686 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3687 pcap_src->interface_id);
3688 g_thread_exit(NULL);
3692 /* Try to pop an item off the packet queue and if it exists, write it */
3694 capture_loop_dequeue_packet(void) {
3695 pcap_queue_element *queue_element;
3697 g_async_queue_lock(pcap_queue);
3698 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3699 if (queue_element) {
3700 if (queue_element->pcap_src->from_pcapng) {
3701 pcap_queue_bytes -= queue_element->u.bh.block_total_length;
3703 pcap_queue_bytes -= queue_element->u.phdr.caplen;
3705 pcap_queue_packets -= 1;
3707 g_async_queue_unlock(pcap_queue);
3708 if (queue_element) {
3709 if (queue_element->pcap_src->from_pcapng) {
3710 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3711 "Dequeued a block of type 0x%08x of length %d captured on interface %d.",
3712 queue_element->u.bh.block_type, queue_element->u.bh.block_total_length,
3713 queue_element->pcap_src->interface_id);
3715 capture_loop_write_pcapng_cb(queue_element->pcap_src,
3716 &queue_element->u.bh,
3719 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3720 "Dequeued a packet of length %d captured on interface %d.",
3721 queue_element->u.phdr.caplen, queue_element->pcap_src->interface_id);
3723 capture_loop_write_packet_cb((u_char *) queue_element->pcap_src,
3724 &queue_element->u.phdr,
3727 g_free(queue_element->pd);
3728 g_free(queue_element);
3734 /* Do the low-level work of a capture.
3735 Returns TRUE if it succeeds, FALSE otherwise. */
3737 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3740 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3742 struct timeval upd_time, cur_time;
3746 GTimer *autostop_duration_timer = NULL;
3749 gboolean cfilter_error = FALSE;
3750 char errmsg[MSG_MAX_LENGTH+1];
3751 char secondary_errmsg[MSG_MAX_LENGTH+1];
3752 capture_src *pcap_src;
3753 interface_options *interface_opts;
3754 guint i, error_index = 0;
3757 *secondary_errmsg = '\0';
3759 /* init the loop data */
3760 global_ld.go = TRUE;
3761 global_ld.packets_captured = 0;
3763 global_ld.report_packet_count = FALSE;
3765 global_ld.inpkts_to_sync_pipe = 0;
3766 global_ld.err = 0; /* no error seen yet */
3767 global_ld.pdh = NULL;
3768 global_ld.save_file_fd = -1;
3769 global_ld.io_buffer = NULL;
3770 global_ld.file_count = 0;
3771 global_ld.file_duration_timer = NULL;
3772 global_ld.next_interval_time = 0;
3773 global_ld.interval_s = 0;
3775 /* We haven't yet gotten the capture statistics. */
3776 *stats_known = FALSE;
3778 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3779 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3781 /* open the "input file" from network interface or capture pipe */
3782 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3783 secondary_errmsg, sizeof(secondary_errmsg))) {
3786 for (i = 0; i < capture_opts->ifaces->len; i++) {
3787 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3788 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
3789 /* init the input filter from the network interface (capture pipe will do nothing) */
3791 * When remote capturing WinPCap crashes when the capture filter
3792 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3795 switch (capture_loop_init_filter(pcap_src->pcap_h, pcap_src->from_cap_pipe,
3796 interface_opts->name,
3797 interface_opts->cfilter?interface_opts->cfilter:"")) {
3799 case INITFILTER_NO_ERROR:
3802 case INITFILTER_BAD_FILTER:
3803 cfilter_error = TRUE;
3805 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
3808 case INITFILTER_OTHER_ERROR:
3809 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3810 pcap_geterr(pcap_src->pcap_h));
3811 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report_bug());
3816 /* If we're supposed to write to a capture file, open it for output
3817 (temporary/specified name/ringbuffer) */
3818 if (capture_opts->saving_to_file) {
3819 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3820 errmsg, sizeof(errmsg))) {
3824 /* set up to write to the already-opened capture output file/files */
3825 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3830 /* XXX - capture SIGTERM and close the capture, in case we're on a
3831 Linux 2.0[.x] system and you have to explicitly close the capture
3832 stream in order to turn promiscuous mode off? We need to do that
3833 in other places as well - and I don't think that works all the
3834 time in any case, due to libpcap bugs. */
3836 /* Well, we should be able to start capturing.
3838 Sync out the capture file, so the header makes it to the file system,
3839 and send a "capture started successfully and capture file created"
3840 message to our parent so that they'll open the capture file and
3841 update its windows to indicate that we have a live capture in
3843 fflush(global_ld.pdh);
3844 report_new_capture_file(capture_opts->save_file);
3847 if (capture_opts->has_file_interval) {
3848 global_ld.interval_s = capture_opts->file_interval;
3849 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
3851 /* create stop conditions */
3852 if (capture_opts->has_autostop_filesize) {
3853 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3854 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3857 if (capture_opts->has_autostop_duration) {
3858 autostop_duration_timer = g_timer_new();
3861 if (capture_opts->multi_files_on) {
3862 if (capture_opts->has_file_duration) {
3863 global_ld.file_duration_timer = g_timer_new();
3867 /* init the time values */
3869 upd_time = GetTickCount();
3871 gettimeofday(&upd_time, NULL);
3873 start_time = create_timestamp();
3874 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3875 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3877 /* WOW, everything is prepared! */
3878 /* please fasten your seat belts, we will enter now the actual capture loop */
3880 pcap_queue = g_async_queue_new();
3881 pcap_queue_bytes = 0;
3882 pcap_queue_packets = 0;
3883 for (i = 0; i < global_ld.pcaps->len; i++) {
3884 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3885 /* XXX - Add an interface name here? */
3886 pcap_src->tid = g_thread_new("Capture read", pcap_read_handler, pcap_src);
3889 while (global_ld.go) {
3890 /* dispatch incoming packets */
3892 gboolean dequeued = capture_loop_dequeue_packet();
3900 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3901 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3902 sizeof(errmsg), pcap_src);
3905 /* Stop capturing if all of our sources are pipes and none of them are open. */
3906 gboolean open_interfaces = FALSE;
3907 for (i = 0; i < global_ld.pcaps->len; i++) {
3908 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3909 if (pcap_src->cap_pipe_err == PIPOK) {
3910 /* True for both non-pipes and open pipes. */
3911 open_interfaces = TRUE;
3914 if (!open_interfaces) {
3915 global_ld.go = FALSE;
3919 /* Were we asked to print packet counts by the SIGINFO handler? */
3920 if (global_ld.report_packet_count) {
3921 fprintf(stderr, "%u packet%s captured\n", global_ld.packets_captured,
3922 plurality(global_ld.packets_captured, "", "s"));
3923 global_ld.report_packet_count = FALSE;
3928 /* any news from our parent (signal pipe)? -> just stop the capture */
3929 if (!signal_pipe_check_running()) {
3930 global_ld.go = FALSE;
3935 global_ld.inpkts_to_sync_pipe += inpkts;
3937 if (capture_opts->output_to_pipe) {
3938 fflush(global_ld.pdh);
3942 /* Only update once every 500ms so as not to overload slow displays.
3943 * This also prevents too much context-switching between the dumpcap
3944 * and wireshark processes.
3946 #define DUMPCAP_UPD_TIME 500
3949 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3950 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) /* wrap just causes an extra update */
3952 gettimeofday(&cur_time, NULL);
3953 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3954 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000))
3958 upd_time = cur_time;
3961 if (pcap_stats(pch, stats) >= 0) {
3962 *stats_known = TRUE;
3965 /* Let the parent process know. */
3966 if (global_ld.inpkts_to_sync_pipe) {
3968 fflush(global_ld.pdh);
3970 /* Send our parent a message saying we've written out
3971 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3973 report_packet_count(global_ld.inpkts_to_sync_pipe);
3975 global_ld.inpkts_to_sync_pipe = 0;
3978 /* check capture duration condition */
3979 if (autostop_duration_timer != NULL && g_timer_elapsed(autostop_duration_timer, NULL) >= capture_opts->autostop_duration) {
3980 /* The maximum capture time has elapsed; stop the capture. */
3981 global_ld.go = FALSE;
3985 /* check capture file duration condition */
3986 if (global_ld.file_duration_timer != NULL && g_timer_elapsed(global_ld.file_duration_timer, NULL) >= capture_opts->file_duration) {
3987 /* duration limit reached, do we have another file? */
3988 if (!do_file_switch_or_stop(capture_opts))
3990 } /* cnd_file_duration */
3992 /* check capture file interval condition */
3993 if (global_ld.interval_s && time(NULL) >= global_ld.next_interval_time) {
3994 /* end of interval reached, do we have another file? */
3995 if (!do_file_switch_or_stop(capture_opts))
3997 } /* cnd_file_interval */
4001 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
4004 for (i = 0; i < global_ld.pcaps->len; i++) {
4005 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4006 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
4007 pcap_src->interface_id);
4008 g_thread_join(pcap_src->tid);
4009 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
4010 pcap_src->interface_id);
4013 gboolean dequeued = capture_loop_dequeue_packet();
4017 global_ld.inpkts_to_sync_pipe += 1;
4018 if (capture_opts->output_to_pipe) {
4019 fflush(global_ld.pdh);
4025 /* delete stop conditions */
4026 if (global_ld.file_duration_timer != NULL)
4027 g_timer_destroy(global_ld.file_duration_timer);
4028 if (autostop_duration_timer != NULL)
4029 g_timer_destroy(autostop_duration_timer);
4031 /* did we have a pcap (input) error? */
4032 for (i = 0; i < capture_opts->ifaces->len; i++) {
4033 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4034 if (pcap_src->pcap_err) {
4035 /* On Linux, if an interface goes down while you're capturing on it,
4036 you'll get "recvfrom: Network is down".
4037 (At least you will if g_strerror() doesn't show a local translation
4040 Newer versions of libpcap maps that to just
4041 "The interface went down".
4043 On FreeBSD, DragonFly BSD, and macOS, if a network adapter
4044 disappears while you're capturing on it, you'll get
4045 "read: Device not configured" error (ENXIO). (See previous
4046 parenthetical note.)
4048 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
4050 With WinPcap and Npcap, you'll get
4051 "read error: PacketReceivePacket failed".
4053 Newer versions of libpcap map some or all of those to just
4054 "The interface disappeared".
4056 These should *not* be reported to the Wireshark developers. */
4059 cap_err_str = pcap_geterr(pcap_src->pcap_h);
4060 if (strcmp(cap_err_str, "The interface went down") == 0 ||
4061 strcmp(cap_err_str, "recvfrom: Network is down") == 0) {
4062 report_capture_error("The network adapter on which the capture was being done "
4063 "is no longer running; the capture has stopped.",
4065 } else if (strcmp(cap_err_str, "The interface disappeared") == 0 ||
4066 strcmp(cap_err_str, "read: Device not configured") == 0 ||
4067 strcmp(cap_err_str, "read: I/O error") == 0 ||
4068 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
4069 report_capture_error("The network adapter on which the capture was being done "
4070 "is no longer attached; the capture has stopped.",
4073 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
4075 report_capture_error(errmsg, please_report_bug());
4078 } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
4079 report_capture_error(errmsg, "");
4083 /* did we have an output error while capturing? */
4084 if (global_ld.err == 0) {
4087 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4088 sizeof(secondary_errmsg),
4089 capture_opts->save_file, global_ld.err, FALSE);
4090 report_capture_error(errmsg, secondary_errmsg);
4094 if (capture_opts->saving_to_file) {
4095 /* close the output file */
4096 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
4100 /* there might be packets not yet notified to the parent */
4101 /* (do this after closing the file, so all packets are already flushed) */
4102 if (global_ld.inpkts_to_sync_pipe) {
4104 report_packet_count(global_ld.inpkts_to_sync_pipe);
4105 global_ld.inpkts_to_sync_pipe = 0;
4108 /* If we've displayed a message about a write error, there's no point
4109 in displaying another message about an error on close. */
4110 if (!close_ok && write_ok) {
4111 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4112 sizeof(secondary_errmsg),
4113 capture_opts->save_file, err_close, TRUE);
4114 report_capture_error(errmsg, secondary_errmsg);
4118 * XXX We exhibit different behaviour between normal mode and sync mode
4119 * when the pipe is stdin and not already at EOF. If we're a child, the
4120 * parent's stdin isn't closed, so if the user starts another capture,
4121 * cap_pipe_open_live() will very likely not see the expected magic bytes and
4122 * will say "Unrecognized libpcap format". On the other hand, in normal
4123 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
4126 report_capture_count(TRUE);
4128 /* get packet drop statistics from pcap */
4129 for (i = 0; i < capture_opts->ifaces->len; i++) {
4131 guint32 pcap_dropped = 0;
4133 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4134 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4135 received = pcap_src->received;
4136 if (pcap_src->pcap_h != NULL) {
4137 g_assert(!pcap_src->from_cap_pipe);
4138 /* Get the capture statistics, so we know how many packets were dropped. */
4139 if (pcap_stats(pcap_src->pcap_h, stats) >= 0) {
4140 *stats_known = TRUE;
4141 /* Let the parent process know. */
4142 pcap_dropped += stats->ps_drop;
4144 g_snprintf(errmsg, sizeof(errmsg),
4145 "Can't get packet-drop statistics: %s",
4146 pcap_geterr(pcap_src->pcap_h));
4147 report_capture_error(errmsg, please_report_bug());
4150 report_packet_drops(received, pcap_dropped, pcap_src->dropped, pcap_src->flushed, stats->ps_ifdrop, interface_opts->display_name);
4153 /* close the input file (pcap or capture pipe) */
4154 capture_loop_close_input(&global_ld);
4156 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
4158 /* ok, if the write and the close were successful. */
4159 return write_ok && close_ok;
4162 if (capture_opts->multi_files_on) {
4163 /* cleanup ringbuffer */
4164 ringbuf_error_cleanup();
4166 /* We can't use the save file, and we have no FILE * for the stream
4167 to close in order to close it, so close the FD directly. */
4168 if (global_ld.save_file_fd != -1) {
4169 ws_close(global_ld.save_file_fd);
4172 /* We couldn't even start the capture, so get rid of the capture
4174 if (capture_opts->save_file != NULL) {
4175 ws_unlink(capture_opts->save_file);
4179 report_cfilter_error(capture_opts, error_index, errmsg);
4181 report_capture_error(errmsg, secondary_errmsg);
4183 /* close the input file (pcap or cap_pipe) */
4184 capture_loop_close_input(&global_ld);
4186 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
4193 capture_loop_stop(void)
4195 #ifdef HAVE_PCAP_BREAKLOOP
4197 capture_src *pcap_src;
4199 for (i = 0; i < global_ld.pcaps->len; i++) {
4200 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4201 if (pcap_src->pcap_h != NULL)
4202 pcap_breakloop(pcap_src->pcap_h);
4205 global_ld.go = FALSE;
4210 capture_loop_get_errmsg(char *errmsg, size_t errmsglen, char *secondary_errmsg,
4211 size_t secondary_errmsglen, const char *fname,
4212 int err, gboolean is_close)
4214 static const char find_space[] =
4215 "You will need to free up space on that file system"
4216 " or put the capture file on a different file system.";
4221 g_snprintf(errmsg, (gulong)errmsglen,
4222 "Not all the packets could be written to the file"
4223 " to which the capture was being saved\n"
4224 "(\"%s\") because there is no space left on the file system\n"
4225 "on which that file resides.",
4227 g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen, "%s",
4233 g_snprintf(errmsg, (gulong)errmsglen,
4234 "Not all the packets could be written to the file"
4235 " to which the capture was being saved\n"
4236 "(\"%s\") because you are too close to, or over,"
4237 " your disk quota\n"
4238 "on the file system on which that file resides.",
4240 g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen, "%s",
4247 g_snprintf(errmsg, (gulong)errmsglen,
4248 "The file to which the capture was being saved\n"
4249 "(\"%s\") could not be closed: %s.",
4250 fname, g_strerror(err));
4252 g_snprintf(errmsg, (gulong)errmsglen,
4253 "An error occurred while writing to the file"
4254 " to which the capture was being saved\n"
4256 fname, g_strerror(err));
4258 g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen,
4259 "%s", please_report_bug());
4265 * We wrote one packet. Update some statistics and check if we've met any
4266 * autostop or ring buffer conditions.
4269 capture_loop_wrote_one_packet(capture_src *pcap_src) {
4270 global_ld.packets_captured++;
4271 global_ld.packets_written++;
4272 pcap_src->received++;
4274 /* check -c NUM / -a packets:NUM */
4275 if (global_capture_opts.has_autostop_packets && global_ld.packets_captured >= global_capture_opts.autostop_packets) {
4276 fflush(global_ld.pdh);
4277 global_ld.go = FALSE;
4280 /* check -b packets:NUM */
4281 if (global_capture_opts.has_file_packets && global_ld.packets_written >= global_capture_opts.file_packets) {
4282 do_file_switch_or_stop(&global_capture_opts);
4285 /* check -a filesize:NUM */
4286 if (global_capture_opts.has_autostop_filesize &&
4287 global_capture_opts.autostop_filesize > 0 &&
4288 global_ld.bytes_written / 1000 >= global_capture_opts.autostop_filesize) {
4289 /* Capture size limit reached, do we have another file? */
4290 do_file_switch_or_stop(&global_capture_opts);
4295 /* one pcapng block was captured, process it */
4297 capture_loop_write_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd)
4302 * This should never be called if we're not writing pcapng.
4304 g_assert(global_capture_opts.use_pcapng);
4306 /* We may be called multiple times from pcap_dispatch(); if we've set
4307 the "stop capturing" flag, ignore this packet, as we're not
4308 supposed to be saving any more packets. */
4309 if (!global_ld.go) {
4310 pcap_src->flushed++;
4314 if (!pcapng_adjust_block(pcap_src, bh, pd)) {
4315 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "%s failed to adjust pcapng block.", G_STRFUNC);
4316 g_assert_not_reached();
4320 if (bh->block_type == BLOCK_TYPE_SHB && !global_ld.pcapng_passthrough) {
4322 * capture_loop_init_pcapng_output should've handled this. We need
4323 * to write ISBs when they're initially read so we shouldn't skip
4329 if (global_ld.pdh) {
4330 gboolean successful;
4332 /* We're supposed to write the packet to a file; do so.
4333 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4334 "ld->err" to the error. */
4335 successful = pcapng_write_block(global_ld.pdh,
4337 bh->block_total_length,
4338 &global_ld.bytes_written, &err);
4340 fflush(global_ld.pdh);
4342 global_ld.go = FALSE;
4343 global_ld.err = err;
4344 pcap_src->dropped++;
4345 } else if (bh->block_type == BLOCK_TYPE_EPB || bh->block_type == BLOCK_TYPE_SPB || bh->block_type == BLOCK_TYPE_SYSTEMD_JOURNAL) {
4346 /* count packet only if we actually have an EPB or SPB */
4347 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4348 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4349 "Wrote a pcapng block type %u of length %d captured on interface %u.",
4350 bh->block_type, bh->block_total_length, pcap_src->interface_id);
4352 capture_loop_wrote_one_packet(pcap_src);
4357 /* one pcap packet was captured, process it */
4359 capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4362 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4364 guint ts_mul = pcap_src->ts_nsec ? 1000000000 : 1000000;
4366 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_write_packet_cb");
4368 /* We may be called multiple times from pcap_dispatch(); if we've set
4369 the "stop capturing" flag, ignore this packet, as we're not
4370 supposed to be saving any more packets. */
4371 if (!global_ld.go) {
4372 pcap_src->flushed++;
4376 if (global_ld.pdh) {
4377 gboolean successful;
4379 /* We're supposed to write the packet to a file; do so.
4380 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4381 "ld->err" to the error. */
4382 if (global_capture_opts.use_pcapng) {
4383 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4385 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4386 phdr->caplen, phdr->len,
4387 pcap_src->interface_id,
4390 &global_ld.bytes_written, &err);
4392 successful = libpcap_write_packet(global_ld.pdh,
4393 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4394 phdr->caplen, phdr->len,
4396 &global_ld.bytes_written, &err);
4399 global_ld.go = FALSE;
4400 global_ld.err = err;
4401 pcap_src->dropped++;
4403 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4404 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4405 "Wrote a pcap packet of length %d captured on interface %u.",
4406 phdr->caplen, pcap_src->interface_id);
4408 capture_loop_wrote_one_packet(pcap_src);
4413 /* one packet was captured, queue it */
4415 capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4418 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4419 pcap_queue_element *queue_element;
4420 gboolean limit_reached;
4422 /* We may be called multiple times from pcap_dispatch(); if we've set
4423 the "stop capturing" flag, ignore this packet, as we're not
4424 supposed to be saving any more packets. */
4425 if (!global_ld.go) {
4426 pcap_src->flushed++;
4430 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4431 if (queue_element == NULL) {
4432 pcap_src->dropped++;
4435 queue_element->pcap_src = pcap_src;
4436 queue_element->u.phdr = *phdr;
4437 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4438 if (queue_element->pd == NULL) {
4439 pcap_src->dropped++;
4440 g_free(queue_element);
4443 memcpy(queue_element->pd, pd, phdr->caplen);
4444 g_async_queue_lock(pcap_queue);
4445 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4446 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4447 limit_reached = FALSE;
4448 g_async_queue_push_unlocked(pcap_queue, queue_element);
4449 pcap_queue_bytes += phdr->caplen;
4450 pcap_queue_packets += 1;
4452 limit_reached = TRUE;
4454 g_async_queue_unlock(pcap_queue);
4455 if (limit_reached) {
4456 pcap_src->dropped++;
4457 g_free(queue_element->pd);
4458 g_free(queue_element);
4459 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4460 "Dropped a packet of length %d captured on interface %u.",
4461 phdr->caplen, pcap_src->interface_id);
4463 pcap_src->received++;
4464 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4465 "Queued a packet of length %d captured on interface %u.",
4466 phdr->caplen, pcap_src->interface_id);
4468 /* I don't want to hold the mutex over the debug output. So the
4469 output may be wrong */
4470 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4471 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4472 pcap_queue_bytes, pcap_queue_packets);
4475 /* one pcapng block was captured, queue it */
4477 capture_loop_queue_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd)
4479 pcap_queue_element *queue_element;
4480 gboolean limit_reached;
4482 /* We may be called multiple times from pcap_dispatch(); if we've set
4483 the "stop capturing" flag, ignore this packet, as we're not
4484 supposed to be saving any more packets. */
4485 if (!global_ld.go) {
4486 pcap_src->flushed++;
4490 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4491 if (queue_element == NULL) {
4492 pcap_src->dropped++;
4495 queue_element->pcap_src = pcap_src;
4496 queue_element->u.bh = *bh;
4497 queue_element->pd = (u_char *)g_malloc(bh->block_total_length);
4498 if (queue_element->pd == NULL) {
4499 pcap_src->dropped++;
4500 g_free(queue_element);
4503 memcpy(queue_element->pd, pd, bh->block_total_length);
4504 g_async_queue_lock(pcap_queue);
4505 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4506 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4507 limit_reached = FALSE;
4508 g_async_queue_push_unlocked(pcap_queue, queue_element);
4509 pcap_queue_bytes += bh->block_total_length;
4510 pcap_queue_packets += 1;
4512 limit_reached = TRUE;
4514 g_async_queue_unlock(pcap_queue);
4515 if (limit_reached) {
4516 pcap_src->dropped++;
4517 g_free(queue_element->pd);
4518 g_free(queue_element);
4519 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4520 "Dropped a packet of length %d captured on interface %u.",
4521 bh->block_total_length, pcap_src->interface_id);
4523 pcap_src->received++;
4524 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4525 "Queued a block of type 0x%08x of length %d captured on interface %u.",
4526 bh->block_type, bh->block_total_length, pcap_src->interface_id);
4528 /* I don't want to hold the mutex over the debug output. So the
4529 output may be wrong */
4530 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4531 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4532 pcap_queue_bytes, pcap_queue_packets);
4536 set_80211_channel(const char *iface, const char *opt)
4540 guint32 center_freq1 = 0;
4541 guint32 center_freq2 = 0;
4544 gchar **options = NULL;
4546 options = g_strsplit_set(opt, ",", 4);
4547 for (args = 0; options[args]; args++);
4550 freq = get_nonzero_guint32(options[0], "802.11 channel frequency");
4552 if (args >= 1 && options[1]) {
4553 type = ws80211_str_to_chan_type(options[1]);
4555 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
4561 if (args >= 2 && options[2])
4562 center_freq1 = get_nonzero_guint32(options[2], "VHT center frequency");
4564 if (args >= 3 && options[3])
4565 center_freq2 = get_nonzero_guint32(options[3], "VHT center frequency 2");
4567 ret = ws80211_init();
4569 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4573 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
4576 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4582 pipe_write_block(2, SP_SUCCESS, NULL);
4585 g_strfreev(options);
4590 get_dumpcap_compiled_info(GString *str)
4592 /* Capture libraries */
4593 g_string_append(str, ", ");
4594 get_compiled_caplibs_version(str);
4598 get_dumpcap_runtime_info(GString *str)
4600 /* Capture libraries */
4601 g_string_append(str, ", ");
4602 get_runtime_caplibs_version(str);
4605 /* And now our feature presentation... [ fade to music ] */
4607 main(int argc, char *argv[])
4611 static const struct option long_options[] = {
4612 {"help", no_argument, NULL, 'h'},
4613 {"version", no_argument, NULL, 'v'},
4614 LONGOPT_CAPTURE_COMMON
4618 gboolean arg_error = FALSE;
4621 struct sigaction action, oldaction;
4624 gboolean start_capture = TRUE;
4625 gboolean stats_known;
4626 struct pcap_stat stats = {0};
4627 GLogLevelFlags log_flags;
4628 gboolean list_interfaces = FALSE;
4629 int caps_queries = 0;
4630 #ifdef HAVE_BPF_IMAGE
4631 gboolean print_bpf_code = FALSE;
4633 gboolean set_chan = FALSE;
4634 gchar *set_chan_arg = NULL;
4635 gboolean machine_readable = FALSE;
4636 gboolean print_statistics = FALSE;
4637 int status, run_once_args = 0;
4640 #if defined(__APPLE__) && defined(__LP64__)
4641 struct utsname osinfo;
4645 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
4648 create_app_running_mutex();
4651 * Initialize our DLL search path. MUST be called before LoadLibrary
4654 ws_init_dll_search_path();
4656 /* Load wpcap if possible. Do this before collecting the run-time version information */
4659 /* ... and also load the packet.dll from wpcap */
4660 /* XXX - currently not required, may change later. */
4661 /*wpcap_packet_load();*/
4664 /* Initialize the version information. */
4665 ws_init_version_info("Dumpcap (Wireshark)", NULL, get_dumpcap_compiled_info,
4666 get_dumpcap_runtime_info);
4668 #ifdef HAVE_BPF_IMAGE
4669 #define OPTSTRING_d "d"
4674 #ifdef HAVE_PCAP_REMOTE
4675 #define OPTSTRING_r "r"
4676 #define OPTSTRING_u "u"
4682 #ifdef HAVE_PCAP_SETSAMPLING
4683 #define OPTSTRING_m "m:"
4688 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "ghk:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
4690 #ifdef DEBUG_CHILD_DUMPCAP
4691 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4692 fprintf (stderr, "Unable to open debug log file .\n");
4697 #if defined(__APPLE__) && defined(__LP64__)
4699 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4700 * a bug workaround - timeouts less than 1 second don't work with libpcap
4701 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4702 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4703 * The problem is extremely unlikely to be reintroduced in a future
4706 if (uname(&osinfo) == 0) {
4708 * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
4709 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4710 * number of 10.0.0, not 10.1.0 - go figure).
4712 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4713 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4714 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4715 need_timeout_workaround = TRUE;
4720 * Determine if dumpcap is being requested to run in a special
4721 * capture_child mode by going thru the command line args to see if
4722 * a -Z is present. (-Z is a hidden option).
4724 * The primary result of running in capture_child mode is that
4725 * all messages sent out on stderr are in a special type/len/string
4726 * format to allow message processing by type. These messages include
4727 * error messages if dumpcap fails to start the operation it was
4728 * requested to do, as well as various "status" messages which are sent
4729 * when an actual capture is in progress, and a "success" message sent
4730 * if dumpcap was requested to perform an operation other than a
4733 * Capture_child mode would normally be requested by a parent process
4734 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4735 * to which dumpcap stderr has been redirected. It might also have
4736 * another pipe to obtain dumpcap stdout output; for operations other
4737 * than a capture, that information is formatted specially for easier
4738 * parsing by the parent process.
4740 * Capture_child mode needs to be determined immediately upon
4741 * startup so that any messages generated by dumpcap in this mode
4742 * (eg: during initialization) will be formatted properly.
4745 for (i=1; i<argc; i++) {
4746 if (strcmp("-Z", argv[i]) == 0) {
4747 capture_child = TRUE;
4748 machine_readable = TRUE; /* request machine-readable output */
4750 /* set output pipe to binary mode, to avoid ugly text conversions */
4751 _setmode(2, O_BINARY);
4756 /* The default_log_handler will use stdout, which makes trouble in */
4757 /* capture child mode, as it uses stdout for its sync_pipe. */
4758 /* So: the filtering is done in the console_log_handler and not here.*/
4759 /* We set the log handlers right up front to make sure that any log */
4760 /* messages when running as child will be sent back to the parent */
4761 /* with the correct format. */
4766 G_LOG_LEVEL_CRITICAL|
4767 G_LOG_LEVEL_WARNING|
4768 G_LOG_LEVEL_MESSAGE|
4772 G_LOG_FLAG_RECURSION);
4774 g_log_set_handler(NULL,
4776 console_log_handler, NULL /* user_data */);
4777 g_log_set_handler(LOG_DOMAIN_MAIN,
4779 console_log_handler, NULL /* user_data */);
4780 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4782 console_log_handler, NULL /* user_data */);
4783 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4785 console_log_handler, NULL /* user_data */);
4787 /* Initialize the pcaps list and IDBs */
4788 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(capture_src *));
4789 global_ld.pcapng_passthrough = FALSE;
4790 global_ld.saved_shb = NULL;
4791 global_ld.saved_idbs = g_array_new(FALSE, TRUE, sizeof(saved_idb_t));
4793 err_msg = ws_init_sockets();
4794 if (err_msg != NULL)
4796 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_ERROR,
4797 "ERROR: %s", err_msg);
4799 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_ERROR,
4800 "%s", please_report_bug());
4805 /* Set handler for Ctrl+C key */
4806 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4808 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4809 and exit. Do the same with SIGPIPE, in case, for example,
4810 we're writing to our standard output and it's a pipe.
4811 Do the same with SIGHUP if it's not being ignored (if we're
4812 being run under nohup, it might be ignored, in which case we
4813 should leave it ignored).
4815 XXX - apparently, Coverity complained that part of action
4816 wasn't initialized. Perhaps it's running on Linux, where
4817 struct sigaction has an ignored "sa_restorer" element and
4818 where "sa_handler" and "sa_sigaction" might not be two
4819 members of a union. */
4820 memset(&action, 0, sizeof(action));
4821 action.sa_handler = capture_cleanup_handler;
4823 * Arrange that system calls not get restarted, because when
4824 * our signal handler returns we don't want to restart
4825 * a call that was waiting for packets to arrive.
4827 action.sa_flags = 0;
4828 sigemptyset(&action.sa_mask);
4829 sigaction(SIGTERM, &action, NULL);
4830 sigaction(SIGINT, &action, NULL);
4831 sigaction(SIGPIPE, &action, NULL);
4832 sigaction(SIGHUP, NULL, &oldaction);
4833 if (oldaction.sa_handler == SIG_DFL)
4834 sigaction(SIGHUP, &action, NULL);
4837 /* Catch SIGINFO and, if we get it and we're capturing in
4838 quiet mode, report the number of packets we've captured. */
4839 action.sa_handler = report_counts_siginfo;
4840 action.sa_flags = SA_RESTART;
4841 sigemptyset(&action.sa_mask);
4842 sigaction(SIGINFO, &action, NULL);
4843 #endif /* SIGINFO */
4846 /* ----------------------------------------------------------------- */
4847 /* Privilege and capability handling */
4849 /* 1. Running not as root or suid root; no special capabilities. */
4852 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4855 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4857 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4858 /* capabilities; Drop all other capabilities; */
4859 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4860 /* else: after pcap_open_live() in capture_loop_open_input() */
4861 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4862 /* (Note: this means that the process, although logged in */
4863 /* as root, does not have various permissions such as the */
4864 /* ability to bypass file access permissions). */
4865 /* XXX: Should we just leave capabilities alone in this case */
4866 /* so that user gets expected effect that root can do */
4869 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4871 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4872 /* else: after pcap_open_live() in capture_loop_open_input() */
4873 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4874 /* pcap_open_live). */
4876 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4878 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4879 /* capabilities; Drop all other capabilities; */
4880 /* Drop suid privileges (euid=ruid); */
4881 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4882 /* else: after pcap_open_live() in capture_loop_open_input() */
4883 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4885 /* XXX: For some Linux versions/distros with capabilities */
4886 /* a 'normal' process with any capabilities cannot be */
4887 /* 'killed' (signaled) from another (same uid) non-privileged */
4889 /* For example: If (non-suid) Wireshark forks a */
4890 /* child suid dumpcap which acts as described here (case 5), */
4891 /* Wireshark will be unable to kill (signal) the child */
4892 /* dumpcap process until the capabilities have been dropped */
4893 /* (after pcap_open_live()). */
4894 /* This behaviour will apparently be changed in the kernel */
4895 /* to allow the kill (signal) in this case. */
4896 /* See the following for details: */
4897 /* https://www.mail-archive.com/ [wrapped] */
4898 /* linux-security-module@vger.kernel.org/msg02913.html */
4900 /* It is therefore conceivable that if dumpcap somehow hangs */
4901 /* in pcap_open_live or before that wireshark will not */
4902 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4903 /* In this case, exiting wireshark will kill the child */
4904 /* dumpcap process. */
4906 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4907 /* capabilities; Using libcap. Note: capset cmd (which see) */
4908 /* used to assign capabilities to file. */
4910 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4911 /* else: after pcap_open_live() in capture_loop_open_input() */
4912 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4914 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4915 /* longer required (similar to capture). */
4917 /* ----------------------------------------------------------------- */
4919 init_process_policies();
4922 /* If 'started with special privileges' (and using libcap) */
4923 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4924 /* Set euid/egid = ruid/rgid to remove suid privileges */
4925 relinquish_privs_except_capture();
4928 /* Set the initial values in the capture options. This might be overwritten
4929 by the command line parameters. */
4930 capture_opts_init(&global_capture_opts);
4931 /* We always save to a file - if no file was specified, we save to a
4933 global_capture_opts.saving_to_file = TRUE;
4934 global_capture_opts.has_ring_num_files = TRUE;
4936 /* Pass on capture_child mode for capture_opts */
4937 global_capture_opts.capture_child = capture_child;
4939 /* Now get our args */
4940 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4942 case 'h': /* Print help and exit */
4943 show_help_header("Capture network packets and dump them into a pcapng or pcap file.");
4944 print_usage(stdout);
4947 case 'v': /* Show version and exit */
4951 /*** capture option specific ***/
4952 case 'a': /* autostop criteria */
4953 case 'b': /* Ringbuffer option */
4954 case 'c': /* Capture x packets */
4955 case 'f': /* capture filter */
4956 case 'g': /* enable group read access on file(s) */
4957 case 'i': /* Use interface x */
4958 case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
4959 case 'n': /* Use pcapng format */
4960 case 'p': /* Don't capture in promiscuous mode */
4961 case 'P': /* Use pcap format */
4962 case 's': /* Set the snapshot (capture) length */
4963 case 'w': /* Write to capture file x */
4964 case 'y': /* Set the pcap data link type */
4965 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4966 #ifdef HAVE_PCAP_REMOTE
4967 case 'u': /* Use UDP for data transfer */
4968 case 'r': /* Capture own RPCAP traffic too */
4969 case 'A': /* Authentication */
4971 #ifdef HAVE_PCAP_SETSAMPLING
4972 case 'm': /* Sampling */
4974 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4975 case 'B': /* Buffer size */
4977 #ifdef HAVE_PCAP_CREATE
4978 case 'I': /* Monitor mode */
4980 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4985 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4987 capture_child = TRUE;
4989 /* set output pipe to binary mode, to avoid ugly text conversions */
4990 _setmode(2, O_BINARY);
4992 * optarg = the control ID, aka the PPID, currently used for the
4995 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4996 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4997 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4998 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
5000 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
5001 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5002 "Signal pipe: Unable to open %s. Dead parent?",
5010 case 'q': /* Quiet */
5016 /*** all non capture option specific ***/
5017 case 'D': /* Print a list of capture devices and exit */
5018 if (!list_interfaces) {
5019 list_interfaces = TRUE;
5023 case 'L': /* Print list of link-layer types and exit */
5024 if (!(caps_queries & CAPS_QUERY_LINK_TYPES)) {
5025 caps_queries |= CAPS_QUERY_LINK_TYPES;
5029 case LONGOPT_LIST_TSTAMP_TYPES:
5030 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
5032 #ifdef HAVE_BPF_IMAGE
5033 case 'd': /* Print BPF code for capture filter and exit */
5034 if (!print_bpf_code) {
5035 print_bpf_code = TRUE;
5040 case 'S': /* Print interface statistics once a second */
5041 if (!print_statistics) {
5042 print_statistics = TRUE;
5046 case 'k': /* Set wireless channel */
5049 set_chan_arg = optarg;
5052 cmdarg_err("Only one -k flag may be specified");
5056 case 'M': /* For -D, -L, and -S, print machine-readable output */
5057 machine_readable = TRUE;
5060 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
5063 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
5066 cmdarg_err("Invalid Option: %s", argv[optind-1]);
5068 case '?': /* Bad flag - print usage message */
5077 /* user specified file name as regular command-line argument */
5078 /* XXX - use it as the capture file name (or something else)? */
5084 * Extra command line arguments were specified; complain.
5085 * XXX - interpret as capture filter, as tcpdump and tshark do?
5087 cmdarg_err("Invalid argument: %s", argv[0]);
5092 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
5095 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
5096 /* Use some default if the user hasn't specified some */
5097 /* XXX: Are these defaults good enough? */
5098 pcap_queue_byte_limit = 1000 * 1000;
5099 pcap_queue_packet_limit = 1000;
5102 print_usage(stderr);
5106 if (run_once_args > 1) {
5107 #ifdef HAVE_BPF_IMAGE
5108 cmdarg_err("Only one of -D, -L, -d, -k or -S may be supplied.");
5110 cmdarg_err("Only one of -D, -L, -k or -S may be supplied.");
5113 } else if (run_once_args == 1) {
5114 /* We're supposed to print some information, rather than
5115 to capture traffic; did they specify a ring buffer option? */
5116 if (global_capture_opts.multi_files_on) {
5117 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
5121 /* We're supposed to capture traffic; */
5123 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
5124 if (global_capture_opts.ifaces->len > 1) {
5126 global_capture_opts.use_pcapng = TRUE;
5129 if (global_capture_opts.capture_comment &&
5130 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
5131 /* XXX - for ringbuffer, should we apply the comment to each file? */
5132 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
5136 /* Was the ring buffer option specified and, if so, does it make sense? */
5137 if (global_capture_opts.multi_files_on) {
5138 /* Ring buffer works only under certain conditions:
5139 a) ring buffer does not work with temporary files;
5140 b) it makes no sense to enable the ring buffer if the maximum
5141 file size is set to "infinite". */
5142 if (global_capture_opts.save_file == NULL) {
5143 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
5144 global_capture_opts.multi_files_on = FALSE;
5146 if (!global_capture_opts.has_autostop_filesize &&
5147 !global_capture_opts.has_file_duration &&
5148 !global_capture_opts.has_file_interval &&
5149 !global_capture_opts.has_file_packets) {
5150 cmdarg_err("Ring buffer requested, but no maximum capture file size, duration "
5151 "interval, or packets were specified.");
5153 /* XXX - this must be redesigned as the conditions changed */
5154 global_capture_opts.multi_files_on = FALSE;
5157 if (global_capture_opts.has_file_duration && global_capture_opts.has_file_interval) {
5158 cmdarg_err("Ring buffer file duration and interval can't be used at the same time.");
5165 * "-D" requires no interface to be selected; it's supposed to list
5168 if (list_interfaces) {
5169 /* Get the list of interfaces */
5174 if_list = capture_interface_list(&err, &err_str, NULL);
5175 if (if_list == NULL) {
5178 * If we're being run by another program, just give them
5179 * an empty list of interfaces, don't report this as
5180 * an error; that lets them decide whether to report
5181 * this as an error or not.
5183 if (!machine_readable) {
5184 cmdarg_err("There are no interfaces on which a capture can be done");
5188 cmdarg_err("%s", err_str);
5194 if (machine_readable) /* tab-separated values to stdout */
5195 print_machine_readable_interfaces(if_list);
5197 capture_opts_print_interfaces(if_list);
5198 free_interface_list(if_list);
5203 * "-S" requires no interface to be selected; it gives statistics
5204 * for all interfaces.
5206 if (print_statistics) {
5207 status = print_statistics_loop(machine_readable);
5212 interface_options *interface_opts;
5214 if (global_capture_opts.ifaces->len != 1) {
5215 cmdarg_err("Need one interface");
5219 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
5220 status = set_80211_channel(interface_opts->name, set_chan_arg);
5225 * "-L", "-d", and capturing act on a particular interface, so we have to
5226 * have an interface; if none was specified, pick a default.
5228 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
5230 /* cmdarg_err() already called .... */
5235 /* Get the list of link-layer and/or timestamp types for the capture device. */
5236 if_capabilities_t *caps;
5237 cap_device_open_err err;
5241 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
5242 int if_caps_queries = caps_queries;
5243 interface_options *interface_opts;
5245 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, ii);
5247 caps = get_if_capabilities(interface_opts, &err, &err_str);
5249 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
5250 "%s", interface_opts->name, err_str,
5251 get_pcap_failure_secondary_error_message(err, err_str));
5255 if ((if_caps_queries & CAPS_QUERY_LINK_TYPES) && caps->data_link_types == NULL) {
5256 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts->name);
5258 } /* No timestamp types is no big deal. So we will just ignore it */
5260 if (interface_opts->monitor_mode)
5261 if_caps_queries |= CAPS_MONITOR_MODE;
5263 if (machine_readable) /* tab-separated values to stdout */
5264 /* XXX: We need to change the format and adapt consumers */
5265 print_machine_readable_if_capabilities(caps, if_caps_queries);
5267 /* XXX: We might want to print also the interface name */
5268 capture_opts_print_if_capabilities(caps, interface_opts->name, if_caps_queries);
5269 free_if_capabilities(caps);
5274 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
5275 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5276 interface_options *interface_opts;
5278 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5279 if (interface_opts->timestamp_type) {
5280 interface_opts->timestamp_type_id = pcap_tstamp_type_name_to_val(interface_opts->timestamp_type);
5281 if (interface_opts->timestamp_type_id < 0) {
5282 cmdarg_err("Invalid argument to option: --time-stamp-type=%s", interface_opts->timestamp_type);
5289 /* We're supposed to do a capture, or print the BPF code for a filter. */
5291 /* Let the user know what interfaces were chosen. */
5292 if (capture_child) {
5293 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5294 interface_options *interface_opts;
5296 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5297 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
5298 interface_opts->name);
5301 str = g_string_new("");
5303 if (global_capture_opts.ifaces->len < 2)
5305 if (global_capture_opts.ifaces->len < 4)
5308 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5309 interface_options *interface_opts;
5311 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5313 if (global_capture_opts.ifaces->len > 2) {
5314 g_string_append_printf(str, ",");
5316 g_string_append_printf(str, " ");
5317 if (j == global_capture_opts.ifaces->len - 1) {
5318 g_string_append_printf(str, "and ");
5321 g_string_append_printf(str, "'%s'", interface_opts->display_name);
5324 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
5326 fprintf(stderr, "Capturing on %s\n", str->str);
5327 g_string_free(str, TRUE);
5330 /* Process the snapshot length, as that affects the generated BPF code. */
5331 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
5333 #ifdef HAVE_BPF_IMAGE
5334 if (print_bpf_code) {
5335 show_filter_code(&global_capture_opts);
5340 /* We're supposed to do a capture. Process the ring buffer arguments. */
5341 capture_opts_trim_ring_num_files(&global_capture_opts);
5343 /* flush stderr prior to starting the main capture loop */
5346 /* Now start the capture. */
5347 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
5351 /* capture failed */
5354 return 0; /* never here, make compiler happy */
5358 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
5359 const char *message, gpointer user_data _U_)
5366 /* ignore log message, if log_level isn't interesting */
5367 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5368 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
5373 switch(log_level & G_LOG_LEVEL_MASK) {
5374 case G_LOG_LEVEL_ERROR:
5377 case G_LOG_LEVEL_CRITICAL:
5380 case G_LOG_LEVEL_WARNING:
5383 case G_LOG_LEVEL_MESSAGE:
5386 case G_LOG_LEVEL_INFO:
5389 case G_LOG_LEVEL_DEBUG:
5393 fprintf(stderr, "unknown log_level %d\n", log_level);
5395 g_assert_not_reached();
5398 /* Generate the output message */
5399 if (log_level & G_LOG_LEVEL_MESSAGE) {
5400 /* normal user messages without additional infos */
5401 msg = g_strdup_printf("%s\n", message);
5403 /* create a "timestamp" */
5405 today = localtime(&curr);
5407 /* info/debug messages with additional infos */
5409 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
5410 today->tm_hour, today->tm_min, today->tm_sec,
5411 log_domain != NULL ? log_domain : "",
5414 msg = g_strdup_printf("Time not representable %8s %s %s\n",
5415 log_domain != NULL ? log_domain : "",
5419 /* DEBUG & INFO msgs (if we're debugging today) */
5420 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
5421 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5422 #ifdef DEBUG_DUMPCAP
5423 fprintf(stderr, "%s", msg);
5426 #ifdef DEBUG_CHILD_DUMPCAP
5427 fprintf(debug_log, "%s", msg);
5435 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
5436 /* to parent especially formatted if dumpcap running as child. */
5437 if (capture_child) {
5438 sync_pipe_errmsg_to_parent(2, msg, "");
5440 fprintf(stderr, "%s", msg);
5447 /****************************************************************************************************************/
5448 /* indication report routines */
5452 report_packet_count(unsigned int packet_count)
5454 char count_str[SP_DECISIZE+1+1];
5455 static unsigned int count = 0;
5457 if (capture_child) {
5458 g_snprintf(count_str, sizeof(count_str), "%u", packet_count);
5459 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", count_str);
5460 pipe_write_block(2, SP_PACKET_COUNT, count_str);
5462 count += packet_count;
5463 fprintf(stderr, "\rPackets: %u ", count);
5464 /* stderr could be line buffered */
5470 report_new_capture_file(const char *filename)
5472 if (capture_child) {
5473 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
5474 pipe_write_block(2, SP_FILE, filename);
5478 * Prevent a SIGINFO handler from writing to the standard error
5479 * while we're doing so; instead, have it just set a flag telling
5480 * us to print that information when we're done.
5483 #endif /* SIGINFO */
5484 fprintf(stderr, "File: %s\n", filename);
5485 /* stderr could be line buffered */
5490 * Allow SIGINFO handlers to write.
5495 * If a SIGINFO handler asked us to write out capture counts, do so.
5498 report_counts_for_siginfo();
5499 #endif /* SIGINFO */
5504 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5506 interface_options *interface_opts;
5507 char tmp[MSG_MAX_LENGTH+1+6];
5509 if (i < capture_opts->ifaces->len) {
5510 if (capture_child) {
5511 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5512 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5513 pipe_write_block(2, SP_BAD_FILTER, tmp);
5516 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5517 * the error message below.
5519 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
5521 "Invalid capture filter \"%s\" for interface '%s'.\n"
5523 "That string isn't a valid capture filter (%s).\n"
5524 "See the User's Guide for a description of the capture filter syntax.",
5525 interface_opts->cfilter, interface_opts->name, errmsg);
5531 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5533 if (capture_child) {
5534 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5535 "Primary Error: %s", error_msg);
5536 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5537 "Secondary Error: %s", secondary_error_msg);
5538 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5540 cmdarg_err("%s", error_msg);
5541 if (secondary_error_msg[0] != '\0')
5542 cmdarg_err_cont("%s", secondary_error_msg);
5547 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
5549 guint32 total_drops = pcap_drops + drops + flushed;
5551 if (capture_child) {
5552 char* tmp = g_strdup_printf("%u:%s", total_drops, name);
5554 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5555 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5556 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
5557 pipe_write_block(2, SP_DROPS, tmp);
5561 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5562 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
5563 received ? 100.0 * received / (received + total_drops) : 0.0);
5564 /* stderr could be line buffered */
5570 /************************************************************************************************/
5571 /* signal_pipe handling */
5576 signal_pipe_check_running(void)
5578 /* any news from our parent? -> just stop the capture */
5582 /* if we are running standalone, no check required */
5583 if (!capture_child) {
5587 if (!sig_pipe_name || !sig_pipe_handle) {
5588 /* This shouldn't happen */
5589 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5590 "Signal pipe: No name or handle");
5595 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5596 * at this point. Should we check to see if the parent is still alive,
5597 * e.g. by using OpenProcess?
5600 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5602 if (!result || avail > 0) {
5603 /* peek failed or some bytes really available */
5604 /* (if not piping from stdin this would fail) */
5605 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5606 "Signal pipe: Stop capture: %s", sig_pipe_name);
5607 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5608 "Signal pipe: %s (%p) result: %u avail: %lu", sig_pipe_name,
5609 sig_pipe_handle, result, avail);
5612 /* pipe ok and no bytes available */
5619 * Editor modelines - https://www.wireshark.org/tools/modelines.html
5624 * indent-tabs-mode: nil
5627 * vi: set shiftwidth=4 tabstop=8 expandtab:
5628 * :indentSize=4:tabSize=8:noTabs=true: