3 * Wireshark - Network traffic analyzer
4 * By Gerald Combs <gerald@wireshark.org>
5 * Copyright 1998 Gerald Combs
7 * SPDX-License-Identifier: GPL-2.0-or-later
13 #include <stdlib.h> /* for exit() */
18 #include <sys/types.h>
20 #ifdef HAVE_SYS_SOCKET_H
21 #include <sys/socket.h>
24 #ifdef HAVE_NETINET_IN_H
25 #include <netinet/in.h>
32 #ifdef HAVE_ARPA_INET_H
33 #include <arpa/inet.h>
36 #if defined(__APPLE__) && defined(__LP64__)
37 #include <sys/utsname.h>
43 #include <ui/cmdarg_err.h>
44 #include <wsutil/strtoi.h>
46 #include <version_info.h>
48 #ifndef HAVE_GETOPT_LONG
49 #include "wsutil/wsgetopt.h"
53 # include <sys/prctl.h>
54 # include <sys/capability.h>
57 #include "ringbuffer.h"
59 #include "caputils/capture_ifinfo.h"
60 #include "caputils/capture-pcap-util.h"
61 #include "caputils/capture-pcap-util-int.h"
63 #include "caputils/capture-wpcap.h"
66 #include "writecap/pcapio.h"
72 #include <ui/clopts_common.h>
73 #include <wsutil/privileges.h>
75 #include "sync_pipe.h"
77 #include "capture_opts.h"
78 #include <capchild/capture_session.h>
79 #include <capchild/capture_sync.h>
81 #include "wsutil/tempfile.h"
83 #include "wsutil/file_util.h"
84 #include "wsutil/cpu_info.h"
85 #include "wsutil/os_version_info.h"
86 #include "wsutil/str_util.h"
87 #include "wsutil/inet_addr.h"
88 #include "wsutil/time_util.h"
90 #include "caputils/ws80211_utils.h"
95 * Get information about libpcap format from "wiretap/libpcap.h".
96 * Get information about pcapng format from "wiretap/pcapng_module.h".
97 * XXX - can we just use pcap_open_offline() to read the pipe?
99 #include "wiretap/libpcap.h"
100 #include "wiretap/pcapng_module.h"
101 #include "wiretap/pcapng.h"
103 /**#define DEBUG_DUMPCAP**/
104 /**#define DEBUG_CHILD_DUMPCAP**/
108 #include <conio.h> /* _getch() */
112 #ifdef DEBUG_CHILD_DUMPCAP
113 FILE *debug_log; /* for logging debug messages to */
114 /* a file if DEBUG_CHILD_DUMPCAP */
118 static GAsyncQueue *pcap_queue;
119 static gint64 pcap_queue_bytes;
120 static gint64 pcap_queue_packets;
121 static gint64 pcap_queue_byte_limit = 0;
122 static gint64 pcap_queue_packet_limit = 0;
124 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
126 static gchar *sig_pipe_name = NULL;
127 static HANDLE sig_pipe_handle = NULL;
128 static gboolean signal_pipe_check_running(void);
132 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
133 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
136 /** Stop a low-level capture (stops the capture child). */
137 static void capture_loop_stop(void);
138 /** Close a pipe, or socket if \a from_socket is TRUE */
139 static void cap_pipe_close(int pipe_fd, gboolean from_socket);
141 #if !defined (__linux__)
142 #ifndef HAVE_PCAP_BREAKLOOP
144 * We don't have pcap_breakloop(), which is the only way to ensure that
145 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
146 * won't, if the call to read the next packet or batch of packets is
147 * is interrupted by a signal on UN*X, just go back and try again to
150 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
151 * the signal handler, set a flag to stop capturing; however, without
152 * a guarantee of that sort, we can't guarantee that we'll stop capturing
153 * if the read will be retried and won't time out if no packets arrive.
155 * Therefore, on at least some platforms, we work around the lack of
156 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
157 * to wait for packets to arrive, so that we're probably going to be
158 * blocked in the select() when the signal arrives, and can just bail
159 * out of the loop at that point.
161 * However, we don't want to do that on BSD (because "select()" doesn't work
162 * correctly on BPF devices on at least some releases of some flavors of
163 * BSD), and we don't want to do it on Windows (because "select()" is
164 * something for sockets, not for arbitrary handles). (Note that "Windows"
165 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
166 * using WinPcap, not a UNIX libpcap.)
168 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
169 * on BSD times out even if no packets have arrived, so we'll eventually
170 * exit pcap_dispatch() with an indication that no packets have arrived,
171 * and will break out of the capture loop at that point.
173 * On Windows, we can't send a SIGINT to stop capturing, so none of this
174 * applies in any case.
176 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
177 * want to include it if it's not present on this platform, however.
179 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
180 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
182 # define MUST_DO_SELECT
183 # endif /* avoid select */
184 #endif /* HAVE_PCAP_BREAKLOOP */
186 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
187 * in pcap_dispatch(); on the other hand, select() works just fine there.
188 * Hence we use a select for that come what may.
190 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
191 * internally, and, with TPACKET_V3, once that's supported, it'll
192 * support timeouts, at least as I understand the way the code works.
194 #define MUST_DO_SELECT
197 /** init the capture filter */
200 INITFILTER_BAD_FILTER,
201 INITFILTER_OTHER_ERROR
202 } initfilter_status_t;
205 STATE_EXPECT_REC_HDR,
218 typedef struct _pcap_pipe_info {
219 gboolean byte_swapped; /**< TRUE if data in the pipe is byte swapped. */
220 struct pcap_hdr hdr; /**< Pcap header when capturing from a pipe */
221 struct pcaprec_modified_hdr rechdr; /**< Pcap record header when capturing from a pipe */
224 typedef struct _pcapng_pipe_info {
225 struct pcapng_block_header_s bh; /**< Pcapng general block header when capturing from a pipe */
226 GArray *src_iface_to_global; /**< Int array mapping local IDB numbers to global_ld.interface_data */
227 } pcapng_pipe_info_t;
229 struct _loop_data; /* forward declaration so we can use it in the cap_pipe_dispatch function pointer */
232 * A source of packets from which we're capturing.
234 typedef struct _capture_src {
239 #ifdef MUST_DO_SELECT
240 int pcap_fd; /**< pcap file descriptor */
247 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
248 /**< capture pipe (unix only "input file") */
249 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
250 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
251 gboolean from_pcapng; /**< TRUE if we're capturing from pcapng format */
253 pcap_pipe_info_t pcap; /**< Pcap info when capturing from a pipe */
254 pcapng_pipe_info_t pcapng; /**< Pcapng info when capturing from a pipe */
257 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
259 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
260 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
261 char * cap_pipe_databuf; /**< Pointer to the data buffer we've allocated */
262 size_t cap_pipe_databuf_size; /**< Current size of the data buffer */
263 guint cap_pipe_max_pkt_size; /**< Maximum packet size allowed */
265 char * cap_pipe_buf; /**< Pointer to the buffer we read into */
266 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
267 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
269 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
270 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
272 int (*cap_pipe_dispatch)(struct _loop_data *, struct _capture_src *, char *, size_t);
273 cap_pipe_state_t cap_pipe_state;
274 cap_pipe_err_t cap_pipe_err;
277 GMutex *cap_pipe_read_mtx;
278 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
282 typedef struct _saved_idb {
284 guint interface_id; /* capture_src->interface_id for the associated SHB */
285 guint8 *idb; /* If non-NULL, IDB read from capture_src. This is an interface specified on the command line otherwise. */
290 * Global capture loop state.
292 typedef struct _loop_data {
294 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
295 int err; /**< if non-zero, error seen while capturing */
296 gint packets_captured; /**< Number of packets we have already captured */
297 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
299 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
301 GArray *pcaps; /**< Array of capture_src's on which we're capturing */
302 gboolean pcapng_passthrough; /**< We have one source and it's pcapng. Pass its SHB and IDBs through. */
303 guint8 *saved_shb; /**< SHB to write when we have one pcapng input */
304 GArray *saved_idbs; /**< Array of saved_idb_t, written when we have a new section or output file. */
305 GRWLock saved_shb_idb_lock; /**< Saved IDB RW mutex */
309 guint64 bytes_written; /**< Bytes written for the current file. */
310 /* autostop conditions */
311 int packets_written; /**< Packets written for the current file. */
313 /* ring buffer conditions */
314 GTimer *file_duration_timer;
315 time_t next_interval_time;
319 typedef struct _pcap_queue_element {
320 capture_src *pcap_src;
322 struct pcap_pkthdr phdr;
323 struct pcapng_block_header_s bh;
326 } pcap_queue_element;
329 * Standard secondary message for unexpected errors.
331 static const char please_report[] =
332 "Please report this to the Wireshark developers.\n"
333 "https://bugs.wireshark.org/\n"
334 "(This is not a crash; please do not report it as such.)";
337 * This needs to be static, so that the SIGINT handler can clear the "go"
338 * flag and for saved_shb_idb_lock.
340 static loop_data global_ld;
343 * Timeout, in milliseconds, for reads from the stream of captured packets
344 * from a capture device.
346 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
347 * 64-bit applications, with sub-second timeouts not to work. The bug is
348 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
350 #if defined(__APPLE__) && defined(__LP64__)
351 static gboolean need_timeout_workaround;
353 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
355 #define CAP_READ_TIMEOUT 250
359 * Timeout, in microseconds, for reads from the stream of captured packets
360 * from a pipe. Pipes don't have the same problem that BPF devices do
361 * in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
362 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
363 * of the offending versions of Snow Leopard.
365 * On Windows this value is converted to milliseconds and passed to
366 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
367 * will return immediately.
370 #define PIPE_READ_TIMEOUT 100000
372 #define PIPE_READ_TIMEOUT 250000
375 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
378 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
379 const char *message, gpointer user_data _U_);
381 /* capture related options */
382 static capture_options global_capture_opts;
383 static gboolean quiet = FALSE;
384 static gboolean use_threads = FALSE;
385 static guint64 start_time;
387 static void capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
389 static void capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
391 static void capture_loop_write_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, u_char *pd);
392 static void capture_loop_queue_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, u_char *pd);
393 static void capture_loop_get_errmsg(char *errmsg, size_t errmsglen,
394 char *secondary_errmsg,
395 size_t secondary_errmsglen,
396 const char *fname, int err,
399 static void WS_NORETURN exit_main(int err);
401 static void report_new_capture_file(const char *filename);
402 static void report_packet_count(unsigned int packet_count);
403 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
404 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
405 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
407 #define MSG_MAX_LENGTH 4096
410 print_usage(FILE *output)
412 fprintf(output, "\nUsage: dumpcap [options] ...\n");
413 fprintf(output, "\n");
414 fprintf(output, "Capture interface:\n");
415 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
416 " or for remote capturing, use one of these formats:\n"
417 " rpcap://<host>/<interface>\n"
418 " TCP@<host>:<port>\n");
419 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
420 #ifdef HAVE_PCAP_CREATE
421 fprintf(output, " -s <snaplen> packet snapshot length (def: appropriate maximum)\n");
423 fprintf(output, " -s <snaplen> packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
425 fprintf(output, " -p don't capture in promiscuous mode\n");
426 #ifdef HAVE_PCAP_CREATE
427 fprintf(output, " -I capture in monitor mode, if available\n");
429 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
430 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
432 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
433 fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
434 fprintf(output, " -D print list of interfaces and exit\n");
435 fprintf(output, " -L print list of link-layer types of iface and exit\n");
436 fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
437 #ifdef HAVE_BPF_IMAGE
438 fprintf(output, " -d print generated BPF code for capture filter\n");
440 fprintf(output, " -k set channel on wifi interface:\n"
441 " <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
442 fprintf(output, " -S print statistics for each interface once per second\n");
443 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
444 fprintf(output, "\n");
445 #ifdef HAVE_PCAP_REMOTE
446 fprintf(output, "RPCAP options:\n");
447 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
448 fprintf(output, " -u use UDP for RPCAP data transfer\n");
449 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
450 #ifdef HAVE_PCAP_SETSAMPLING
451 fprintf(output, " -m <sampling type> use packet sampling\n");
452 fprintf(output, " count:NUM - capture one packet of every NUM\n");
453 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
456 fprintf(output, "Stop conditions:\n");
457 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
458 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
459 fprintf(output, " filesize:NUM - stop this file after NUM kB\n");
460 fprintf(output, " files:NUM - stop after NUM files\n");
461 fprintf(output, " packets:NUM - stop after NUM packets\n");
462 /*fprintf(output, "\n");*/
463 fprintf(output, "Output (files):\n");
464 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
465 fprintf(output, " -g enable group read access on the output file(s)\n");
466 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
467 fprintf(output, " interval:NUM - create time intervals of NUM secs\n");
468 fprintf(output, " filesize:NUM - switch to next file after NUM kB\n");
469 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
470 fprintf(output, " packets:NUM - ringbuffer: replace after NUM packets\n");
471 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
472 fprintf(output, " -P use libpcap format instead of pcapng\n");
473 fprintf(output, " --capture-comment <comment>\n");
474 fprintf(output, " add a capture comment to the output file\n");
475 fprintf(output, " (only for pcapng)\n");
476 fprintf(output, "\n");
477 fprintf(output, "Miscellaneous:\n");
478 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
479 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
480 fprintf(output, " within dumpcap\n");
481 fprintf(output, " -t use a separate thread per interface\n");
482 fprintf(output, " -q don't report packet capture counts\n");
483 fprintf(output, " -v print version information and exit\n");
484 fprintf(output, " -h display this help and exit\n");
485 fprintf(output, "\n");
487 fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
488 fprintf(output, "You might want to enable it by executing:\n");
489 fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
490 fprintf(output, "Note that this can make your system less secure!\n");
491 fprintf(output, "\n");
493 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
494 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
495 fprintf(output, "\n");
496 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
500 * Report an error in command-line arguments.
501 * If we're a capture child, send a message back to the parent, otherwise
505 dumpcap_cmdarg_err(const char *fmt, va_list ap)
509 /* Generate a 'special format' message back to parent */
510 msg = g_strdup_vprintf(fmt, ap);
511 sync_pipe_errmsg_to_parent(2, msg, "");
514 fprintf(stderr, "dumpcap: ");
515 vfprintf(stderr, fmt, ap);
516 fprintf(stderr, "\n");
521 * Report additional information for an error in command-line arguments.
522 * If we're a capture child, send a message back to the parent, otherwise
526 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
530 msg = g_strdup_vprintf(fmt, ap);
531 sync_pipe_errmsg_to_parent(2, msg, "");
534 vfprintf(stderr, fmt, ap);
535 fprintf(stderr, "\n");
541 #if 0 /* Set to enable capability debugging */
542 /* see 'man cap_to_text()' for explanation of output */
543 /* '=' means 'all= ' ie: no capabilities */
544 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
546 print_caps(const char *pfx) {
547 cap_t caps = cap_get_proc();
548 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
549 "%s: EUID: %d Capabilities: %s", pfx,
550 geteuid(), cap_to_text(caps, NULL));
554 print_caps(const char *pfx _U_) {
559 relinquish_all_capabilities(void)
561 /* Drop any and all capabilities this process may have. */
562 /* Allowed whether or not process has any privileges. */
563 cap_t caps = cap_init(); /* all capabilities initialized to off */
564 print_caps("Pre-clear");
565 if (cap_set_proc(caps)) {
566 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
568 print_caps("Post-clear");
574 * Platform-dependent suggestions for fixing permissions.
576 #if defined(__linux__)
577 #define PLATFORM_PERMISSIONS_SUGGESTION \
579 "On Debian and Debian derivatives such as Ubuntu, if you have " \
580 "installed Wireshark from a package, try running" \
582 " sudo dpkg-reconfigure wireshark-common" \
584 "selecting \"<Yes>\" in response to the question" \
586 " Should non-superusers be able to capture packets?" \
588 "adding yourself to the \"wireshark\" group by running" \
590 " sudo usermod -a -G wireshark {your username}" \
592 "and then logging out and logging back in again."
593 #elif defined(__APPLE__)
594 #define PLATFORM_PERMISSIONS_SUGGESTION \
596 "If you installed Wireshark using the package from wireshark.org, "\
597 "Try re-installing it and checking the box for the \"Set capture " \
598 "permissions on startup\" item."
600 #define PLATFORM_PERMISSIONS_SUGGESTION
604 get_pcap_failure_secondary_error_message(cap_device_open_err open_err,
605 const char *open_err_str
613 * On Windows, first make sure they *have* WinPcap installed.
617 "In order to capture packets, WinPcap must be installed; see\n"
619 " https://www.winpcap.org/\n"
621 "for a downloadable version of WinPcap and for instructions on how to install\n"
627 * Now deal with ancient versions of libpcap that, on HP-UX, don't
628 * correctly figure out how to open a device given the device name.
631 /* HP-UX-specific suggestion. */
632 static const char ppamsg[] = "can't find PPA for ";
634 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0) {
636 "You are running (T)Wireshark with a version of the libpcap library\n"
637 "that doesn't handle HP-UX network devices well; this means that\n"
638 "(T)Wireshark may not be able to capture packets.\n"
640 "To fix this, you should install libpcap 0.6.2, or a later version\n"
641 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
642 "packaged binary form from the Software Porting And Archive Centre\n"
643 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
644 "at the URL lists a number of mirror sites.";
649 * OK, now just return a largely platform-independent error that might
650 * have platform-specific suggestions at the end (for example, suggestions
651 * for how to get permission to capture).
653 if (open_err == CAP_DEVICE_OPEN_ERR_GENERIC) {
655 * We don't know what kind of error it is, so throw all the
656 * suggestions at the user.
659 "Please check to make sure you have sufficient permissions, and that you have "
660 "the proper interface or pipe specified."
661 PLATFORM_PERMISSIONS_SUGGESTION;
662 } else if (open_err == CAP_DEVICE_OPEN_ERR_PERMISSIONS) {
664 * This is a permissions error, so no need to specify any other
668 "Please check to make sure you have sufficient permissions."
669 PLATFORM_PERMISSIONS_SUGGESTION;
672 * This is not a permissons error, so no need to suggest
673 * checking permissions.
676 "Please check that you have the proper interface or pipe specified.";
681 get_capture_device_open_failure_messages(cap_device_open_err open_err,
682 const char *open_err_str,
684 char *errmsg, size_t errmsg_len,
685 char *secondary_errmsg,
686 size_t secondary_errmsg_len)
688 g_snprintf(errmsg, (gulong) errmsg_len,
689 "The capture session could not be initiated on interface '%s' (%s).",
690 iface, open_err_str);
691 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, "%s",
692 get_pcap_failure_secondary_error_message(open_err, open_err_str));
696 compile_capture_filter(const char *iface, pcap_t *pcap_h,
697 struct bpf_program *fcode, const char *cfilter)
699 bpf_u_int32 netnum, netmask;
700 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
702 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
704 * Well, we can't get the netmask for this interface; it's used
705 * only for filters that check for broadcast IP addresses, so
706 * we just punt and use 0. It might be nice to warn the user,
707 * but that's a pain in a GUI application, as it'd involve popping
708 * up a message box, and it's not clear how often this would make
709 * a difference (only filters that check for IP broadcast addresses
713 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
718 * Sigh. Older versions of libpcap don't properly declare the
719 * third argument to pcap_compile() as a const pointer. Cast
723 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
729 #ifdef HAVE_BPF_IMAGE
731 show_filter_code(capture_options *capture_opts)
733 interface_options *interface_opts;
735 cap_device_open_err open_err;
736 gchar open_err_str[PCAP_ERRBUF_SIZE];
737 char errmsg[MSG_MAX_LENGTH+1];
738 char secondary_errmsg[MSG_MAX_LENGTH+1];
739 struct bpf_program fcode;
740 struct bpf_insn *insn;
744 for (j = 0; j < capture_opts->ifaces->len; j++) {
745 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, j);
746 pcap_h = open_capture_device(capture_opts, interface_opts,
747 CAP_READ_TIMEOUT, &open_err, &open_err_str);
748 if (pcap_h == NULL) {
749 /* Open failed; get messages */
750 get_capture_device_open_failure_messages(open_err, open_err_str,
751 interface_opts->name,
752 errmsg, sizeof errmsg,
754 sizeof secondary_errmsg);
755 /* And report them */
756 report_capture_error(errmsg, secondary_errmsg);
760 /* Set the link-layer type. */
761 if (!set_pcap_datalink(pcap_h, interface_opts->linktype, interface_opts->name,
762 errmsg, sizeof errmsg,
763 secondary_errmsg, sizeof secondary_errmsg)) {
765 report_capture_error(errmsg, secondary_errmsg);
769 /* OK, try to compile the capture filter. */
770 if (!compile_capture_filter(interface_opts->name, pcap_h, &fcode,
771 interface_opts->cfilter)) {
773 report_cfilter_error(capture_opts, j, errmsg);
778 /* Now print the filter code. */
779 insn = fcode.bf_insns;
781 for (i = 0; i < fcode.bf_len; insn++, i++)
782 printf("%s\n", bpf_image(insn, i));
784 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
785 /* to remove any suid privileges. */
786 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
787 /* (euid/egid have already previously been set to ruid/rgid. */
788 /* (See comment in main() for details) */
790 relinquish_special_privs_perm();
792 relinquish_all_capabilities();
795 /* Let our parent know we succeeded. */
796 pipe_write_block(2, SP_SUCCESS, NULL);
803 * capture_interface_list() is expected to do the right thing to get
804 * a list of interfaces.
806 * In most of the programs in the Wireshark suite, "the right thing"
807 * is to run dumpcap and ask it for the list, because dumpcap may
808 * be the only program in the suite with enough privileges to get
811 * In dumpcap itself, however, we obviously can't run dumpcap to
812 * ask for the list. Therefore, our capture_interface_list() should
813 * just call get_interface_list().
816 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
818 return get_interface_list(err, err_str);
822 * Output a machine readable list of the interfaces
823 * This list is retrieved by the sync_interface_list_open() function
824 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
827 print_machine_readable_interfaces(GList *if_list)
834 char addr_str[WS_INET6_ADDRSTRLEN];
837 /* Let our parent know we succeeded. */
838 pipe_write_block(2, SP_SUCCESS, NULL);
841 i = 1; /* Interface id number */
842 for (if_entry = g_list_first(if_list); if_entry != NULL;
843 if_entry = g_list_next(if_entry)) {
844 if_info = (if_info_t *)if_entry->data;
845 printf("%d. %s\t", i++, if_info->name);
848 * Print the contents of the if_entry struct in a parseable format.
849 * Each if_entry element is tab-separated. Addresses are comma-
852 /* XXX - Make sure our description doesn't contain a tab */
853 if (if_info->vendor_description != NULL)
854 printf("%s\t", if_info->vendor_description);
858 /* XXX - Make sure our friendly name doesn't contain a tab */
859 if (if_info->friendly_name != NULL)
860 printf("%s\t", if_info->friendly_name);
864 printf("%i\t", if_info->type);
866 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
867 addr = g_slist_next(addr)) {
868 if (addr != g_slist_nth(if_info->addrs, 0))
871 if_addr = (if_addr_t *)addr->data;
872 switch(if_addr->ifat_type) {
874 printf("%s", ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str, sizeof(addr_str)));
877 printf("%s", ws_inet_ntop6(&if_addr->addr.ip6_addr, addr_str, sizeof(addr_str)));
880 printf("<type unknown %i>", if_addr->ifat_type);
884 if (if_info->loopback)
885 printf("\tloopback");
888 printf("\t%s", if_info->extcap);
894 * If you change the machine-readable output format of this function,
895 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
898 print_machine_readable_if_capabilities(if_capabilities_t *caps, int queries)
900 GList *lt_entry, *ts_entry;
901 const gchar *desc_str;
904 /* Let our parent know we succeeded. */
905 pipe_write_block(2, SP_SUCCESS, NULL);
908 if (queries & CAPS_QUERY_LINK_TYPES) {
909 if (caps->can_set_rfmon)
913 for (lt_entry = caps->data_link_types; lt_entry != NULL;
914 lt_entry = g_list_next(lt_entry)) {
915 data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
916 if (data_link_info->description != NULL)
917 desc_str = data_link_info->description;
919 desc_str = "(not supported)";
920 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
925 if (queries & CAPS_QUERY_TIMESTAMP_TYPES) {
926 for (ts_entry = caps->timestamp_types; ts_entry != NULL;
927 ts_entry = g_list_next(ts_entry)) {
928 timestamp_info_t *timestamp = (timestamp_info_t *)ts_entry->data;
929 if (timestamp->description != NULL)
930 desc_str = timestamp->description;
933 printf("%s\t%s\n", timestamp->name, desc_str);
943 /* Print the number of packets captured for each interface until we're killed. */
945 print_statistics_loop(gboolean machine_readable)
947 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
953 char errbuf[PCAP_ERRBUF_SIZE];
956 if_list = get_interface_list(&err, &err_str);
957 if (if_list == NULL) {
959 cmdarg_err("There are no interfaces on which a capture can be done");
961 cmdarg_err("%s", err_str);
967 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
968 if_info = (if_info_t *)if_entry->data;
971 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
972 * connections. We avoid collecting stats on them.
974 if (!strncmp(if_info->name, "nf", 2)) {
975 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
981 #ifdef HAVE_PCAP_OPEN
982 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
984 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
988 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
989 if_stat->name = g_strdup(if_info->name);
991 stat_list = g_list_append(stat_list, if_stat);
996 cmdarg_err("There are no interfaces on which a capture can be done");
1000 if (capture_child) {
1001 /* Let our parent know we succeeded. */
1002 pipe_write_block(2, SP_SUCCESS, NULL);
1005 if (!machine_readable) {
1006 printf("%-15s %10s %10s\n", "Interface", "Received",
1010 global_ld.go = TRUE;
1011 while (global_ld.go) {
1012 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1013 if_stat = (if_stat_t *)stat_entry->data;
1014 pcap_stats(if_stat->pch, &ps);
1016 if (!machine_readable) {
1017 printf("%-15s %10u %10u\n", if_stat->name,
1018 ps.ps_recv, ps.ps_drop);
1020 printf("%s\t%u\t%u\n", if_stat->name,
1021 ps.ps_recv, ps.ps_drop);
1026 /* If we have a dummy signal pipe check it */
1027 if (!signal_pipe_check_running()) {
1028 global_ld.go = FALSE;
1036 /* XXX - Not reached. Should we look for 'q' in stdin? */
1037 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1038 if_stat = (if_stat_t *)stat_entry->data;
1039 pcap_close(if_stat->pch);
1040 g_free(if_stat->name);
1043 g_list_free(stat_list);
1044 free_interface_list(if_list);
1052 capture_cleanup_handler(DWORD dwCtrlType)
1054 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1055 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1056 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1057 like SIGTERM at least when the machine's shutting down.
1059 For now, if we're running as a command rather than a capture child,
1060 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1061 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1062 in that way on UN*X.
1064 If we're not running as a capture child, we might be running as
1065 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1066 user logs out. (XXX - can we explicitly check whether we're
1067 running as a service?) */
1069 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1070 "Console: Control signal");
1071 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1072 "Console: Control signal, CtrlType: %lu", dwCtrlType);
1074 /* Keep capture running if we're a service and a user logs off */
1075 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1076 capture_loop_stop();
1084 capture_cleanup_handler(int signum _U_)
1086 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1087 SIGTERM. We assume that if the user wanted it to keep running
1088 after they logged out, they'd have nohupped it. */
1090 /* Note: don't call g_log() in the signal handler: if we happened to be in
1091 * g_log() in process context when the signal came in, g_log will detect
1092 * the "recursion" and abort.
1095 capture_loop_stop();
1101 report_capture_count(gboolean reportit)
1103 /* Don't print this if we're a capture child. */
1104 if (!capture_child && reportit) {
1105 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packets_captured);
1106 /* stderr could be line buffered */
1114 report_counts_for_siginfo(void)
1116 report_capture_count(quiet);
1117 infoprint = FALSE; /* we just reported it */
1121 report_counts_siginfo(int signum _U_)
1123 int sav_errno = errno;
1125 /* If we've been told to delay printing, just set a flag asking
1126 that we print counts (if we're supposed to), otherwise print
1127 the count of packets captured (if we're supposed to). */
1131 report_counts_for_siginfo();
1134 #endif /* SIGINFO */
1137 exit_main(int status)
1140 /* Shutdown windows sockets */
1143 /* can be helpful for debugging */
1144 #ifdef DEBUG_DUMPCAP
1145 printf("Press any key\n");
1151 capture_opts_cleanup(&global_capture_opts);
1157 * If we were linked with libcap (not related to libpcap), make sure we have
1158 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1159 * (See comment in main() for details)
1162 relinquish_privs_except_capture(void)
1164 /* If 'started_with_special_privs' (ie: suid) then enable for
1165 * ourself the NET_ADMIN and NET_RAW capabilities and then
1166 * drop our suid privileges.
1168 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1169 * stuff we don't need (and shouldn't have).
1170 * CAP_NET_RAW: Packet capture (raw sockets).
1173 if (started_with_special_privs()) {
1174 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1175 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1177 cap_t caps = cap_init(); /* all capabilities initialized to off */
1179 print_caps("Pre drop, pre set");
1181 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1182 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1185 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1186 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1188 if (cap_set_proc(caps)) {
1189 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1191 print_caps("Pre drop, post set");
1193 relinquish_special_privs_perm();
1195 print_caps("Post drop, pre set");
1196 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1197 if (cap_set_proc(caps)) {
1198 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1200 print_caps("Post drop, post set");
1206 #endif /* HAVE_LIBCAP */
1208 /* Take care of byte order in the libpcap headers read from pipes.
1209 * (function taken from wiretap/libpcap.c) */
1211 cap_pipe_adjust_pcap_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1214 /* Byte-swap the record header fields. */
1215 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1216 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1217 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1218 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1221 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1222 swapped, in order to match the BPF header layout.
1224 Unfortunately, some files were, according to a comment in the "libpcap"
1225 source, written with version 2.3 in their headers but without the
1226 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1227 would make no sense - we assume that we need to swap them. */
1228 if (hdr->version_major == 2 &&
1229 (hdr->version_minor < 3 ||
1230 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1233 temp = rechdr->orig_len;
1234 rechdr->orig_len = rechdr->incl_len;
1235 rechdr->incl_len = temp;
1239 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1243 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1247 return recv(pipe_fd, buf, (int)sz, 0);
1252 return ws_read(pipe_fd, buf, sz);
1258 * Thread function that reads from a pipe and pushes the data
1259 * to the main application thread.
1262 * XXX Right now we use async queues for basic signaling. The main thread
1263 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1264 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1265 * Iff the read is successful cap_pipe_read pushes an item onto
1266 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1267 * the queues themselves (yet).
1269 * We might want to move some of the cap_pipe_dispatch logic here so that
1270 * we can let cap_thread_read run independently, queuing up multiple reads
1271 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1273 static void *cap_thread_read(void *arg)
1275 capture_src *pcap_src;
1278 DWORD last_err, bytes_read;
1283 pcap_src = (capture_src *)arg;
1284 while (pcap_src->cap_pipe_err == PIPOK) {
1285 g_async_queue_pop(pcap_src->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1286 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1288 while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1289 if ((pcap_src->from_cap_socket)
1296 b = cap_pipe_read(pcap_src->cap_pipe_fd, pcap_src->cap_pipe_buf+bytes_read,
1297 pcap_src->cap_pipe_bytes_to_read - bytes_read, pcap_src->from_cap_socket);
1300 pcap_src->cap_pipe_err = PIPEOF;
1304 pcap_src->cap_pipe_err = PIPERR;
1315 /* If we try to use read() on a named pipe on Windows with partial
1316 * data it appears to return EOF.
1319 res = ReadFile(pcap_src->cap_pipe_h, pcap_src->cap_pipe_buf+bytes_read,
1320 pcap_src->cap_pipe_bytes_to_read - bytes_read,
1325 last_err = GetLastError();
1326 if (last_err == ERROR_MORE_DATA) {
1328 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1329 pcap_src->cap_pipe_err = PIPEOF;
1333 pcap_src->cap_pipe_err = PIPERR;
1336 } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1337 pcap_src->cap_pipe_err = PIPEOF;
1344 pcap_src->cap_pipe_bytes_read = bytes_read;
1345 if (pcap_src->cap_pipe_bytes_read >= pcap_src->cap_pipe_bytes_to_read) {
1346 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1348 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1354 /* Provide select() functionality for a single file descriptor
1355 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1357 * Returns the same values as select.
1360 cap_pipe_select(int pipe_fd)
1363 struct timeval timeout;
1366 FD_SET(pipe_fd, &rfds);
1368 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1369 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1371 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1374 #define DEF_TCP_PORT 19000
1377 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, size_t errmsgl)
1379 char *sockname = pipename + 4;
1380 struct sockaddr_in sa;
1387 memset(&sa, 0, sizeof(sa));
1389 p = strchr(sockname, ':');
1391 len = strlen(sockname);
1392 port = DEF_TCP_PORT;
1396 port = strtoul(p + 1, &p, 10);
1397 if (*p || port > 65535) {
1406 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1408 if (!ws_inet_pton4(buf, (guint32 *)&sa.sin_addr)) {
1412 sa.sin_family = AF_INET;
1413 sa.sin_port = g_htons((u_short)port);
1415 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1416 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1418 LPTSTR errorText = NULL;
1421 lastError = WSAGetLastError();
1422 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1423 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1424 FORMAT_MESSAGE_IGNORE_INSERTS,
1425 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1426 (LPTSTR)&errorText, 0, NULL);
1428 g_snprintf(errmsg, (gulong)errmsgl,
1429 "The capture session could not be initiated due to the socket error: \n"
1431 " %d: %s", lastError, errorText ? (char *)errorText : "Unknown");
1433 LocalFree(errorText);
1435 " %d: %s", errno, g_strerror(errno));
1437 pcap_src->cap_pipe_err = PIPERR;
1440 cap_pipe_close(fd, TRUE);
1444 pcap_src->from_cap_socket = TRUE;
1448 g_snprintf(errmsg, (gulong)errmsgl,
1449 "The capture session could not be initiated because\n"
1450 "\"%s\" is not a valid socket specification", pipename);
1451 pcap_src->cap_pipe_err = PIPERR;
1455 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1459 cap_pipe_close(int pipe_fd, gboolean from_socket)
1463 closesocket(pipe_fd);
1466 (void) from_socket; /* Mark unused, similar to Q_UNUSED */
1471 /** Read bytes from a capture source, which is assumed to be a pipe.
1473 * Returns -1, or the number of bytes read similar to read(2).
1474 * Sets pcap_src->cap_pipe_err on error or EOF.
1477 cap_pipe_read_data_bytes(capture_src *pcap_src, char *errmsg, size_t errmsgl)
1480 int fd = pcap_src->cap_pipe_fd;
1482 DWORD sz, bytes_read = 0;
1484 ssize_t sz, bytes_read = 0;
1488 #ifdef LOG_CAPTURE_VERBOSE
1489 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_read_data_bytes read %lu of %lu",
1490 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1492 sz = pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read;
1493 while (bytes_read < sz) {
1495 g_snprintf(errmsg, (gulong)errmsgl, "Invalid file descriptor.");
1496 pcap_src->cap_pipe_err = PIPNEXIST;
1500 sel_ret = cap_pipe_select(fd);
1502 g_snprintf(errmsg, (gulong)errmsgl,
1503 "Unexpected error from select: %s.", g_strerror(errno));
1504 pcap_src->cap_pipe_err = PIPERR;
1506 } else if (sel_ret > 0) {
1507 b = cap_pipe_read(fd, pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read+bytes_read,
1508 sz-bytes_read, pcap_src->from_cap_socket);
1511 g_snprintf(errmsg, (gulong)errmsgl,
1512 "End of file on pipe during cap_pipe_read.");
1513 pcap_src->cap_pipe_err = PIPEOF;
1516 LPTSTR errorText = NULL;
1517 int lastError = WSAGetLastError();
1519 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1520 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1521 FORMAT_MESSAGE_IGNORE_INSERTS,
1522 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1523 (LPTSTR)&errorText, 0, NULL);
1524 g_snprintf(errmsg, (gulong)errmsgl,
1525 "Error on pipe data during cap_pipe_read: "
1526 " %d: %s", lastError,
1527 errorText ? (char *)errorText : "Unknown");
1529 LocalFree(errorText);
1531 g_snprintf(errmsg, (gulong)errmsgl,
1532 "Error on pipe data during cap_pipe_read: %s.",
1535 pcap_src->cap_pipe_err = PIPERR;
1542 pcap_src->cap_pipe_bytes_read += bytes_read;
1543 #ifdef LOG_CAPTURE_VERBOSE
1544 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_read_data_bytes read %lu of %lu",
1545 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1550 /* Some forward declarations for breaking up cap_pipe_open_live for pcap and pcapng formats */
1551 static void pcap_pipe_open_live(int fd, capture_src *pcap_src,
1552 struct pcap_hdr *hdr,
1553 char *errmsg, size_t errmsgl,
1554 char *secondary_errmsg, size_t secondary_errmsgl);
1555 static void pcapng_pipe_open_live(int fd, capture_src *pcap_src,
1556 char *errmsg, size_t errmsgl);
1557 static int pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src,
1558 char *errmsg, size_t errmsgl);
1560 /* For problems that are probably Not Our Fault. */
1561 static char not_our_bug[] =
1562 "Please report this to the developers of the program writing to the pipe.";
1564 /* Mimic pcap_open_live() for pipe captures
1566 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1567 * open it, and read the header.
1569 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1570 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1572 cap_pipe_open_live(char *pipename,
1573 capture_src *pcap_src,
1575 char *errmsg, size_t errmsgl,
1576 char *secondary_errmsg, size_t secondary_errmsgl)
1579 ws_statb64 pipe_stat;
1580 struct sockaddr_un sa;
1584 char* extcap_pipe_name;
1586 gboolean extcap_pipe = FALSE;
1588 int fd = -1, sel_ret;
1591 pcap_src->cap_pipe_fd = -1;
1593 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1596 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1599 * XXX - this blocks until a pcap per-file header has been written to
1600 * the pipe, so it could block indefinitely.
1602 if (strcmp(pipename, "-") == 0) {
1604 fd = 0; /* read from stdin */
1606 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1608 } else if (!strncmp(pipename, "TCP@", 4)) {
1609 if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1614 if ( g_strrstr(pipename, EXTCAP_PIPE_PREFIX) != NULL )
1617 if (ws_stat64(pipename, &pipe_stat) < 0) {
1618 if (errno == ENOENT || errno == ENOTDIR)
1619 pcap_src->cap_pipe_err = PIPNEXIST;
1621 g_snprintf(errmsg, (gulong)errmsgl,
1622 "The capture session could not be initiated "
1623 "due to error getting information on pipe/socket: %s.", g_strerror(errno));
1624 pcap_src->cap_pipe_err = PIPERR;
1628 if (S_ISFIFO(pipe_stat.st_mode)) {
1629 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1631 g_snprintf(errmsg, (gulong)errmsgl,
1632 "The capture session could not be initiated "
1633 "due to error on pipe open: %s.", g_strerror(errno));
1634 pcap_src->cap_pipe_err = PIPERR;
1637 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1638 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1640 g_snprintf(errmsg, (gulong)errmsgl,
1641 "The capture session could not be initiated "
1642 "due to error on socket create: %s.", g_strerror(errno));
1643 pcap_src->cap_pipe_err = PIPERR;
1646 sa.sun_family = AF_UNIX;
1648 * The Single UNIX Specification says:
1650 * The size of sun_path has intentionally been left undefined.
1651 * This is because different implementations use different sizes.
1652 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1653 * of 104. Since most implementations originate from BSD versions,
1654 * the size is typically in the range 92 to 108.
1656 * Applications should not assume a particular length for sun_path
1657 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1661 * The <sys/un.h> header shall define the sockaddr_un structure,
1662 * which shall include at least the following members:
1664 * sa_family_t sun_family Address family.
1665 * char sun_path[] Socket pathname.
1667 * so we assume that it's an array, with a specified size,
1668 * and that the size reflects the maximum path length.
1670 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1671 /* Path name too long */
1672 g_snprintf(errmsg, (gulong)errmsgl,
1673 "The capture session coud not be initiated "
1674 "due to error on socket connect: Path name too long.");
1675 pcap_src->cap_pipe_err = PIPERR;
1679 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1681 g_snprintf(errmsg, (gulong)errmsgl,
1682 "The capture session coud not be initiated "
1683 "due to error on socket connect: %s.", g_strerror(errno));
1684 pcap_src->cap_pipe_err = PIPERR;
1689 if (S_ISCHR(pipe_stat.st_mode)) {
1691 * Assume the user specified an interface on a system where
1692 * interfaces are in /dev. Pretend we haven't seen it.
1694 pcap_src->cap_pipe_err = PIPNEXIST;
1696 g_snprintf(errmsg, (gulong)errmsgl,
1697 "The capture session could not be initiated because\n"
1698 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1699 pcap_src->cap_pipe_err = PIPERR;
1705 #define PIPE_STR "\\pipe\\"
1706 /* Under Windows, named pipes _must_ have the form
1707 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1709 pncopy = g_strdup(pipename);
1710 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1711 pos = strchr(pncopy + 3, '\\');
1712 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1719 g_snprintf(errmsg, (gulong)errmsgl,
1720 "The capture session could not be initiated because\n"
1721 "\"%s\" is neither an interface nor a pipe.", pipename);
1722 pcap_src->cap_pipe_err = PIPNEXIST;
1725 extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
1726 extcap_pipe = strstr(pipename, extcap_pipe_name) ? TRUE : FALSE;
1727 g_free(extcap_pipe_name);
1729 /* Wait for the pipe to appear */
1732 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1734 pcap_src->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1735 OPEN_EXISTING, 0, NULL);
1737 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE)
1740 if (GetLastError() != ERROR_PIPE_BUSY) {
1741 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1742 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1743 g_snprintf(errmsg, (gulong)errmsgl,
1744 "The capture session on \"%s\" could not be started "
1745 "due to error on pipe open: %s (error %lu).",
1746 pipename, utf_16to8(err_str), GetLastError());
1748 pcap_src->cap_pipe_err = PIPERR;
1752 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1753 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1754 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1755 g_snprintf(errmsg, (gulong)errmsgl,
1756 "The capture session on \"%s\" timed out during "
1757 "pipe open: %s (error %lu).",
1758 pipename, utf_16to8(err_str), GetLastError());
1760 pcap_src->cap_pipe_err = PIPERR;
1767 pcap_src->from_cap_pipe = TRUE;
1770 * We start with a 2KB buffer for packet data, which should be
1771 * large enough for most regular network packets. We increase it,
1772 * up to the maximum size we allow, as necessary.
1774 pcap_src->cap_pipe_databuf = (char*)g_malloc(2048);
1775 pcap_src->cap_pipe_databuf_size = 2048;
1778 if (pcap_src->from_cap_socket)
1781 /* read the pcap header */
1783 while (bytes_read < sizeof magic) {
1784 sel_ret = cap_pipe_select(fd);
1786 g_snprintf(errmsg, (gulong)errmsgl,
1787 "Unexpected error from select: %s.",
1790 } else if (sel_ret > 0) {
1791 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1792 sizeof magic-bytes_read,
1793 pcap_src->from_cap_socket);
1794 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1795 if (extcap_pipe && b <= 0)
1800 g_snprintf(errmsg, (gulong)errmsgl,
1801 "End of file on pipe magic during open.");
1803 g_snprintf(errmsg, (gulong)errmsgl,
1804 "Error on pipe magic during open: %s.",
1814 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
1816 pcap_src->cap_pipe_buf = (char *) &magic;
1817 pcap_src->cap_pipe_bytes_read = 0;
1818 pcap_src->cap_pipe_bytes_to_read = sizeof(magic);
1819 /* We don't have to worry about cap_pipe_read_mtx here */
1820 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1821 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1822 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1823 if (pcap_src->cap_pipe_bytes_read <= 0 && extcap_pipe)
1826 if (pcap_src->cap_pipe_bytes_read <= 0) {
1827 if (pcap_src->cap_pipe_bytes_read == 0)
1828 g_snprintf(errmsg, (gulong)errmsgl,
1829 "End of file on pipe magic during open.");
1831 g_snprintf(errmsg, (gulong)errmsgl,
1832 "Error on pipe magic during open: %s.",
1841 case PCAP_NSEC_MAGIC:
1842 /* Host that wrote it has our byte order, and was running
1843 a program using either standard or ss990417 libpcap. */
1844 pcap_src->cap_pipe_info.pcap.byte_swapped = FALSE;
1845 pcap_src->cap_pipe_modified = FALSE;
1846 pcap_src->ts_nsec = magic == PCAP_NSEC_MAGIC;
1848 case PCAP_MODIFIED_MAGIC:
1849 /* Host that wrote it has our byte order, but was running
1850 a program using either ss990915 or ss991029 libpcap. */
1851 pcap_src->cap_pipe_info.pcap.byte_swapped = FALSE;
1852 pcap_src->cap_pipe_modified = TRUE;
1854 case PCAP_SWAPPED_MAGIC:
1855 case PCAP_SWAPPED_NSEC_MAGIC:
1856 /* Host that wrote it has a byte order opposite to ours,
1857 and was running a program using either standard or
1858 ss990417 libpcap. */
1859 pcap_src->cap_pipe_info.pcap.byte_swapped = TRUE;
1860 pcap_src->cap_pipe_modified = FALSE;
1861 pcap_src->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
1863 case PCAP_SWAPPED_MODIFIED_MAGIC:
1864 /* Host that wrote it out has a byte order opposite to
1865 ours, and was running a program using either ss990915
1866 or ss991029 libpcap. */
1867 pcap_src->cap_pipe_info.pcap.byte_swapped = TRUE;
1868 pcap_src->cap_pipe_modified = TRUE;
1870 case BLOCK_TYPE_SHB:
1871 /* This isn't pcap, it's pcapng. */
1872 pcap_src->from_pcapng = TRUE;
1873 pcap_src->cap_pipe_dispatch = pcapng_pipe_dispatch;
1874 pcap_src->cap_pipe_info.pcapng.src_iface_to_global = g_array_new(FALSE, FALSE, sizeof(guint32));
1875 global_capture_opts.use_pcapng = TRUE; /* we can only output in pcapng format */
1876 pcapng_pipe_open_live(fd, pcap_src, errmsg, errmsgl);
1879 /* Not a pcap type we know about, or not pcap at all. */
1880 g_snprintf(errmsg, (gulong)errmsgl,
1881 "Data written to the pipe is neither in a supported pcap format nor in pcapng format.");
1882 g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl, "%s",
1887 pcap_pipe_open_live(fd, pcap_src, (struct pcap_hdr *) hdr, errmsg, errmsgl,
1888 secondary_errmsg, secondary_errmsgl);
1892 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1893 pcap_src->cap_pipe_err = PIPERR;
1894 cap_pipe_close(fd, pcap_src->from_cap_socket);
1895 pcap_src->cap_pipe_fd = -1;
1897 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1902 pcap_pipe_open_live(int fd,
1903 capture_src *pcap_src,
1904 struct pcap_hdr *hdr,
1905 char *errmsg, size_t errmsgl,
1906 char *secondary_errmsg, size_t secondary_errmsgl)
1912 if (pcap_src->from_cap_socket)
1915 /* Read the rest of the header */
1917 while (bytes_read < sizeof(struct pcap_hdr)) {
1918 sel_ret = cap_pipe_select(fd);
1920 g_snprintf(errmsg, (gulong)errmsgl,
1921 "Unexpected error from select: %s.",
1924 } else if (sel_ret > 0) {
1925 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
1926 sizeof(struct pcap_hdr) - bytes_read,
1927 pcap_src->from_cap_socket);
1930 g_snprintf(errmsg, (gulong)errmsgl,
1931 "End of file on pipe header during open.");
1933 g_snprintf(errmsg, (gulong)errmsgl,
1934 "Error on pipe header during open: %s.",
1936 g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl,
1946 pcap_src->cap_pipe_buf = (char *) hdr;
1947 pcap_src->cap_pipe_bytes_read = 0;
1948 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1949 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1950 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1951 if (pcap_src->cap_pipe_bytes_read <= 0) {
1952 if (pcap_src->cap_pipe_bytes_read == 0)
1953 g_snprintf(errmsg, (gulong)errmsgl,
1954 "End of file on pipe header during open.");
1956 g_snprintf(errmsg, (gulong)errmsgl,
1957 "Error on pipe header header during open: %s.",
1959 g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl, "%s",
1966 if (pcap_src->cap_pipe_info.pcap.byte_swapped) {
1967 /* Byte-swap the header fields about which we care. */
1968 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
1969 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
1970 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
1971 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
1973 pcap_src->linktype = hdr->network;
1975 if (pcap_src->linktype == DLT_DBUS) {
1977 * The maximum D-Bus message size is 128MB, so allow packets up
1980 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_DBUS;
1983 if (pcap_src->linktype == 279) { /* DLT_EBHSCR */
1985 * The maximum EBHSCR message size is 8MB, so allow packets up
1988 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_EBHSCR;
1991 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
1994 if (hdr->version_major < 2) {
1995 g_snprintf(errmsg, (gulong)errmsgl,
1996 "The old pcap format version %d.%d is not supported.",
1997 hdr->version_major, hdr->version_minor);
1998 g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl, "%s",
2003 pcap_src->cap_pipe_fd = fd;
2007 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcap_pipe_open_live: error %s", errmsg);
2008 pcap_src->cap_pipe_err = PIPERR;
2009 cap_pipe_close(fd, pcap_src->from_cap_socket);
2010 pcap_src->cap_pipe_fd = -1;
2012 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2016 /* Read the pcapng section header block */
2018 pcapng_read_shb(capture_src *pcap_src,
2022 struct pcapng_section_header_block_s shb;
2025 if (pcap_src->from_cap_socket)
2028 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s) + sizeof(struct pcapng_section_header_block_s);
2029 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2035 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + sizeof(struct pcapng_block_header_s);
2036 pcap_src->cap_pipe_bytes_read = 0;
2037 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_section_header_block_s);
2038 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2039 g_async_queue_pop(pcap_src->cap_pipe_done_q);
2040 if (pcap_src->cap_pipe_bytes_read <= 0) {
2041 if (pcap_src->cap_pipe_bytes_read == 0)
2042 g_snprintf(errmsg, (gulong)errmsgl,
2043 "End of file on pipe section header during open.");
2045 g_snprintf(errmsg, (gulong)errmsgl,
2046 "Error on pipe section header during open: %s.",
2050 /* Continuing with STATE_EXPECT_DATA requires reading into cap_pipe_databuf at offset cap_pipe_bytes_read */
2051 pcap_src->cap_pipe_bytes_read = sizeof(struct pcapng_block_header_s) + sizeof(struct pcapng_section_header_block_s);
2054 memcpy(&shb, pcap_src->cap_pipe_databuf + sizeof(struct pcapng_block_header_s), sizeof(struct pcapng_section_header_block_s));
2058 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng SHB MAGIC");
2060 case PCAPNG_SWAPPED_MAGIC:
2061 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng SHB SWAPPED MAGIC");
2063 * pcapng sources can contain all sorts of block types. Rather than add a bunch of
2064 * complexity to this code (which is often privileged), punt and tell the user to
2065 * swap bytes elsewhere.
2067 #if G_BYTE_ORDER == G_BIG_ENDIAN
2068 #define OUR_ENDIAN "big"
2069 #define IFACE_ENDIAN "little"
2071 #define OUR_ENDIAN "little"
2072 #define IFACE_ENDIAN "big"
2074 g_snprintf(errmsg, (gulong)errmsgl,
2075 "Interface %u is " IFACE_ENDIAN " endian but we're " OUR_ENDIAN " endian.",
2076 pcap_src->interface_id);
2079 /* Not a pcapng type we know about, or not pcapng at all. */
2080 g_snprintf(errmsg, (gulong)errmsgl,
2081 "Unrecognized pcapng format or not pcapng data.");
2085 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
2087 /* Setup state to capture any options following the section header block */
2088 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2094 * Save IDB blocks for playback whenever we change output files.
2095 * Rewrite EPB and ISB interface IDs.
2098 pcapng_adjust_block(capture_src *pcap_src, const struct pcapng_block_header_s *bh, u_char *pd)
2100 switch(bh->block_type) {
2101 case BLOCK_TYPE_SHB:
2103 if (global_ld.pcapng_passthrough) {
2105 * We have a single pcapng input. We pass the SHB through when
2106 * writing a single output file and for the first ring buffer
2107 * file. We need to save it for the second and subsequent ring
2110 g_free(global_ld.saved_shb);
2111 global_ld.saved_shb = (guint8 *) g_memdup(pd, bh->block_total_length);
2114 * We're dealing with one section at a time, so we can (and must)
2115 * get rid of our old IDBs.
2117 for (unsigned i = 0; i < global_ld.saved_idbs->len; i++) {
2118 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, i);
2119 g_free(idb_source->idb);
2121 g_array_set_size(global_ld.saved_idbs, 0);
2124 * We have a new SHB from this capture source. We need to keep
2125 * global_ld.saved_idbs intact, so we mark IDBs we previously
2126 * collected from this source as deleted.
2128 for (unsigned i = 0; i < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len; i++) {
2129 guint32 iface_id = g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, guint32, i);
2130 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, iface_id);
2131 g_assert(idb_source->interface_id == pcap_src->interface_id);
2132 g_free(idb_source->idb);
2133 memset(idb_source, 0, sizeof(saved_idb_t));
2134 idb_source->deleted = TRUE;
2135 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: deleted pcapng IDB %u", G_STRFUNC, iface_id);
2138 g_array_set_size(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, 0);
2141 case BLOCK_TYPE_IDB:
2144 * Always gather IDBs. We can remove them or mark them as deleted
2145 * when we get a new SHB.
2147 saved_idb_t idb_source = { 0 };
2148 idb_source.interface_id = pcap_src->interface_id;
2149 idb_source.idb_len = bh->block_total_length;
2150 idb_source.idb = (guint8 *) g_memdup(pd, idb_source.idb_len);
2151 g_array_append_val(global_ld.saved_idbs, idb_source);
2152 guint32 iface_id = global_ld.saved_idbs->len - 1;
2153 g_array_append_val(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, iface_id);
2154 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: mapped pcapng IDB %u -> %u from source %u",
2155 G_STRFUNC, pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len - 1, iface_id, pcap_src->interface_id);
2158 case BLOCK_TYPE_EPB:
2159 case BLOCK_TYPE_ISB:
2161 if (global_ld.pcapng_passthrough) {
2162 /* Our input and output interface IDs are the same. */
2165 /* The interface ID is the first 32-bit field after the BH for both EPBs and ISBs. */
2167 memcpy(&iface_id, pd + sizeof(struct pcapng_block_header_s), 4);
2168 if (iface_id < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len) {
2169 memcpy(pd + sizeof(struct pcapng_block_header_s),
2170 &g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, guint32, iface_id), 4);
2172 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);
2185 pcapng_pipe_open_live(int fd,
2186 capture_src *pcap_src,
2190 guint32 type = BLOCK_TYPE_SHB;
2191 struct pcapng_block_header_s *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2193 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_open_live: fd %d", fd);
2195 if (pcap_src->from_cap_socket)
2198 memcpy(pcap_src->cap_pipe_databuf, &type, sizeof(guint32));
2199 /* read the rest of the pcapng general block header */
2200 pcap_src->cap_pipe_bytes_read = sizeof(guint32);
2201 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s);
2202 pcap_src->cap_pipe_fd = fd;
2203 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2206 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(struct pcapng_block_header_s));
2210 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
2212 bh->block_type = type;
2213 pcap_src->cap_pipe_buf = (char *) &bh->block_total_length;
2214 pcap_src->cap_pipe_bytes_read = 0;
2215 pcap_src->cap_pipe_bytes_to_read = sizeof(bh->block_total_length);
2216 /* We don't have to worry about cap_pipe_read_mtx here */
2217 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2218 g_async_queue_pop(pcap_src->cap_pipe_done_q);
2219 if (pcap_src->cap_pipe_bytes_read <= 0) {
2220 if (pcap_src->cap_pipe_bytes_read == 0)
2221 g_snprintf(errmsg, (gulong)errmsgl,
2222 "End of file on pipe block_total_length during open.");
2224 g_snprintf(errmsg, (gulong)errmsgl,
2225 "Error on pipe block_total_length during open: %s.",
2229 pcap_src->cap_pipe_bytes_read = sizeof(struct pcapng_block_header_s);
2230 memcpy(pcap_src->cap_pipe_databuf, bh, sizeof(struct pcapng_block_header_s));
2231 pcap_src->cap_pipe_fd = fd;
2234 if (pcapng_read_shb(pcap_src, errmsg, errmsgl)) {
2241 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_open_live: error %s", errmsg);
2242 pcap_src->cap_pipe_err = PIPERR;
2243 cap_pipe_close(fd, pcap_src->from_cap_socket);
2244 pcap_src->cap_pipe_fd = -1;
2246 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2250 /* We read one record from the pipe, take care of byte order in the record
2251 * header, write the record to the capture file, and update capture statistics. */
2253 pcap_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2255 struct pcap_pkthdr phdr;
2256 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2264 pcap_pipe_info_t *pcap_info = &pcap_src->cap_pipe_info.pcap;
2266 #ifdef LOG_CAPTURE_VERBOSE
2267 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcap_pipe_dispatch");
2270 switch (pcap_src->cap_pipe_state) {
2272 case STATE_EXPECT_REC_HDR:
2274 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2277 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2278 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_modified ?
2279 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2280 pcap_src->cap_pipe_bytes_read = 0;
2283 pcap_src->cap_pipe_buf = (char *) &pcap_info->rechdr;
2284 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2285 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2290 case STATE_READ_REC_HDR:
2292 if (pcap_src->from_cap_socket)
2295 b = cap_pipe_read(pcap_src->cap_pipe_fd, ((char *)&pcap_info->rechdr)+pcap_src->cap_pipe_bytes_read,
2296 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read, pcap_src->from_cap_socket);
2299 result = PD_PIPE_EOF;
2301 result = PD_PIPE_ERR;
2304 pcap_src->cap_pipe_bytes_read += b;
2308 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2309 if (pcap_src->cap_pipe_err == PIPEOF) {
2310 result = PD_PIPE_EOF;
2312 } else if (pcap_src->cap_pipe_err == PIPERR) {
2313 result = PD_PIPE_ERR;
2321 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2323 result = PD_REC_HDR_READ;
2326 case STATE_EXPECT_DATA:
2328 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2331 pcap_src->cap_pipe_state = STATE_READ_DATA;
2332 pcap_src->cap_pipe_bytes_to_read = pcap_info->rechdr.hdr.incl_len;
2333 pcap_src->cap_pipe_bytes_read = 0;
2336 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2337 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2338 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2343 case STATE_READ_DATA:
2345 if (pcap_src->from_cap_socket)
2348 b = cap_pipe_read(pcap_src->cap_pipe_fd,
2349 pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read,
2350 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read,
2351 pcap_src->from_cap_socket);
2354 result = PD_PIPE_EOF;
2356 result = PD_PIPE_ERR;
2359 pcap_src->cap_pipe_bytes_read += b;
2364 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2365 if (pcap_src->cap_pipe_err == PIPEOF) {
2366 result = PD_PIPE_EOF;
2368 } else if (pcap_src->cap_pipe_err == PIPERR) {
2369 result = PD_PIPE_ERR;
2377 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2379 result = PD_DATA_READ;
2383 g_snprintf(errmsg, (gulong)errmsgl,
2384 "pcap_pipe_dispatch: invalid state");
2387 } /* switch (pcap_src->cap_pipe_state) */
2390 * We've now read as much data as we were expecting, so process it.
2394 case PD_REC_HDR_READ:
2395 /* We've read the header. Take care of byte order. */
2396 cap_pipe_adjust_pcap_header(pcap_src->cap_pipe_info.pcap.byte_swapped, &pcap_info->hdr,
2397 &pcap_info->rechdr.hdr);
2398 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_max_pkt_size) {
2400 * The record contains more data than the advertised/allowed in the
2401 * pcap header, do not try to read more data (do not change to
2402 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2403 * instead stop with an error.
2405 g_snprintf(errmsg, (gulong)errmsgl, "Frame %u too long (%d bytes)",
2406 ld->packets_captured+1, pcap_info->rechdr.hdr.incl_len);
2410 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_databuf_size) {
2412 * Grow the buffer to the packet size, rounded up to a power of
2415 new_bufsize = pcap_info->rechdr.hdr.incl_len;
2417 * http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2420 new_bufsize |= new_bufsize >> 1;
2421 new_bufsize |= new_bufsize >> 2;
2422 new_bufsize |= new_bufsize >> 4;
2423 new_bufsize |= new_bufsize >> 8;
2424 new_bufsize |= new_bufsize >> 16;
2426 pcap_src->cap_pipe_databuf = (char*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2427 pcap_src->cap_pipe_databuf_size = new_bufsize;
2431 * The record has some data following the header, try to read it next
2434 if (pcap_info->rechdr.hdr.incl_len) {
2435 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2440 * No data following the record header? Then no more data needs to be
2441 * read and we will fallthrough and emit an empty packet.
2445 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2446 phdr.ts.tv_sec = pcap_info->rechdr.hdr.ts_sec;
2447 phdr.ts.tv_usec = pcap_info->rechdr.hdr.ts_usec;
2448 phdr.caplen = pcap_info->rechdr.hdr.incl_len;
2449 phdr.len = pcap_info->rechdr.hdr.orig_len;
2452 capture_loop_queue_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2454 capture_loop_write_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2456 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2460 pcap_src->cap_pipe_err = PIPEOF;
2465 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2466 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2467 g_snprintf(errmsg, (gulong)errmsgl,
2468 "Error reading from pipe: %s (error %lu)",
2469 utf_16to8(err_str), GetLastError());
2472 g_snprintf(errmsg, (gulong)errmsgl, "Error reading from pipe: %s",
2480 pcap_src->cap_pipe_err = PIPERR;
2481 /* Return here rather than inside the switch to prevent GCC warning */
2486 pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2488 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2495 struct pcapng_block_header_s *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2497 #ifdef LOG_CAPTURE_VERBOSE
2498 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch");
2501 switch (pcap_src->cap_pipe_state) {
2503 case STATE_EXPECT_REC_HDR:
2504 #ifdef LOG_CAPTURE_VERBOSE
2505 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_EXPECT_REC_HDR");
2508 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2511 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2512 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s);
2513 pcap_src->cap_pipe_bytes_read = 0;
2516 if (!pcap_src->from_cap_socket) {
2517 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2518 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2520 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2525 case STATE_READ_REC_HDR:
2526 #ifdef LOG_CAPTURE_VERBOSE
2527 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_READ_REC_HDR");
2530 if (pcap_src->from_cap_socket) {
2532 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2537 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2538 if (pcap_src->cap_pipe_err == PIPEOF) {
2539 result = PD_PIPE_EOF;
2541 } else if (pcap_src->cap_pipe_err == PIPERR) {
2542 result = PD_PIPE_ERR;
2550 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2553 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(struct pcapng_block_header_s));
2554 result = PD_REC_HDR_READ;
2557 case STATE_EXPECT_DATA:
2558 #ifdef LOG_CAPTURE_VERBOSE
2559 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_EXPECT_DATA");
2562 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2564 pcap_src->cap_pipe_state = STATE_READ_DATA;
2565 pcap_src->cap_pipe_bytes_to_read = bh->block_total_length;
2568 if (!pcap_src->from_cap_socket) {
2569 pcap_src->cap_pipe_bytes_to_read -= pcap_src->cap_pipe_bytes_read;
2570 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + pcap_src->cap_pipe_bytes_read;
2571 pcap_src->cap_pipe_bytes_read = 0;
2572 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2574 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2579 case STATE_READ_DATA:
2580 #ifdef LOG_CAPTURE_VERBOSE
2581 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_READ_DATA");
2584 if (pcap_src->from_cap_socket) {
2586 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2592 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2593 if (pcap_src->cap_pipe_err == PIPEOF) {
2594 result = PD_PIPE_EOF;
2596 } else if (pcap_src->cap_pipe_err == PIPERR) {
2597 result = PD_PIPE_ERR;
2605 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2608 result = PD_DATA_READ;
2612 g_snprintf(errmsg, (gulong)errmsgl,
2613 "pcapng_pipe_dispatch: invalid state");
2616 } /* switch (pcap_src->cap_pipe_state) */
2619 * We've now read as much data as we were expecting, so process it.
2623 case PD_REC_HDR_READ:
2624 if (bh->block_type == BLOCK_TYPE_SHB) {
2625 /* we need to read ahead to get the endianess before getting the block type and length */
2626 pcapng_read_shb(pcap_src, errmsg, errmsgl);
2630 if (bh->block_total_length > pcap_src->cap_pipe_max_pkt_size) {
2632 * The record contains more data than the advertised/allowed in the
2633 * pcapng header, do not try to read more data (do not change to
2634 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2635 * instead stop with an error.
2637 g_snprintf(errmsg, (gulong)errmsgl, "Frame %u too long (%d bytes)",
2638 ld->packets_captured+1, bh->block_total_length);
2642 if (bh->block_total_length > pcap_src->cap_pipe_databuf_size) {
2644 * Grow the buffer to the packet size, rounded up to a power of
2647 new_bufsize = bh->block_total_length;
2649 * http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2652 new_bufsize |= new_bufsize >> 1;
2653 new_bufsize |= new_bufsize >> 2;
2654 new_bufsize |= new_bufsize >> 4;
2655 new_bufsize |= new_bufsize >> 8;
2656 new_bufsize |= new_bufsize >> 16;
2658 pcap_src->cap_pipe_databuf = (guchar*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2659 pcap_src->cap_pipe_databuf_size = new_bufsize;
2662 /* The record always has at least the block total length following the header */
2663 if (bh->block_total_length < sizeof(struct pcapng_block_header_s)+sizeof(guint32)) {
2664 g_snprintf(errmsg, (gulong)errmsgl,
2665 "malformed pcapng block_total_length < minimum");
2666 pcap_src->cap_pipe_err = PIPEOF;
2669 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2674 capture_loop_queue_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
2676 capture_loop_write_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
2678 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2682 pcap_src->cap_pipe_err = PIPEOF;
2687 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2688 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2689 g_snprintf(errmsg, (gulong)errmsgl,
2690 "Error reading from pipe: %s (error %lu)",
2691 utf_16to8(err_str), GetLastError());
2694 g_snprintf(errmsg, (gulong)errmsgl, "Error reading from pipe: %s",
2702 pcap_src->cap_pipe_err = PIPERR;
2703 /* Return here rather than inside the switch to prevent GCC warning */
2707 /** Open the capture input file (pcap or capture pipe).
2708 * Returns TRUE if it succeeds, FALSE otherwise. */
2710 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2711 char *errmsg, size_t errmsg_len,
2712 char *secondary_errmsg, size_t secondary_errmsg_len)
2714 cap_device_open_err open_err;
2715 gchar open_err_str[PCAP_ERRBUF_SIZE];
2716 gchar *sync_msg_str;
2717 interface_options *interface_opts;
2718 capture_src *pcap_src;
2722 WORD wVersionRequested;
2726 /* XXX - opening Winsock on tshark? */
2728 /* Initialize Windows Socket if we are in a Win32 OS
2729 This needs to be done before querying the interface for network/netmask */
2731 /* XXX - do we really require 1.1 or earlier?
2732 Are there any versions that support only 2.0 or higher? */
2733 wVersionRequested = MAKEWORD(1, 1);
2734 err = WSAStartup(wVersionRequested, &wsaData);
2738 case WSASYSNOTREADY:
2739 g_snprintf(errmsg, (gulong) errmsg_len,
2740 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2743 case WSAVERNOTSUPPORTED:
2744 g_snprintf(errmsg, (gulong) errmsg_len,
2745 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2746 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2749 case WSAEINPROGRESS:
2750 g_snprintf(errmsg, (gulong) errmsg_len,
2751 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2755 g_snprintf(errmsg, (gulong) errmsg_len,
2756 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2760 g_snprintf(errmsg, (gulong) errmsg_len,
2761 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2765 g_snprintf(errmsg, (gulong) errmsg_len,
2766 "Couldn't initialize Windows Sockets: error %d", err);
2769 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2773 if ((use_threads == FALSE) &&
2774 (capture_opts->ifaces->len > 1)) {
2775 g_snprintf(errmsg, (gulong) errmsg_len,
2776 "Using threads is required for capturing on multiple interfaces.");
2780 int pcapng_src_count = 0;
2781 for (i = 0; i < capture_opts->ifaces->len; i++) {
2782 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
2783 pcap_src = (capture_src *)g_malloc0(sizeof (capture_src));
2784 if (pcap_src == NULL) {
2785 g_snprintf(errmsg, (gulong) errmsg_len,
2786 "Could not allocate memory.");
2791 * Add our pcapng interface entry. This will be deleted further
2792 * down if pcapng_passthrough == TRUE.
2794 saved_idb_t idb_source = { 0 };
2795 idb_source.interface_id = i;
2796 g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
2797 g_array_append_val(global_ld.saved_idbs, idb_source);
2798 g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
2799 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: saved capture_opts IDB %u",
2802 #ifdef MUST_DO_SELECT
2803 pcap_src->pcap_fd = -1;
2805 pcap_src->interface_id = i;
2806 pcap_src->linktype = -1;
2808 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2810 pcap_src->cap_pipe_fd = -1;
2811 pcap_src->cap_pipe_dispatch = pcap_pipe_dispatch;
2812 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2813 pcap_src->cap_pipe_err = PIPOK;
2815 pcap_src->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2816 g_mutex_init(pcap_src->cap_pipe_read_mtx);
2817 pcap_src->cap_pipe_pending_q = g_async_queue_new();
2818 pcap_src->cap_pipe_done_q = g_async_queue_new();
2820 g_array_append_val(ld->pcaps, pcap_src);
2822 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts->name);
2823 pcap_src->pcap_h = open_capture_device(capture_opts, interface_opts,
2824 CAP_READ_TIMEOUT, &open_err, &open_err_str);
2826 if (pcap_src->pcap_h != NULL) {
2827 /* we've opened "iface" as a network device */
2829 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2830 /* Find out if we're getting nanosecond-precision time stamps */
2831 pcap_src->ts_nsec = have_high_resolution_timestamp(pcap_src->pcap_h);
2834 #if defined(HAVE_PCAP_SETSAMPLING)
2835 if (interface_opts->sampling_method != CAPTURE_SAMP_NONE) {
2836 struct pcap_samp *samp;
2838 if ((samp = pcap_setsampling(pcap_src->pcap_h)) != NULL) {
2839 switch (interface_opts->sampling_method) {
2840 case CAPTURE_SAMP_BY_COUNT:
2841 samp->method = PCAP_SAMP_1_EVERY_N;
2844 case CAPTURE_SAMP_BY_TIMER:
2845 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2849 sync_msg_str = g_strdup_printf(
2850 "Unknown sampling method %d specified,\n"
2851 "continue without packet sampling",
2852 interface_opts->sampling_method);
2853 report_capture_error("Couldn't set the capture "
2854 "sampling", sync_msg_str);
2855 g_free(sync_msg_str);
2857 samp->value = interface_opts->sampling_param;
2859 report_capture_error("Couldn't set the capture sampling",
2860 "Cannot get packet sampling data structure");
2865 /* setting the data link type only works on real interfaces */
2866 if (!set_pcap_datalink(pcap_src->pcap_h, interface_opts->linktype,
2867 interface_opts->name,
2869 secondary_errmsg, secondary_errmsg_len)) {
2872 pcap_src->linktype = get_pcap_datalink(pcap_src->pcap_h, interface_opts->name);
2874 /* We couldn't open "iface" as a network device. */
2875 /* Try to open it as a pipe */
2876 gboolean pipe_err = FALSE;
2877 cap_pipe_open_live(interface_opts->name, pcap_src,
2878 &pcap_src->cap_pipe_info.pcap.hdr,
2880 secondary_errmsg, secondary_errmsg_len);
2883 if (pcap_src->from_cap_socket) {
2885 if (pcap_src->cap_pipe_fd == -1) {
2890 if (pcap_src->cap_pipe_h == INVALID_HANDLE_VALUE) {
2897 if (pcap_src->cap_pipe_err == PIPNEXIST) {
2899 * We tried opening as an interface, and that failed,
2900 * so we tried to open it as a pipe, but the pipe
2901 * doesn't exist. Report the error message for
2904 get_capture_device_open_failure_messages(open_err,
2906 interface_opts->name,
2910 secondary_errmsg_len);
2913 * Else pipe (or file) does exist and cap_pipe_open_live() has
2918 /* cap_pipe_open_live() succeeded; don't want
2919 error message from pcap_open_live() */
2920 open_err_str[0] = '\0';
2924 /* XXX - will this work for tshark? */
2925 #ifdef MUST_DO_SELECT
2926 if (!pcap_src->from_cap_pipe) {
2927 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2928 pcap_src->pcap_fd = pcap_get_selectable_fd(pcap_src->pcap_h);
2930 pcap_src->pcap_fd = pcap_fileno(pcap_src->pcap_h);
2935 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2936 returned a warning; print it, but keep capturing. */
2937 if (open_err_str[0] != '\0') {
2938 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2939 report_capture_error(sync_msg_str, "");
2940 g_free(sync_msg_str);
2942 if (pcap_src->from_pcapng) {
2946 if (capture_opts->ifaces->len == 1 && pcapng_src_count == 1) {
2947 ld->pcapng_passthrough = TRUE;
2948 g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
2949 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: Clearing %u interfaces for passthrough",
2950 G_STRFUNC, global_ld.saved_idbs->len);
2951 g_array_set_size(global_ld.saved_idbs, 0);
2952 g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
2955 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2956 /* to remove any suid privileges. */
2957 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2958 /* (euid/egid have already previously been set to ruid/rgid. */
2959 /* (See comment in main() for details) */
2961 relinquish_special_privs_perm();
2963 relinquish_all_capabilities();
2968 /* close the capture input file (pcap or capture pipe) */
2969 static void capture_loop_close_input(loop_data *ld)
2972 capture_src *pcap_src;
2974 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2976 for (i = 0; i < ld->pcaps->len; i++) {
2977 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2978 /* Pipe, or capture device? */
2979 if (pcap_src->from_cap_pipe) {
2980 /* Pipe. If open, close the capture pipe "input file". */
2981 if (pcap_src->cap_pipe_fd >= 0) {
2982 cap_pipe_close(pcap_src->cap_pipe_fd, pcap_src->from_cap_socket);
2983 pcap_src->cap_pipe_fd = -1;
2986 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE) {
2987 CloseHandle(pcap_src->cap_pipe_h);
2988 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2991 if (pcap_src->cap_pipe_databuf != NULL) {
2992 /* Free the buffer. */
2993 g_free(pcap_src->cap_pipe_databuf);
2994 pcap_src->cap_pipe_databuf = NULL;
2996 if (pcap_src->from_pcapng) {
2997 g_array_free(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, TRUE);
2998 pcap_src->cap_pipe_info.pcapng.src_iface_to_global = NULL;
3001 /* Capture device. If open, close the pcap_t. */
3002 if (pcap_src->pcap_h != NULL) {
3003 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_src->pcap_h);
3004 pcap_close(pcap_src->pcap_h);
3005 pcap_src->pcap_h = NULL;
3013 /* Shut down windows sockets */
3019 /* init the capture filter */
3020 static initfilter_status_t
3021 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
3022 const gchar * name, const gchar * cfilter)
3024 struct bpf_program fcode;
3026 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
3028 /* capture filters only work on real interfaces */
3029 if (cfilter && !from_cap_pipe) {
3030 /* A capture filter was specified; set it up. */
3031 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
3032 /* Treat this specially - our caller might try to compile this
3033 as a display filter and, if that succeeds, warn the user that
3034 the display and capture filter syntaxes are different. */
3035 return INITFILTER_BAD_FILTER;
3037 if (pcap_setfilter(pcap_h, &fcode) < 0) {
3038 #ifdef HAVE_PCAP_FREECODE
3039 pcap_freecode(&fcode);
3041 return INITFILTER_OTHER_ERROR;
3043 #ifdef HAVE_PCAP_FREECODE
3044 pcap_freecode(&fcode);
3048 return INITFILTER_NO_ERROR;
3052 * Write the dumpcap pcapng SHB and IDBs if needed.
3053 * Called from capture_loop_init_output and do_file_switch_or_stop.
3056 capture_loop_init_pcapng_output(capture_options *capture_opts, loop_data *ld)
3058 g_rw_lock_reader_lock (&ld->saved_shb_idb_lock);
3060 if (ld->pcapng_passthrough && !ld->saved_shb) {
3061 /* We have a single pcapng capture interface and this is the first or only output file. */
3062 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: skipping dumpcap SHB and IDBs in favor of source", G_STRFUNC);
3063 g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3067 gboolean successful = TRUE;
3069 GString *os_info_str = g_string_new("");
3071 get_os_version_info(os_info_str);
3073 if (ld->saved_shb) {
3074 /* We have a single pcapng capture interface and multiple output files. */
3076 struct pcapng_block_header_s bh;
3078 memcpy(&bh, ld->saved_shb, sizeof(struct pcapng_block_header_s));
3080 successful = pcapng_write_block(ld->pdh, ld->saved_shb, bh.block_total_length, &ld->bytes_written, &err);
3082 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: wrote saved passthrough SHB %d", G_STRFUNC, successful);
3084 GString *cpu_info_str = g_string_new("");
3085 get_cpu_info(cpu_info_str);
3087 successful = pcapng_write_section_header_block(ld->pdh,
3088 (const char *)capture_opts->capture_comment, /* Comment */
3089 cpu_info_str->str, /* HW */
3090 os_info_str->str, /* OS */
3091 get_appname_and_version(),
3092 -1, /* section_length */
3095 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: wrote dumpcap SHB %d", G_STRFUNC, successful);
3096 g_string_free(cpu_info_str, TRUE);
3099 for (unsigned i = 0; successful && (i < ld->saved_idbs->len); i++) {
3100 saved_idb_t idb_source = g_array_index(ld->saved_idbs, saved_idb_t, i);
3101 if (idb_source.deleted) {
3103 * Our interface is out of scope. Suppose we're writing multiple
3104 * files and a source switches sections. We currently write dummy
3107 * File 1: IDB0, IDB1, IDB2
3108 * [ The source of IDBs 1 and 2 writes an SHB with two new IDBs ]
3109 * [ We switch output files ]
3110 * File 2: IDB0, dummy IDB, dummy IDB, IDB3, IDB4
3112 * It might make more sense to write the original data so that
3113 * so that our IDB lists are more consistent across files.
3115 successful = pcapng_write_interface_description_block(global_ld.pdh,
3116 "Interface went out of scope", /* OPT_COMMENT 1 */
3117 "dummy", /* IDB_NAME 2 */
3118 "Dumpcap dummy interface", /* IDB_DESCRIPTION 3 */
3119 NULL, /* IDB_FILTER 11 */
3120 os_info_str->str, /* IDB_OS 12 */
3123 &(global_ld.bytes_written),
3124 0, /* IDB_IF_SPEED 8 */
3125 6, /* IDB_TSRESOL 9 */
3127 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: skipping deleted pcapng IDB %u", G_STRFUNC, i);
3128 } else if (idb_source.idb && idb_source.idb_len) {
3129 successful = pcapng_write_block(global_ld.pdh, idb_source.idb, idb_source.idb_len, &ld->bytes_written, &err);
3130 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: wrote pcapng IDB %d", G_STRFUNC, successful);
3131 } else if (idb_source.interface_id < capture_opts->ifaces->len) {
3132 unsigned if_id = idb_source.interface_id;
3133 interface_options *interface_opts = &g_array_index(capture_opts->ifaces, interface_options, if_id);
3134 capture_src *pcap_src = g_array_index(ld->pcaps, capture_src *, if_id);
3135 if (pcap_src->from_cap_pipe) {
3136 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3138 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3140 successful = pcapng_write_interface_description_block(global_ld.pdh,
3141 NULL, /* OPT_COMMENT 1 */
3142 interface_opts->name, /* IDB_NAME 2 */
3143 interface_opts->descr, /* IDB_DESCRIPTION 3 */
3144 interface_opts->cfilter, /* IDB_FILTER 11 */
3145 os_info_str->str, /* IDB_OS 12 */
3148 &(global_ld.bytes_written),
3149 0, /* IDB_IF_SPEED 8 */
3150 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3152 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: wrote capture_opts IDB %d: %d", G_STRFUNC, if_id, successful);
3155 g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3157 g_string_free(os_info_str, TRUE);
3162 /* set up to write to the already-opened capture output file/files */
3164 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
3167 gboolean successful;
3169 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
3171 if ((capture_opts->use_pcapng == FALSE) &&
3172 (capture_opts->ifaces->len > 1)) {
3173 g_snprintf(errmsg, errmsg_len,
3174 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
3178 /* Set up to write to the capture file. */
3179 if (capture_opts->multi_files_on) {
3180 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
3182 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
3183 if (ld->pdh == NULL) {
3188 if (capture_opts->use_pcapng) {
3189 successful = capture_loop_init_pcapng_output(capture_opts, ld);
3191 capture_src *pcap_src;
3192 pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
3193 if (pcap_src->from_cap_pipe) {
3194 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3196 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3198 successful = libpcap_write_file_header(ld->pdh, pcap_src->linktype, pcap_src->snaplen,
3199 pcap_src->ts_nsec, &ld->bytes_written, &err);
3207 if (ld->pdh == NULL) {
3208 /* We couldn't set up to write to the capture file. */
3209 /* XXX - use cf_open_error_message from tshark instead? */
3214 g_snprintf(errmsg, errmsg_len,
3215 "The file to which the capture would be"
3216 " saved (\"%s\") could not be opened: Error %d.",
3217 capture_opts->save_file, err);
3219 g_snprintf(errmsg, errmsg_len,
3220 "The file to which the capture would be"
3221 " saved (\"%s\") could not be opened: %s.",
3222 capture_opts->save_file, g_strerror(err));
3234 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
3238 capture_src *pcap_src;
3239 guint64 end_time = create_timestamp();
3241 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
3243 if (capture_opts->multi_files_on) {
3244 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
3246 if (capture_opts->use_pcapng) {
3247 for (i = 0; i < global_ld.pcaps->len; i++) {
3248 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3249 if (!pcap_src->from_cap_pipe) {
3250 guint64 isb_ifrecv, isb_ifdrop;
3251 struct pcap_stat stats;
3253 if (pcap_stats(pcap_src->pcap_h, &stats) >= 0) {
3254 isb_ifrecv = pcap_src->received;
3255 isb_ifdrop = stats.ps_drop + pcap_src->dropped + pcap_src->flushed;
3257 isb_ifrecv = G_MAXUINT64;
3258 isb_ifdrop = G_MAXUINT64;
3260 pcapng_write_interface_statistics_block(ld->pdh,
3263 "Counters provided by dumpcap",
3272 if (fclose(ld->pdh) == EOF) {
3273 if (err_close != NULL) {
3283 /* dispatch incoming packets (pcap or capture pipe)
3285 * Waits for incoming packets to be available, and calls pcap_dispatch()
3286 * to cause them to be processed.
3288 * Returns the number of packets which were processed.
3290 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3291 * packet-batching behaviour does not cause packets to get held back
3295 capture_loop_dispatch(loop_data *ld,
3296 char *errmsg, int errmsg_len, capture_src *pcap_src)
3299 gint packet_count_before;
3302 packet_count_before = ld->packets_captured;
3303 if (pcap_src->from_cap_pipe) {
3304 /* dispatch from capture pipe */
3305 #ifdef LOG_CAPTURE_VERBOSE
3306 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3309 if (pcap_src->from_cap_socket) {
3311 sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
3313 if (sel_ret < 0 && errno != EINTR) {
3314 g_snprintf(errmsg, errmsg_len,
3315 "Unexpected error from select: %s", g_strerror(errno));
3316 report_capture_error(errmsg, please_report);
3322 /* Windows does not have select() for pipes. */
3323 /* Proceed with _dispatch() which waits for cap_pipe_done_q
3324 * notification from cap_thread_read() when ReadFile() on
3325 * the pipe has read enough bytes. */
3331 * "select()" says we can read from the pipe without blocking
3333 inpkts = pcap_src->cap_pipe_dispatch(ld, pcap_src, errmsg, errmsg_len);
3335 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: src %u pipe reached EOF or err, rcv: %u drop: %u flush: %u",
3336 G_STRFUNC, pcap_src->interface_id, pcap_src->received, pcap_src->dropped, pcap_src->flushed);
3337 g_assert(pcap_src->cap_pipe_err != PIPOK);
3343 /* dispatch from pcap */
3344 #ifdef MUST_DO_SELECT
3346 * If we have "pcap_get_selectable_fd()", we use it to get the
3347 * descriptor on which to select; if that's -1, it means there
3348 * is no descriptor on which you can do a "select()" (perhaps
3349 * because you're capturing on a special device, and that device's
3350 * driver unfortunately doesn't support "select()", in which case
3351 * we don't do the select - which means it might not be possible
3352 * to stop a capture until a packet arrives. If that's unacceptable,
3353 * plead with whoever supplies the software for that device to add
3354 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3355 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3356 * later, so it can use pcap_breakloop().
3358 #ifdef LOG_CAPTURE_VERBOSE
3359 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3361 if (pcap_src->pcap_fd != -1) {
3362 sel_ret = cap_pipe_select(pcap_src->pcap_fd);
3365 * "select()" says we can read from it without blocking; go for
3368 * We don't have pcap_breakloop(), so we only process one packet
3369 * per pcap_dispatch() call, to allow a signal to stop the
3370 * processing immediately, rather than processing all packets
3371 * in a batch before quitting.
3374 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3376 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3380 /* Error, rather than pcap_breakloop(). */
3381 pcap_src->pcap_err = TRUE;
3383 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3386 if (sel_ret < 0 && errno != EINTR) {
3387 g_snprintf(errmsg, errmsg_len,
3388 "Unexpected error from select: %s", g_strerror(errno));
3389 report_capture_error(errmsg, please_report);
3395 #endif /* MUST_DO_SELECT */
3397 /* dispatch from pcap without select */
3399 #ifdef LOG_CAPTURE_VERBOSE
3400 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3404 * On Windows, we don't support asynchronously telling a process to
3405 * stop capturing; instead, we check for an indication on a pipe
3406 * after processing packets. We therefore process only one packet
3407 * at a time, so that we can check the pipe after every packet.
3410 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3412 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3416 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3418 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3423 /* Error, rather than pcap_breakloop(). */
3424 pcap_src->pcap_err = TRUE;
3426 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3428 #else /* pcap_next_ex */
3429 #ifdef LOG_CAPTURE_VERBOSE
3430 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3432 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3435 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3436 * see https://wiki.wireshark.org/CaptureSetup/WinPcapRemote
3437 * This should be fixed in the WinPcap 4.0 alpha release.
3439 * For reference, an example remote interface:
3440 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3443 /* emulate dispatch from pcap */
3446 struct pcap_pkthdr *pkt_header;
3451 (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
3453 capture_loop_queue_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3455 capture_loop_write_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3460 pcap_src->pcap_err = TRUE;
3464 #endif /* pcap_next_ex */
3468 #ifdef LOG_CAPTURE_VERBOSE
3469 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3472 return ld->packets_captured - packet_count_before;
3476 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3477 * want to grab only the characters between the '{' and '}' delimiters.
3479 * Returns a GString that must be freed with g_string_free(). */
3481 isolate_uuid(const char *iface)
3486 ptr = strchr(iface, '{');
3488 return g_string_new(iface);
3489 gstr = g_string_new(ptr + 1);
3491 ptr = strchr(gstr->str, '}');
3495 gstr = g_string_truncate(gstr, ptr - gstr->str);
3500 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3501 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3503 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3504 char *errmsg, int errmsg_len)
3507 gchar *capfile_name;
3508 gchar *prefix, *suffix;
3509 gboolean is_tempfile;
3511 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3512 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3514 if (capture_opts->save_file != NULL) {
3515 /* We return to the caller while the capture is in progress.
3516 * Therefore we need to take a copy of save_file in
3517 * case the caller destroys it after we return.
3519 capfile_name = g_strdup(capture_opts->save_file);
3521 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3522 if (capture_opts->multi_files_on) {
3523 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3524 g_snprintf(errmsg, errmsg_len,
3525 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3526 g_free(capfile_name);
3529 if (strcmp(capfile_name, "-") == 0) {
3530 /* write to stdout */
3533 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3534 _setmode(1, O_BINARY);
3537 /* Try to open the specified FIFO for use as a capture buffer.
3538 Do *not* create it if it doesn't exist. There's nothing
3539 to truncate. If we need to read it, We Have A Problem. */
3540 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY, 0);
3542 } /* if (...output_to_pipe ... */
3545 if (capture_opts->multi_files_on) {
3546 /* ringbuffer is enabled */
3547 *save_file_fd = ringbuf_init(capfile_name,
3548 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3549 capture_opts->group_read_access);
3551 /* we need the ringbuf name */
3552 if (*save_file_fd != -1) {
3553 g_free(capfile_name);
3554 capfile_name = g_strdup(ringbuf_current_filename());
3557 /* Try to open/create the specified file for use as a capture buffer. */
3558 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY|O_TRUNC|O_CREAT,
3559 (capture_opts->group_read_access) ? 0640 : 0600);
3562 is_tempfile = FALSE;
3564 /* Choose a random name for the temporary capture buffer */
3565 if (global_capture_opts.ifaces->len > 1) {
3567 * More than one interface; just use the number of interfaces
3568 * to generate the temporary file name prefix.
3570 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3573 * One interface; use its description, if it has one, to generate
3574 * the temporary file name, otherwise use its name.
3577 const interface_options *interface_opts;
3579 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
3582 * Do we have a description?
3584 if (interface_opts->descr) {
3588 * Strip off any stuff we shouldn't use in the file name,
3589 * by getting the last component of what would be a file
3592 basename = g_path_get_basename(interface_opts->descr);
3595 * No - use the name.
3597 * Strip off any stuff we shouldn't use in the file name,
3598 * by getting the last component of what would be a file
3601 basename = g_path_get_basename(interface_opts->name);
3604 * This is Windows, where we might have an ugly GUID-based
3607 * If it's an ugly GUID-based name, use the generic portion
3608 * of the interface GUID to form the basis of the filename.
3610 if (strncmp("NPF_{", basename, 5) == 0) {
3612 * We have a GUID-based name; extract the GUID digits
3613 * as the basis of the filename.
3616 iface = isolate_uuid(basename);
3618 basename = g_strdup(iface->str);
3619 g_string_free(iface, TRUE);
3623 /* generate the temp file name prefix */
3624 prefix = g_strconcat("wireshark_", basename, NULL);
3628 /* Generate the appropriate suffix. */
3629 if (capture_opts->use_pcapng) {
3634 *save_file_fd = create_tempfile(&tmpname, prefix, suffix);
3636 capfile_name = g_strdup(tmpname);
3640 /* did we fail to open the output file? */
3641 if (*save_file_fd == -1) {
3643 g_snprintf(errmsg, errmsg_len,
3644 "The temporary file to which the capture would be saved (\"%s\") "
3645 "could not be opened: %s.", capfile_name, g_strerror(errno));
3647 if (capture_opts->multi_files_on) {
3648 ringbuf_error_cleanup();
3651 g_snprintf(errmsg, errmsg_len,
3652 "The file to which the capture would be saved (\"%s\") "
3653 "could not be opened: %s.", capfile_name,
3656 g_free(capfile_name);
3660 if (capture_opts->save_file != NULL) {
3661 g_free(capture_opts->save_file);
3663 capture_opts->save_file = capfile_name;
3664 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3665 "g_free(capfile_name)". */
3670 static time_t get_next_time_interval(int interval_s) {
3671 time_t next_time = time(NULL);
3672 next_time -= next_time % interval_s;
3673 next_time += interval_s;
3677 /* Do the work of handling either the file size or file duration capture
3678 conditions being reached, and switching files or stopping. */
3680 do_file_switch_or_stop(capture_options *capture_opts)
3682 gboolean successful;
3684 if (capture_opts->multi_files_on) {
3685 if (capture_opts->has_autostop_files &&
3686 ++global_ld.file_count >= capture_opts->autostop_files) {
3687 /* no files left: stop here */
3688 global_ld.go = FALSE;
3692 /* Switch to the next ringbuffer file */
3693 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3694 &global_ld.save_file_fd, &global_ld.err)) {
3696 /* File switch succeeded: reset the conditions */
3697 global_ld.bytes_written = 0;
3698 global_ld.packets_written = 0;
3699 if (capture_opts->use_pcapng) {
3700 successful = capture_loop_init_pcapng_output(capture_opts, &global_ld);
3702 capture_src *pcap_src;
3703 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3704 successful = libpcap_write_file_header(global_ld.pdh, pcap_src->linktype, pcap_src->snaplen,
3705 pcap_src->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3709 fclose(global_ld.pdh);
3710 global_ld.pdh = NULL;
3711 global_ld.go = FALSE;
3714 if (global_ld.file_duration_timer) {
3715 g_timer_reset(global_ld.file_duration_timer);
3717 if (global_ld.next_interval_time) {
3718 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
3720 fflush(global_ld.pdh);
3722 report_packet_count(global_ld.inpkts_to_sync_pipe);
3723 global_ld.inpkts_to_sync_pipe = 0;
3724 report_new_capture_file(capture_opts->save_file);
3726 /* File switch failed: stop here */
3727 global_ld.go = FALSE;
3731 /* single file, stop now */
3732 global_ld.go = FALSE;
3739 pcap_read_handler(void* arg)
3741 capture_src *pcap_src = (capture_src *)arg;
3742 char errmsg[MSG_MAX_LENGTH+1];
3744 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3745 pcap_src->interface_id);
3747 /* If this is a pipe input it might finish early. */
3748 while (global_ld.go && pcap_src->cap_pipe_err == PIPOK) {
3749 /* dispatch incoming packets */
3750 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_src);
3753 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3754 pcap_src->interface_id);
3755 g_thread_exit(NULL);
3759 /* Try to pop an item off the packet queue and if it exists, write it */
3761 capture_loop_dequeue_packet(void) {
3762 pcap_queue_element *queue_element;
3764 g_async_queue_lock(pcap_queue);
3765 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3766 if (queue_element) {
3767 if (queue_element->pcap_src->from_pcapng) {
3768 pcap_queue_bytes -= queue_element->u.bh.block_total_length;
3770 pcap_queue_bytes -= queue_element->u.phdr.caplen;
3772 pcap_queue_packets -= 1;
3774 g_async_queue_unlock(pcap_queue);
3775 if (queue_element) {
3776 if (queue_element->pcap_src->from_pcapng) {
3777 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3778 "Dequeued a block of type 0x%08x of length %d captured on interface %d.",
3779 queue_element->u.bh.block_type, queue_element->u.bh.block_total_length,
3780 queue_element->pcap_src->interface_id);
3782 capture_loop_write_pcapng_cb(queue_element->pcap_src,
3783 &queue_element->u.bh,
3786 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3787 "Dequeued a packet of length %d captured on interface %d.",
3788 queue_element->u.phdr.caplen, queue_element->pcap_src->interface_id);
3790 capture_loop_write_packet_cb((u_char *) queue_element->pcap_src,
3791 &queue_element->u.phdr,
3794 g_free(queue_element->pd);
3795 g_free(queue_element);
3801 /* Do the low-level work of a capture.
3802 Returns TRUE if it succeeds, FALSE otherwise. */
3804 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3807 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3809 struct timeval upd_time, cur_time;
3813 GTimer *autostop_duration_timer = NULL;
3816 gboolean cfilter_error = FALSE;
3817 char errmsg[MSG_MAX_LENGTH+1];
3818 char secondary_errmsg[MSG_MAX_LENGTH+1];
3819 capture_src *pcap_src;
3820 interface_options *interface_opts;
3821 guint i, error_index = 0;
3824 *secondary_errmsg = '\0';
3826 /* init the loop data */
3827 global_ld.go = TRUE;
3828 global_ld.packets_captured = 0;
3830 global_ld.report_packet_count = FALSE;
3832 global_ld.inpkts_to_sync_pipe = 0;
3833 global_ld.err = 0; /* no error seen yet */
3834 global_ld.pdh = NULL;
3835 global_ld.save_file_fd = -1;
3836 global_ld.file_count = 0;
3837 global_ld.file_duration_timer = NULL;
3838 global_ld.next_interval_time = 0;
3839 global_ld.interval_s = 0;
3841 /* We haven't yet gotten the capture statistics. */
3842 *stats_known = FALSE;
3844 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3845 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3847 /* open the "input file" from network interface or capture pipe */
3848 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3849 secondary_errmsg, sizeof(secondary_errmsg))) {
3852 for (i = 0; i < capture_opts->ifaces->len; i++) {
3853 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3854 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
3855 /* init the input filter from the network interface (capture pipe will do nothing) */
3857 * When remote capturing WinPCap crashes when the capture filter
3858 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3861 switch (capture_loop_init_filter(pcap_src->pcap_h, pcap_src->from_cap_pipe,
3862 interface_opts->name,
3863 interface_opts->cfilter?interface_opts->cfilter:"")) {
3865 case INITFILTER_NO_ERROR:
3868 case INITFILTER_BAD_FILTER:
3869 cfilter_error = TRUE;
3871 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
3874 case INITFILTER_OTHER_ERROR:
3875 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3876 pcap_geterr(pcap_src->pcap_h));
3877 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3882 /* If we're supposed to write to a capture file, open it for output
3883 (temporary/specified name/ringbuffer) */
3884 if (capture_opts->saving_to_file) {
3885 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3886 errmsg, sizeof(errmsg))) {
3890 /* set up to write to the already-opened capture output file/files */
3891 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3896 /* XXX - capture SIGTERM and close the capture, in case we're on a
3897 Linux 2.0[.x] system and you have to explicitly close the capture
3898 stream in order to turn promiscuous mode off? We need to do that
3899 in other places as well - and I don't think that works all the
3900 time in any case, due to libpcap bugs. */
3902 /* Well, we should be able to start capturing.
3904 Sync out the capture file, so the header makes it to the file system,
3905 and send a "capture started successfully and capture file created"
3906 message to our parent so that they'll open the capture file and
3907 update its windows to indicate that we have a live capture in
3909 fflush(global_ld.pdh);
3910 report_new_capture_file(capture_opts->save_file);
3913 if (capture_opts->has_file_interval) {
3914 global_ld.interval_s = capture_opts->file_interval;
3915 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
3917 /* create stop conditions */
3918 if (capture_opts->has_autostop_filesize) {
3919 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3920 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3923 if (capture_opts->has_autostop_duration) {
3924 autostop_duration_timer = g_timer_new();
3927 if (capture_opts->multi_files_on) {
3928 if (capture_opts->has_file_duration) {
3929 global_ld.file_duration_timer = g_timer_new();
3933 /* init the time values */
3935 upd_time = GetTickCount();
3937 gettimeofday(&upd_time, NULL);
3939 start_time = create_timestamp();
3940 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3941 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3943 /* WOW, everything is prepared! */
3944 /* please fasten your seat belts, we will enter now the actual capture loop */
3946 pcap_queue = g_async_queue_new();
3947 pcap_queue_bytes = 0;
3948 pcap_queue_packets = 0;
3949 for (i = 0; i < global_ld.pcaps->len; i++) {
3950 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3951 /* XXX - Add an interface name here? */
3952 pcap_src->tid = g_thread_new("Capture read", pcap_read_handler, pcap_src);
3955 while (global_ld.go) {
3956 /* dispatch incoming packets */
3958 gboolean dequeued = capture_loop_dequeue_packet();
3966 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3967 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3968 sizeof(errmsg), pcap_src);
3971 /* Stop capturing if all of our sources are pipes and none of them are open. */
3972 gboolean open_interfaces = FALSE;
3973 for (i = 0; i < global_ld.pcaps->len; i++) {
3974 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3975 if (pcap_src->cap_pipe_err == PIPOK) {
3976 /* True for both non-pipes and open pipes. */
3977 open_interfaces = TRUE;
3980 if (!open_interfaces) {
3981 global_ld.go = FALSE;
3985 /* Were we asked to print packet counts by the SIGINFO handler? */
3986 if (global_ld.report_packet_count) {
3987 fprintf(stderr, "%u packet%s captured\n", global_ld.packets_captured,
3988 plurality(global_ld.packets_captured, "", "s"));
3989 global_ld.report_packet_count = FALSE;
3994 /* any news from our parent (signal pipe)? -> just stop the capture */
3995 if (!signal_pipe_check_running()) {
3996 global_ld.go = FALSE;
4001 global_ld.inpkts_to_sync_pipe += inpkts;
4003 if (capture_opts->output_to_pipe) {
4004 fflush(global_ld.pdh);
4008 /* Only update once every 500ms so as not to overload slow displays.
4009 * This also prevents too much context-switching between the dumpcap
4010 * and wireshark processes.
4012 #define DUMPCAP_UPD_TIME 500
4015 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
4016 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) /* wrap just causes an extra update */
4018 gettimeofday(&cur_time, NULL);
4019 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
4020 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000))
4024 upd_time = cur_time;
4027 if (pcap_stats(pch, stats) >= 0) {
4028 *stats_known = TRUE;
4031 /* Let the parent process know. */
4032 if (global_ld.inpkts_to_sync_pipe) {
4034 fflush(global_ld.pdh);
4036 /* Send our parent a message saying we've written out
4037 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
4039 report_packet_count(global_ld.inpkts_to_sync_pipe);
4041 global_ld.inpkts_to_sync_pipe = 0;
4044 /* check capture duration condition */
4045 if (autostop_duration_timer != NULL && g_timer_elapsed(autostop_duration_timer, NULL) >= capture_opts->autostop_duration) {
4046 /* The maximum capture time has elapsed; stop the capture. */
4047 global_ld.go = FALSE;
4051 /* check capture file duration condition */
4052 if (global_ld.file_duration_timer != NULL && g_timer_elapsed(global_ld.file_duration_timer, NULL) >= capture_opts->file_duration) {
4053 /* duration limit reached, do we have another file? */
4054 if (!do_file_switch_or_stop(capture_opts))
4056 } /* cnd_file_duration */
4058 /* check capture file interval condition */
4059 if (global_ld.interval_s && time(NULL) >= global_ld.next_interval_time) {
4060 /* end of interval reached, do we have another file? */
4061 if (!do_file_switch_or_stop(capture_opts))
4063 } /* cnd_file_interval */
4067 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
4070 for (i = 0; i < global_ld.pcaps->len; i++) {
4071 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4072 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
4073 pcap_src->interface_id);
4074 g_thread_join(pcap_src->tid);
4075 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
4076 pcap_src->interface_id);
4079 gboolean dequeued = capture_loop_dequeue_packet();
4083 global_ld.inpkts_to_sync_pipe += 1;
4084 if (capture_opts->output_to_pipe) {
4085 fflush(global_ld.pdh);
4091 /* delete stop conditions */
4092 if (global_ld.file_duration_timer != NULL)
4093 g_timer_destroy(global_ld.file_duration_timer);
4094 if (autostop_duration_timer != NULL)
4095 g_timer_destroy(autostop_duration_timer);
4097 /* did we have a pcap (input) error? */
4098 for (i = 0; i < capture_opts->ifaces->len; i++) {
4099 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4100 if (pcap_src->pcap_err) {
4101 /* On Linux, if an interface goes down while you're capturing on it,
4102 you'll get a "recvfrom: Network is down" or
4103 "The interface went down" error (ENETDOWN).
4104 (At least you will if g_strerror() doesn't show a local translation
4107 On FreeBSD, DragonFly BSD, and macOS, if a network adapter
4108 disappears while you're capturing on it, you'll get a
4109 "read: Device not configured" error (ENXIO). (See previous
4110 parenthetical note.)
4112 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
4114 These should *not* be reported to the Wireshark developers. */
4117 cap_err_str = pcap_geterr(pcap_src->pcap_h);
4118 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
4119 strcmp(cap_err_str, "The interface went down") == 0 ||
4120 strcmp(cap_err_str, "read: Device not configured") == 0 ||
4121 strcmp(cap_err_str, "read: I/O error") == 0 ||
4122 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
4123 report_capture_error("The network adapter on which the capture was being done "
4124 "is no longer running; the capture has stopped.",
4127 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
4129 report_capture_error(errmsg, please_report);
4132 } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
4133 report_capture_error(errmsg, "");
4137 /* did we have an output error while capturing? */
4138 if (global_ld.err == 0) {
4141 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4142 sizeof(secondary_errmsg),
4143 capture_opts->save_file, global_ld.err, FALSE);
4144 report_capture_error(errmsg, secondary_errmsg);
4148 if (capture_opts->saving_to_file) {
4149 /* close the output file */
4150 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
4154 /* there might be packets not yet notified to the parent */
4155 /* (do this after closing the file, so all packets are already flushed) */
4156 if (global_ld.inpkts_to_sync_pipe) {
4158 report_packet_count(global_ld.inpkts_to_sync_pipe);
4159 global_ld.inpkts_to_sync_pipe = 0;
4162 /* If we've displayed a message about a write error, there's no point
4163 in displaying another message about an error on close. */
4164 if (!close_ok && write_ok) {
4165 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4166 sizeof(secondary_errmsg),
4167 capture_opts->save_file, err_close, TRUE);
4168 report_capture_error(errmsg, secondary_errmsg);
4172 * XXX We exhibit different behaviour between normal mode and sync mode
4173 * when the pipe is stdin and not already at EOF. If we're a child, the
4174 * parent's stdin isn't closed, so if the user starts another capture,
4175 * cap_pipe_open_live() will very likely not see the expected magic bytes and
4176 * will say "Unrecognized libpcap format". On the other hand, in normal
4177 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
4180 report_capture_count(TRUE);
4182 /* get packet drop statistics from pcap */
4183 for (i = 0; i < capture_opts->ifaces->len; i++) {
4185 guint32 pcap_dropped = 0;
4187 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4188 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4189 received = pcap_src->received;
4190 if (pcap_src->pcap_h != NULL) {
4191 g_assert(!pcap_src->from_cap_pipe);
4192 /* Get the capture statistics, so we know how many packets were dropped. */
4194 * Older versions of libpcap didn't set ps_ifdrop on some
4195 * platforms; initialize it to 0 to handle that.
4197 stats->ps_ifdrop = 0;
4198 if (pcap_stats(pcap_src->pcap_h, stats) >= 0) {
4199 *stats_known = TRUE;
4200 /* Let the parent process know. */
4201 pcap_dropped += stats->ps_drop;
4203 g_snprintf(errmsg, sizeof(errmsg),
4204 "Can't get packet-drop statistics: %s",
4205 pcap_geterr(pcap_src->pcap_h));
4206 report_capture_error(errmsg, please_report);
4209 report_packet_drops(received, pcap_dropped, pcap_src->dropped, pcap_src->flushed, stats->ps_ifdrop, interface_opts->display_name);
4212 /* close the input file (pcap or capture pipe) */
4213 capture_loop_close_input(&global_ld);
4215 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
4217 /* ok, if the write and the close were successful. */
4218 return write_ok && close_ok;
4221 if (capture_opts->multi_files_on) {
4222 /* cleanup ringbuffer */
4223 ringbuf_error_cleanup();
4225 /* We can't use the save file, and we have no FILE * for the stream
4226 to close in order to close it, so close the FD directly. */
4227 if (global_ld.save_file_fd != -1) {
4228 ws_close(global_ld.save_file_fd);
4231 /* We couldn't even start the capture, so get rid of the capture
4233 if (capture_opts->save_file != NULL) {
4234 ws_unlink(capture_opts->save_file);
4235 g_free(capture_opts->save_file);
4238 capture_opts->save_file = NULL;
4240 report_cfilter_error(capture_opts, error_index, errmsg);
4242 report_capture_error(errmsg, secondary_errmsg);
4244 /* close the input file (pcap or cap_pipe) */
4245 capture_loop_close_input(&global_ld);
4247 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
4254 capture_loop_stop(void)
4256 #ifdef HAVE_PCAP_BREAKLOOP
4258 capture_src *pcap_src;
4260 for (i = 0; i < global_ld.pcaps->len; i++) {
4261 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4262 if (pcap_src->pcap_h != NULL)
4263 pcap_breakloop(pcap_src->pcap_h);
4266 global_ld.go = FALSE;
4271 capture_loop_get_errmsg(char *errmsg, size_t errmsglen, char *secondary_errmsg,
4272 size_t secondary_errmsglen, const char *fname,
4273 int err, gboolean is_close)
4275 static const char find_space[] =
4276 "You will need to free up space on that file system"
4277 " or put the capture file on a different file system.";
4282 g_snprintf(errmsg, (gulong)errmsglen,
4283 "Not all the packets could be written to the file"
4284 " to which the capture was being saved\n"
4285 "(\"%s\") because there is no space left on the file system\n"
4286 "on which that file resides.",
4288 g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen, "%s",
4294 g_snprintf(errmsg, (gulong)errmsglen,
4295 "Not all the packets could be written to the file"
4296 " to which the capture was being saved\n"
4297 "(\"%s\") because you are too close to, or over,"
4298 " your disk quota\n"
4299 "on the file system on which that file resides.",
4301 g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen, "%s",
4308 g_snprintf(errmsg, (gulong)errmsglen,
4309 "The file to which the capture was being saved\n"
4310 "(\"%s\") could not be closed: %s.",
4311 fname, g_strerror(err));
4313 g_snprintf(errmsg, (gulong)errmsglen,
4314 "An error occurred while writing to the file"
4315 " to which the capture was being saved\n"
4317 fname, g_strerror(err));
4319 g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen,
4320 "%s", please_report);
4326 * We wrote one packet. Update some statistics and check if we've met any
4327 * autostop or ring buffer conditions.
4330 capture_loop_wrote_one_packet(capture_src *pcap_src) {
4331 global_ld.packets_captured++;
4332 global_ld.packets_written++;
4333 pcap_src->received++;
4335 /* check -c NUM / -a packets:NUM */
4336 if (global_capture_opts.has_autostop_packets && global_ld.packets_captured >= global_capture_opts.autostop_packets) {
4337 fflush(global_ld.pdh);
4338 global_ld.go = FALSE;
4341 /* check -b packets:NUM */
4342 if (global_capture_opts.has_file_packets && global_ld.packets_written >= global_capture_opts.file_packets) {
4343 do_file_switch_or_stop(&global_capture_opts);
4346 /* check -a filesize:NUM */
4347 if (global_capture_opts.has_autostop_filesize &&
4348 global_capture_opts.autostop_filesize > 0 &&
4349 global_ld.bytes_written / 1000 >= global_capture_opts.autostop_filesize) {
4350 /* Capture size limit reached, do we have another file? */
4351 do_file_switch_or_stop(&global_capture_opts);
4356 /* one pcapng block was captured, process it */
4358 capture_loop_write_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, u_char *pd)
4363 * This should never be called if we're not writing pcapng.
4365 g_assert(global_capture_opts.use_pcapng);
4367 /* We may be called multiple times from pcap_dispatch(); if we've set
4368 the "stop capturing" flag, ignore this packet, as we're not
4369 supposed to be saving any more packets. */
4370 if (!global_ld.go) {
4371 pcap_src->flushed++;
4375 if (!pcapng_adjust_block(pcap_src, bh, pd)) {
4376 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "%s failed to adjust pcapng block.", G_STRFUNC);
4377 g_assert_not_reached();
4381 if (bh->block_type == BLOCK_TYPE_SHB && !global_ld.pcapng_passthrough) {
4383 * capture_loop_init_pcapng_output should've handled this. We need
4384 * to write ISBs when they're initially read so we shouldn't skip
4390 if (global_ld.pdh) {
4391 gboolean successful;
4393 /* We're supposed to write the packet to a file; do so.
4394 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4395 "ld->err" to the error. */
4396 successful = pcapng_write_block(global_ld.pdh,
4398 bh->block_total_length,
4399 &global_ld.bytes_written, &err);
4401 fflush(global_ld.pdh);
4403 global_ld.go = FALSE;
4404 global_ld.err = err;
4405 pcap_src->dropped++;
4406 } else if (bh->block_type == BLOCK_TYPE_EPB || bh->block_type == BLOCK_TYPE_SPB || bh->block_type == BLOCK_TYPE_SYSTEMD_JOURNAL) {
4407 /* count packet only if we actually have an EPB or SPB */
4408 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4409 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4410 "Wrote a pcapng block type %u of length %d captured on interface %u.",
4411 bh->block_type, bh->block_total_length, pcap_src->interface_id);
4413 capture_loop_wrote_one_packet(pcap_src);
4418 /* one pcap packet was captured, process it */
4420 capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4423 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4425 guint ts_mul = pcap_src->ts_nsec ? 1000000000 : 1000000;
4427 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_write_packet_cb");
4429 /* We may be called multiple times from pcap_dispatch(); if we've set
4430 the "stop capturing" flag, ignore this packet, as we're not
4431 supposed to be saving any more packets. */
4432 if (!global_ld.go) {
4433 pcap_src->flushed++;
4437 if (global_ld.pdh) {
4438 gboolean successful;
4440 /* We're supposed to write the packet to a file; do so.
4441 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4442 "ld->err" to the error. */
4443 if (global_capture_opts.use_pcapng) {
4444 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4446 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4447 phdr->caplen, phdr->len,
4448 pcap_src->interface_id,
4451 &global_ld.bytes_written, &err);
4453 successful = libpcap_write_packet(global_ld.pdh,
4454 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4455 phdr->caplen, phdr->len,
4457 &global_ld.bytes_written, &err);
4460 global_ld.go = FALSE;
4461 global_ld.err = err;
4462 pcap_src->dropped++;
4464 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4465 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4466 "Wrote a pcap packet of length %d captured on interface %u.",
4467 phdr->caplen, pcap_src->interface_id);
4469 capture_loop_wrote_one_packet(pcap_src);
4474 /* one packet was captured, queue it */
4476 capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4479 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4480 pcap_queue_element *queue_element;
4481 gboolean limit_reached;
4483 /* We may be called multiple times from pcap_dispatch(); if we've set
4484 the "stop capturing" flag, ignore this packet, as we're not
4485 supposed to be saving any more packets. */
4486 if (!global_ld.go) {
4487 pcap_src->flushed++;
4491 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4492 if (queue_element == NULL) {
4493 pcap_src->dropped++;
4496 queue_element->pcap_src = pcap_src;
4497 queue_element->u.phdr = *phdr;
4498 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4499 if (queue_element->pd == NULL) {
4500 pcap_src->dropped++;
4501 g_free(queue_element);
4504 memcpy(queue_element->pd, pd, phdr->caplen);
4505 g_async_queue_lock(pcap_queue);
4506 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4507 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4508 limit_reached = FALSE;
4509 g_async_queue_push_unlocked(pcap_queue, queue_element);
4510 pcap_queue_bytes += phdr->caplen;
4511 pcap_queue_packets += 1;
4513 limit_reached = TRUE;
4515 g_async_queue_unlock(pcap_queue);
4516 if (limit_reached) {
4517 pcap_src->dropped++;
4518 g_free(queue_element->pd);
4519 g_free(queue_element);
4520 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4521 "Dropped a packet of length %d captured on interface %u.",
4522 phdr->caplen, pcap_src->interface_id);
4524 pcap_src->received++;
4525 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4526 "Queued a packet of length %d captured on interface %u.",
4527 phdr->caplen, pcap_src->interface_id);
4529 /* I don't want to hold the mutex over the debug output. So the
4530 output may be wrong */
4531 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4532 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4533 pcap_queue_bytes, pcap_queue_packets);
4536 /* one pcapng block was captured, queue it */
4538 capture_loop_queue_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, u_char *pd)
4540 pcap_queue_element *queue_element;
4541 gboolean limit_reached;
4543 /* We may be called multiple times from pcap_dispatch(); if we've set
4544 the "stop capturing" flag, ignore this packet, as we're not
4545 supposed to be saving any more packets. */
4546 if (!global_ld.go) {
4547 pcap_src->flushed++;
4551 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4552 if (queue_element == NULL) {
4553 pcap_src->dropped++;
4556 queue_element->pcap_src = pcap_src;
4557 queue_element->u.bh = *bh;
4558 queue_element->pd = (u_char *)g_malloc(bh->block_total_length);
4559 if (queue_element->pd == NULL) {
4560 pcap_src->dropped++;
4561 g_free(queue_element);
4564 memcpy(queue_element->pd, pd, bh->block_total_length);
4565 g_async_queue_lock(pcap_queue);
4566 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4567 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4568 limit_reached = FALSE;
4569 g_async_queue_push_unlocked(pcap_queue, queue_element);
4570 pcap_queue_bytes += bh->block_total_length;
4571 pcap_queue_packets += 1;
4573 limit_reached = TRUE;
4575 g_async_queue_unlock(pcap_queue);
4576 if (limit_reached) {
4577 pcap_src->dropped++;
4578 g_free(queue_element->pd);
4579 g_free(queue_element);
4580 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4581 "Dropped a packet of length %d captured on interface %u.",
4582 bh->block_total_length, pcap_src->interface_id);
4584 pcap_src->received++;
4585 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4586 "Queued a block of type 0x%08x of length %d captured on interface %u.",
4587 bh->block_type, bh->block_total_length, pcap_src->interface_id);
4589 /* I don't want to hold the mutex over the debug output. So the
4590 output may be wrong */
4591 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4592 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4593 pcap_queue_bytes, pcap_queue_packets);
4597 set_80211_channel(const char *iface, const char *opt)
4601 guint32 center_freq1 = 0;
4602 guint32 center_freq2 = 0;
4605 gchar **options = NULL;
4607 options = g_strsplit_set(opt, ",", 4);
4608 for (args = 0; options[args]; args++);
4611 freq = get_nonzero_guint32(options[0], "802.11 channel frequency");
4613 if (args >= 1 && options[1]) {
4614 type = ws80211_str_to_chan_type(options[1]);
4616 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
4622 if (args >= 2 && options[2])
4623 center_freq1 = get_nonzero_guint32(options[2], "VHT center frequency");
4625 if (args >= 3 && options[3])
4626 center_freq2 = get_nonzero_guint32(options[3], "VHT center frequency 2");
4628 ret = ws80211_init();
4630 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4634 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
4637 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4643 pipe_write_block(2, SP_SUCCESS, NULL);
4646 g_strfreev(options);
4651 get_dumpcap_compiled_info(GString *str)
4653 /* Capture libraries */
4654 g_string_append(str, ", ");
4655 get_compiled_caplibs_version(str);
4659 get_dumpcap_runtime_info(GString *str)
4661 /* Capture libraries */
4662 g_string_append(str, ", ");
4663 get_runtime_caplibs_version(str);
4666 /* And now our feature presentation... [ fade to music ] */
4668 main(int argc, char *argv[])
4671 static const struct option long_options[] = {
4672 {"help", no_argument, NULL, 'h'},
4673 {"version", no_argument, NULL, 'v'},
4674 LONGOPT_CAPTURE_COMMON
4678 gboolean arg_error = FALSE;
4684 struct sigaction action, oldaction;
4687 gboolean start_capture = TRUE;
4688 gboolean stats_known;
4689 struct pcap_stat stats;
4690 GLogLevelFlags log_flags;
4691 gboolean list_interfaces = FALSE;
4692 int caps_queries = 0;
4693 #ifdef HAVE_BPF_IMAGE
4694 gboolean print_bpf_code = FALSE;
4696 gboolean set_chan = FALSE;
4697 gchar *set_chan_arg = NULL;
4698 gboolean machine_readable = FALSE;
4699 gboolean print_statistics = FALSE;
4700 int status, run_once_args = 0;
4703 #if defined(__APPLE__) && defined(__LP64__)
4704 struct utsname osinfo;
4708 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
4710 /* Initialize the version information. */
4711 ws_init_version_info("Dumpcap (Wireshark)", NULL, get_dumpcap_compiled_info,
4712 get_dumpcap_runtime_info);
4715 create_app_running_mutex();
4718 * Initialize our DLL search path. MUST be called before LoadLibrary
4721 ws_init_dll_search_path();
4724 #ifdef HAVE_BPF_IMAGE
4725 #define OPTSTRING_d "d"
4727 #define OPTSTRING_d ""
4730 #ifdef HAVE_PCAP_REMOTE
4731 #define OPTSTRING_r "r"
4732 #define OPTSTRING_u "u"
4734 #define OPTSTRING_r ""
4735 #define OPTSTRING_u ""
4738 #ifdef HAVE_PCAP_SETSAMPLING
4739 #define OPTSTRING_m "m:"
4741 #define OPTSTRING_m ""
4744 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
4746 #ifdef DEBUG_CHILD_DUMPCAP
4747 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4748 fprintf (stderr, "Unable to open debug log file .\n");
4753 #if defined(__APPLE__) && defined(__LP64__)
4755 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4756 * a bug workaround - timeouts less than 1 second don't work with libpcap
4757 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4758 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4759 * The problem is extremely unlikely to be reintroduced in a future
4762 if (uname(&osinfo) == 0) {
4764 * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
4765 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4766 * number of 10.0.0, not 10.1.0 - go figure).
4768 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4769 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4770 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4771 need_timeout_workaround = TRUE;
4776 * Determine if dumpcap is being requested to run in a special
4777 * capture_child mode by going thru the command line args to see if
4778 * a -Z is present. (-Z is a hidden option).
4780 * The primary result of running in capture_child mode is that
4781 * all messages sent out on stderr are in a special type/len/string
4782 * format to allow message processing by type. These messages include
4783 * error messages if dumpcap fails to start the operation it was
4784 * requested to do, as well as various "status" messages which are sent
4785 * when an actual capture is in progress, and a "success" message sent
4786 * if dumpcap was requested to perform an operation other than a
4789 * Capture_child mode would normally be requested by a parent process
4790 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4791 * to which dumpcap stderr has been redirected. It might also have
4792 * another pipe to obtain dumpcap stdout output; for operations other
4793 * than a capture, that information is formatted specially for easier
4794 * parsing by the parent process.
4796 * Capture_child mode needs to be determined immediately upon
4797 * startup so that any messages generated by dumpcap in this mode
4798 * (eg: during initialization) will be formatted properly.
4801 for (i=1; i<argc; i++) {
4802 if (strcmp("-Z", argv[i]) == 0) {
4803 capture_child = TRUE;
4804 machine_readable = TRUE; /* request machine-readable output */
4806 /* set output pipe to binary mode, to avoid ugly text conversions */
4807 _setmode(2, O_BINARY);
4812 /* The default_log_handler will use stdout, which makes trouble in */
4813 /* capture child mode, as it uses stdout for its sync_pipe. */
4814 /* So: the filtering is done in the console_log_handler and not here.*/
4815 /* We set the log handlers right up front to make sure that any log */
4816 /* messages when running as child will be sent back to the parent */
4817 /* with the correct format. */
4822 G_LOG_LEVEL_CRITICAL|
4823 G_LOG_LEVEL_WARNING|
4824 G_LOG_LEVEL_MESSAGE|
4828 G_LOG_FLAG_RECURSION);
4830 g_log_set_handler(NULL,
4832 console_log_handler, NULL /* user_data */);
4833 g_log_set_handler(LOG_DOMAIN_MAIN,
4835 console_log_handler, NULL /* user_data */);
4836 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4838 console_log_handler, NULL /* user_data */);
4839 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4841 console_log_handler, NULL /* user_data */);
4843 /* Initialize the pcaps list and IDBs */
4844 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(capture_src *));
4845 global_ld.pcapng_passthrough = FALSE;
4846 global_ld.saved_shb = NULL;
4847 global_ld.saved_idbs = g_array_new(FALSE, TRUE, sizeof(saved_idb_t));
4850 /* Load wpcap if possible. Do this before collecting the run-time version information */
4853 /* ... and also load the packet.dll from wpcap */
4854 /* XXX - currently not required, may change later. */
4855 /*wpcap_packet_load();*/
4857 /* Start windows sockets */
4858 result = WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4861 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_ERROR,
4862 "ERROR: WSAStartup failed with error: %d", result);
4866 /* Set handler for Ctrl+C key */
4867 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4869 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4870 and exit. Do the same with SIGPIPE, in case, for example,
4871 we're writing to our standard output and it's a pipe.
4872 Do the same with SIGHUP if it's not being ignored (if we're
4873 being run under nohup, it might be ignored, in which case we
4874 should leave it ignored).
4876 XXX - apparently, Coverity complained that part of action
4877 wasn't initialized. Perhaps it's running on Linux, where
4878 struct sigaction has an ignored "sa_restorer" element and
4879 where "sa_handler" and "sa_sigaction" might not be two
4880 members of a union. */
4881 memset(&action, 0, sizeof(action));
4882 action.sa_handler = capture_cleanup_handler;
4884 * Arrange that system calls not get restarted, because when
4885 * our signal handler returns we don't want to restart
4886 * a call that was waiting for packets to arrive.
4888 action.sa_flags = 0;
4889 sigemptyset(&action.sa_mask);
4890 sigaction(SIGTERM, &action, NULL);
4891 sigaction(SIGINT, &action, NULL);
4892 sigaction(SIGPIPE, &action, NULL);
4893 sigaction(SIGHUP, NULL, &oldaction);
4894 if (oldaction.sa_handler == SIG_DFL)
4895 sigaction(SIGHUP, &action, NULL);
4898 /* Catch SIGINFO and, if we get it and we're capturing in
4899 quiet mode, report the number of packets we've captured. */
4900 action.sa_handler = report_counts_siginfo;
4901 action.sa_flags = SA_RESTART;
4902 sigemptyset(&action.sa_mask);
4903 sigaction(SIGINFO, &action, NULL);
4904 #endif /* SIGINFO */
4907 /* ----------------------------------------------------------------- */
4908 /* Privilege and capability handling */
4910 /* 1. Running not as root or suid root; no special capabilities. */
4913 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4916 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4918 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4919 /* capabilities; Drop all other capabilities; */
4920 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4921 /* else: after pcap_open_live() in capture_loop_open_input() */
4922 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4923 /* (Note: this means that the process, although logged in */
4924 /* as root, does not have various permissions such as the */
4925 /* ability to bypass file access permissions). */
4926 /* XXX: Should we just leave capabilities alone in this case */
4927 /* so that user gets expected effect that root can do */
4930 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4932 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4933 /* else: after pcap_open_live() in capture_loop_open_input() */
4934 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4935 /* pcap_open_live). */
4937 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4939 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4940 /* capabilities; Drop all other capabilities; */
4941 /* Drop suid privileges (euid=ruid); */
4942 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4943 /* else: after pcap_open_live() in capture_loop_open_input() */
4944 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4946 /* XXX: For some Linux versions/distros with capabilities */
4947 /* a 'normal' process with any capabilities cannot be */
4948 /* 'killed' (signaled) from another (same uid) non-privileged */
4950 /* For example: If (non-suid) Wireshark forks a */
4951 /* child suid dumpcap which acts as described here (case 5), */
4952 /* Wireshark will be unable to kill (signal) the child */
4953 /* dumpcap process until the capabilities have been dropped */
4954 /* (after pcap_open_live()). */
4955 /* This behaviour will apparently be changed in the kernel */
4956 /* to allow the kill (signal) in this case. */
4957 /* See the following for details: */
4958 /* https://www.mail-archive.com/ [wrapped] */
4959 /* linux-security-module@vger.kernel.org/msg02913.html */
4961 /* It is therefore conceivable that if dumpcap somehow hangs */
4962 /* in pcap_open_live or before that wireshark will not */
4963 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4964 /* In this case, exiting wireshark will kill the child */
4965 /* dumpcap process. */
4967 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4968 /* capabilities; Using libcap. Note: capset cmd (which see) */
4969 /* used to assign capabilities to file. */
4971 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4972 /* else: after pcap_open_live() in capture_loop_open_input() */
4973 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4975 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4976 /* longer required (similar to capture). */
4978 /* ----------------------------------------------------------------- */
4980 init_process_policies();
4983 /* If 'started with special privileges' (and using libcap) */
4984 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4985 /* Set euid/egid = ruid/rgid to remove suid privileges */
4986 relinquish_privs_except_capture();
4989 /* Set the initial values in the capture options. This might be overwritten
4990 by the command line parameters. */
4991 capture_opts_init(&global_capture_opts);
4992 /* We always save to a file - if no file was specified, we save to a
4994 global_capture_opts.saving_to_file = TRUE;
4995 global_capture_opts.has_ring_num_files = TRUE;
4997 /* Pass on capture_child mode for capture_opts */
4998 global_capture_opts.capture_child = capture_child;
5000 /* Now get our args */
5001 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
5003 case 'h': /* Print help and exit */
5004 show_help_header("Capture network packets and dump them into a pcapng or pcap file.");
5005 print_usage(stdout);
5008 case 'v': /* Show version and exit */
5012 /*** capture option specific ***/
5013 case 'a': /* autostop criteria */
5014 case 'b': /* Ringbuffer option */
5015 case 'c': /* Capture x packets */
5016 case 'f': /* capture filter */
5017 case 'g': /* enable group read access on file(s) */
5018 case 'i': /* Use interface x */
5019 case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
5020 case 'n': /* Use pcapng format */
5021 case 'p': /* Don't capture in promiscuous mode */
5022 case 'P': /* Use pcap format */
5023 case 's': /* Set the snapshot (capture) length */
5024 case 'w': /* Write to capture file x */
5025 case 'y': /* Set the pcap data link type */
5026 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
5027 #ifdef HAVE_PCAP_REMOTE
5028 case 'u': /* Use UDP for data transfer */
5029 case 'r': /* Capture own RPCAP traffic too */
5030 case 'A': /* Authentication */
5032 #ifdef HAVE_PCAP_SETSAMPLING
5033 case 'm': /* Sampling */
5035 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
5036 case 'B': /* Buffer size */
5038 #ifdef HAVE_PCAP_CREATE
5039 case 'I': /* Monitor mode */
5041 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
5046 /*** hidden option: Wireshark child mode (using binary output messages) ***/
5048 capture_child = TRUE;
5050 /* set output pipe to binary mode, to avoid ugly text conversions */
5051 _setmode(2, O_BINARY);
5053 * optarg = the control ID, aka the PPID, currently used for the
5056 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
5057 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
5058 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
5059 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
5061 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
5062 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5063 "Signal pipe: Unable to open %s. Dead parent?",
5071 case 'q': /* Quiet */
5077 /*** all non capture option specific ***/
5078 case 'D': /* Print a list of capture devices and exit */
5079 if (!list_interfaces) {
5080 list_interfaces = TRUE;
5084 case 'L': /* Print list of link-layer types and exit */
5085 if (!(caps_queries & CAPS_QUERY_LINK_TYPES)) {
5086 caps_queries |= CAPS_QUERY_LINK_TYPES;
5090 case LONGOPT_LIST_TSTAMP_TYPES:
5091 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
5093 #ifdef HAVE_BPF_IMAGE
5094 case 'd': /* Print BPF code for capture filter and exit */
5095 if (!print_bpf_code) {
5096 print_bpf_code = TRUE;
5101 case 'S': /* Print interface statistics once a second */
5102 if (!print_statistics) {
5103 print_statistics = TRUE;
5107 case 'k': /* Set wireless channel */
5110 set_chan_arg = optarg;
5113 cmdarg_err("Only one -k flag may be specified");
5117 case 'M': /* For -D, -L, and -S, print machine-readable output */
5118 machine_readable = TRUE;
5121 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
5124 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
5127 cmdarg_err("Invalid Option: %s", argv[optind-1]);
5129 case '?': /* Bad flag - print usage message */
5138 /* user specified file name as regular command-line argument */
5139 /* XXX - use it as the capture file name (or something else)? */
5145 * Extra command line arguments were specified; complain.
5146 * XXX - interpret as capture filter, as tcpdump and tshark do?
5148 cmdarg_err("Invalid argument: %s", argv[0]);
5153 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
5156 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
5157 /* Use some default if the user hasn't specified some */
5158 /* XXX: Are these defaults good enough? */
5159 pcap_queue_byte_limit = 1000 * 1000;
5160 pcap_queue_packet_limit = 1000;
5163 print_usage(stderr);
5167 if (run_once_args > 1) {
5168 #ifdef HAVE_BPF_IMAGE
5169 cmdarg_err("Only one of -D, -L, -d, -k or -S may be supplied.");
5171 cmdarg_err("Only one of -D, -L, -k or -S may be supplied.");
5174 } else if (run_once_args == 1) {
5175 /* We're supposed to print some information, rather than
5176 to capture traffic; did they specify a ring buffer option? */
5177 if (global_capture_opts.multi_files_on) {
5178 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
5182 /* We're supposed to capture traffic; */
5184 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
5185 if (global_capture_opts.ifaces->len > 1) {
5187 global_capture_opts.use_pcapng = TRUE;
5190 if (global_capture_opts.capture_comment &&
5191 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
5192 /* XXX - for ringbuffer, should we apply the comment to each file? */
5193 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
5197 /* Was the ring buffer option specified and, if so, does it make sense? */
5198 if (global_capture_opts.multi_files_on) {
5199 /* Ring buffer works only under certain conditions:
5200 a) ring buffer does not work with temporary files;
5201 b) it makes no sense to enable the ring buffer if the maximum
5202 file size is set to "infinite". */
5203 if (global_capture_opts.save_file == NULL) {
5204 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
5205 global_capture_opts.multi_files_on = FALSE;
5207 if (!global_capture_opts.has_autostop_filesize &&
5208 !global_capture_opts.has_file_duration &&
5209 !global_capture_opts.has_file_interval &&
5210 !global_capture_opts.has_file_packets) {
5211 cmdarg_err("Ring buffer requested, but no maximum capture file size, duration "
5212 "interval, or packets were specified.");
5214 /* XXX - this must be redesigned as the conditions changed */
5215 global_capture_opts.multi_files_on = FALSE;
5218 if (global_capture_opts.has_file_duration && global_capture_opts.has_file_interval) {
5219 cmdarg_err("Ring buffer file duration and interval can't be used at the same time.");
5226 * "-D" requires no interface to be selected; it's supposed to list
5229 if (list_interfaces) {
5230 /* Get the list of interfaces */
5235 if_list = capture_interface_list(&err, &err_str, NULL);
5236 if (if_list == NULL) {
5239 * If we're being run by another program, just give them
5240 * an empty list of interfaces, don't report this as
5241 * an error; that lets them decide whether to report
5242 * this as an error or not.
5244 if (!machine_readable) {
5245 cmdarg_err("There are no interfaces on which a capture can be done");
5249 cmdarg_err("%s", err_str);
5255 if (machine_readable) /* tab-separated values to stdout */
5256 print_machine_readable_interfaces(if_list);
5258 capture_opts_print_interfaces(if_list);
5259 free_interface_list(if_list);
5264 * "-S" requires no interface to be selected; it gives statistics
5265 * for all interfaces.
5267 if (print_statistics) {
5268 status = print_statistics_loop(machine_readable);
5273 interface_options *interface_opts;
5275 if (global_capture_opts.ifaces->len != 1) {
5276 cmdarg_err("Need one interface");
5280 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
5281 status = set_80211_channel(interface_opts->name, set_chan_arg);
5286 * "-L", "-d", and capturing act on a particular interface, so we have to
5287 * have an interface; if none was specified, pick a default.
5289 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
5291 /* cmdarg_err() already called .... */
5296 /* Get the list of link-layer and/or timestamp types for the capture device. */
5297 if_capabilities_t *caps;
5298 cap_device_open_err err;
5302 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
5303 int if_caps_queries = caps_queries;
5304 interface_options *interface_opts;
5306 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, ii);
5308 caps = get_if_capabilities(interface_opts, &err, &err_str);
5310 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
5311 "%s", interface_opts->name, err_str,
5312 get_pcap_failure_secondary_error_message(err, err_str));
5316 if ((if_caps_queries & CAPS_QUERY_LINK_TYPES) && caps->data_link_types == NULL) {
5317 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts->name);
5319 } /* No timestamp types is no big deal. So we will just ignore it */
5321 if (interface_opts->monitor_mode)
5322 if_caps_queries |= CAPS_MONITOR_MODE;
5324 if (machine_readable) /* tab-separated values to stdout */
5325 /* XXX: We need to change the format and adapt consumers */
5326 print_machine_readable_if_capabilities(caps, if_caps_queries);
5328 /* XXX: We might want to print also the interface name */
5329 capture_opts_print_if_capabilities(caps, interface_opts->name, if_caps_queries);
5330 free_if_capabilities(caps);
5335 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
5336 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5337 interface_options *interface_opts;
5339 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5340 if (interface_opts->timestamp_type) {
5341 interface_opts->timestamp_type_id = pcap_tstamp_type_name_to_val(interface_opts->timestamp_type);
5342 if (interface_opts->timestamp_type_id < 0) {
5343 cmdarg_err("Invalid argument to option: --time-stamp-type=%s", interface_opts->timestamp_type);
5350 /* We're supposed to do a capture, or print the BPF code for a filter. */
5352 /* Let the user know what interfaces were chosen. */
5353 if (capture_child) {
5354 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5355 interface_options *interface_opts;
5357 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5358 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
5359 interface_opts->name);
5362 str = g_string_new("");
5364 if (global_capture_opts.ifaces->len < 2)
5366 if (global_capture_opts.ifaces->len < 4)
5369 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5370 interface_options *interface_opts;
5372 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5374 if (global_capture_opts.ifaces->len > 2) {
5375 g_string_append_printf(str, ",");
5377 g_string_append_printf(str, " ");
5378 if (j == global_capture_opts.ifaces->len - 1) {
5379 g_string_append_printf(str, "and ");
5382 g_string_append_printf(str, "'%s'", interface_opts->display_name);
5385 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
5387 fprintf(stderr, "Capturing on %s\n", str->str);
5388 g_string_free(str, TRUE);
5391 /* Process the snapshot length, as that affects the generated BPF code. */
5392 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
5394 #ifdef HAVE_BPF_IMAGE
5395 if (print_bpf_code) {
5396 show_filter_code(&global_capture_opts);
5401 /* We're supposed to do a capture. Process the ring buffer arguments. */
5402 capture_opts_trim_ring_num_files(&global_capture_opts);
5404 /* flush stderr prior to starting the main capture loop */
5407 /* Now start the capture. */
5408 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
5412 /* capture failed */
5415 return 0; /* never here, make compiler happy */
5419 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
5420 const char *message, gpointer user_data _U_)
5427 /* ignore log message, if log_level isn't interesting */
5428 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5429 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
5434 switch(log_level & G_LOG_LEVEL_MASK) {
5435 case G_LOG_LEVEL_ERROR:
5438 case G_LOG_LEVEL_CRITICAL:
5441 case G_LOG_LEVEL_WARNING:
5444 case G_LOG_LEVEL_MESSAGE:
5447 case G_LOG_LEVEL_INFO:
5450 case G_LOG_LEVEL_DEBUG:
5454 fprintf(stderr, "unknown log_level %d\n", log_level);
5456 g_assert_not_reached();
5459 /* Generate the output message */
5460 if (log_level & G_LOG_LEVEL_MESSAGE) {
5461 /* normal user messages without additional infos */
5462 msg = g_strdup_printf("%s\n", message);
5464 /* create a "timestamp" */
5466 today = localtime(&curr);
5468 /* info/debug messages with additional infos */
5470 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
5471 today->tm_hour, today->tm_min, today->tm_sec,
5472 log_domain != NULL ? log_domain : "",
5475 msg = g_strdup_printf("Time not representable %8s %s %s\n",
5476 log_domain != NULL ? log_domain : "",
5480 /* DEBUG & INFO msgs (if we're debugging today) */
5481 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
5482 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5483 #ifdef DEBUG_DUMPCAP
5484 fprintf(stderr, "%s", msg);
5487 #ifdef DEBUG_CHILD_DUMPCAP
5488 fprintf(debug_log, "%s", msg);
5496 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
5497 /* to parent especially formatted if dumpcap running as child. */
5498 if (capture_child) {
5499 sync_pipe_errmsg_to_parent(2, msg, "");
5501 fprintf(stderr, "%s", msg);
5508 /****************************************************************************************************************/
5509 /* indication report routines */
5513 report_packet_count(unsigned int packet_count)
5515 char count_str[SP_DECISIZE+1+1];
5516 static unsigned int count = 0;
5518 if (capture_child) {
5519 g_snprintf(count_str, sizeof(count_str), "%u", packet_count);
5520 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", count_str);
5521 pipe_write_block(2, SP_PACKET_COUNT, count_str);
5523 count += packet_count;
5524 fprintf(stderr, "\rPackets: %u ", count);
5525 /* stderr could be line buffered */
5531 report_new_capture_file(const char *filename)
5533 if (capture_child) {
5534 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
5535 pipe_write_block(2, SP_FILE, filename);
5539 * Prevent a SIGINFO handler from writing to the standard error
5540 * while we're doing so; instead, have it just set a flag telling
5541 * us to print that information when we're done.
5544 #endif /* SIGINFO */
5545 fprintf(stderr, "File: %s\n", filename);
5546 /* stderr could be line buffered */
5551 * Allow SIGINFO handlers to write.
5556 * If a SIGINFO handler asked us to write out capture counts, do so.
5559 report_counts_for_siginfo();
5560 #endif /* SIGINFO */
5565 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5567 interface_options *interface_opts;
5568 char tmp[MSG_MAX_LENGTH+1+6];
5570 if (i < capture_opts->ifaces->len) {
5571 if (capture_child) {
5572 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5573 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5574 pipe_write_block(2, SP_BAD_FILTER, tmp);
5577 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5578 * the error message below.
5580 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
5582 "Invalid capture filter \"%s\" for interface '%s'.\n"
5584 "That string isn't a valid capture filter (%s).\n"
5585 "See the User's Guide for a description of the capture filter syntax.",
5586 interface_opts->cfilter, interface_opts->name, errmsg);
5592 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5594 if (capture_child) {
5595 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5596 "Primary Error: %s", error_msg);
5597 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5598 "Secondary Error: %s", secondary_error_msg);
5599 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5601 cmdarg_err("%s", error_msg);
5602 if (secondary_error_msg[0] != '\0')
5603 cmdarg_err_cont("%s", secondary_error_msg);
5608 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
5610 guint32 total_drops = pcap_drops + drops + flushed;
5612 if (capture_child) {
5613 char* tmp = g_strdup_printf("%u:%s", total_drops, name);
5615 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5616 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5617 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
5618 pipe_write_block(2, SP_DROPS, tmp);
5622 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5623 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
5624 received ? 100.0 * received / (received + total_drops) : 0.0);
5625 /* stderr could be line buffered */
5631 /************************************************************************************************/
5632 /* signal_pipe handling */
5637 signal_pipe_check_running(void)
5639 /* any news from our parent? -> just stop the capture */
5643 /* if we are running standalone, no check required */
5644 if (!capture_child) {
5648 if (!sig_pipe_name || !sig_pipe_handle) {
5649 /* This shouldn't happen */
5650 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5651 "Signal pipe: No name or handle");
5656 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5657 * at this point. Should we check to see if the parent is still alive,
5658 * e.g. by using OpenProcess?
5661 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5663 if (!result || avail > 0) {
5664 /* peek failed or some bytes really available */
5665 /* (if not piping from stdin this would fail) */
5666 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5667 "Signal pipe: Stop capture: %s", sig_pipe_name);
5668 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5669 "Signal pipe: %s (%p) result: %u avail: %lu", sig_pipe_name,
5670 sig_pipe_handle, result, avail);
5673 /* pipe ok and no bytes available */
5680 * Editor modelines - https://www.wireshark.org/tools/modelines.html
5685 * indent-tabs-mode: nil
5688 * vi: set shiftwidth=4 tabstop=8 expandtab:
5689 * :indentSize=4:tabSize=8:noTabs=true: